Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is there any way to run the .NET exe (of a winform app) in Linux **without building the code in linux?** In fact I don't have the code for some of the utilities I developed earlier and would like to run them in linux. Related to : [Feasibility of C# development with Mono](https://stackoverflow.com/questions/797093/feasibility-of-c-development-with-mono)
Mono ! <http://mono-project.com/Main_Page> Works great too. There's a growing tool support, C# compiler etc in a growing community.
You can test it by using the Mono Migration Analyzer or by actually testing it using the Mono command prompt...covered in this [article](http://mono-project.com/Guide:_Porting_Winforms_Applications)
Run .NET exe in linux
[ "", "c#", ".net", "linux", "" ]
I seem to be having a very frustrating time with an inherited class calling an explicit superclass constructor. I just can't seem to get the syntax right! All the examples I have seen on the matter so far do not separate out the header and in-line class definition (using {}'s) from forward-declarations with a header file, so I'm not sure of how to cover the syntax between the .h and .cc files. Any help would be appreciated! Here is the error the compiler gives me (gcc) : > serverconnection.h: In > constructor > "ServerConnection::ServerConnection(std::string, > std::string)": serverconnection.h:25: > error: expected `{' at end of input > serverconnection.cc: At global scope: > serverconnection.cc:20: error: > redefinition of > "ServerConnection::ServerConnection(std::string, > unsigned int, short unsigned int, > PacketSender\*, int)" > serverconnection.h:25: error: > "ServerConnection::ServerConnection(std::string, > unsigned int, short unsigned int, > PacketSender\*, int)" previously > defined here serverconnection.cc: In > constructor > "ServerConnection::ServerConnection(std::string, > std::string)": serverconnection.cc:20: > error: no matching function for call > to "Connection::Connection()" I understand that it is trying to call the default Connection constructor, Connection(), as it just doesn't understand my syntax. Here is the code: connection.h : ``` class Connection { public: Connection(string myOwnArg); }; ``` connection.cc : ``` #include "connection.h" Connection::Connection(string myOwnArg) { //do my constructor stuff } ``` serverconnection.h : ``` #include "connection.h" class ServerConnection : public Connection { public: ServerConnection(string myOwnArg, string superClassArg) : Connection(superClassArg); }; ``` serverconnection.cc : ``` #include "serverconnection.h" #include "connection.h" ServerConnection::ServerConnection(string myOwnArg, string superClassArg) { //do my constructor stuff } ``` Thanks so much in advance!
You don't put the initializer list in the class declaration, but in the function defininition. Remove it from the header, and in your .cc file: ``` #include "serverconnection.h" #include "connection.h" ServerConnection::ServerConnection(string myOwnArg, string superClassArg) : Connection(superClassArg) { //do my constructor stuff } ```
You need to move the base class initializer list from serverconnection.h to server connection.cc: ``` ServerConnection::ServerConnection(string myOwnArg, string superClassArg) : Connection(superClassArg) { //do my constructor stuff } ``` And just declare the ServerConneciton constructor without any decoration in the header.
C++ Explicit Superclass Constructor Problem While Using Header Files
[ "", "c++", "c", "constructor", "super", "" ]
I know that exceptions have a performance penalty, and that it's generally more efficient to try and avoid exceptions than to drop a big try/catch around everything -- but what about the try block itself? What's the cost of merely declaring a try/catch, even if it never throws an exception?
The performance cost of try is very small. The major cost of exception handling is getting the stack trace and other metadata, and that's a cost that's not paid until you actually have to throw an exception. But this will vary by language and implementation. Why not write a simple loop in C# and time it yourself?
Actually, a couple months ago I was creating an ASP.NET web app, and I accidentally wrapped a try / catch block with a very long loop. Even though the loop wasn't generating every exceptions, it was taking too much time to finish. When I went back and saw the try / catch wrapped by the loop, I did it the other way around, I wrapped the loop IN the try / catch block. Performance improved a LOT. You can try this on your own: do something like ``` int total; DateTime startTime = DateTime.Now; for(int i = 0; i < 20000; i++) { try { total += i; } catch { // nothing to catch; } } Console.Write((DateTime.Now - startTime).ToString()); ``` And then take out the try / catch block. You'll see a big difference!
Performance Cost Of 'try' in C#
[ "", "c#", "exception", "" ]
In implementing a basic Scheme interpreter in C# I discovered, to my horror, the following problem: IEnumerator doesn't have a clone method! (or more precisely, IEnumerable can't provide me with a "cloneable" enumerator). What I'd like: ``` interface IEnumerator<T> { bool MoveNext(); T Current { get; } void Reset(); // NEW! IEnumerator<T> Clone(); } ``` I cannot come up with an implementation of IEnumerable that would not be able to supply an efficiently cloneable IEnumerator (vectors, linked lists, etc. all would be able to provide a trivial implementation of IEnumerator's Clone() as specified above... it would be easier than providing a Reset() method anyway!). The absence of the Clone method means that any functional/recursive idiom of enumerating over a sequence won't work. It also means I can't "seamlessly" make IEnumerable's behave like Lisp "lists" (for which you use car/cdr to enumerate recursively). i.e. the only implemention of "(cdr *some IEnumerable*)" would be woefully inefficient. **Can anyone suggest a realistic, useful, example of an IEnumerable object that wouldn't be able to provide an efficient "Clone()" method? Is it that there'd be a problem with the "yield" construct?** Can anyone suggest a workaround?
The logic is inexorable! `IEnumerable` doesn't support `Clone`, and you need `Clone`, so you shouldn't be using `IEnumerable`. Or more accurately, you shouldn't be using it as the fundamental basis for work on a Scheme interpreter. Why not make a trivial immutable linked list instead? ``` public class Link<TValue> { private readonly TValue value; private readonly Link<TValue> next; public Link(TValue value, Link<TValue> next) { this.value = value; this.next = next; } public TValue Value { get { return value; } } public Link<TValue> Next { get { return next; } } public IEnumerable<TValue> ToEnumerable() { for (Link<TValue> v = this; v != null; v = v.next) yield return v.value; } } ``` Note that the `ToEnumerable` method gives you convenient usage in the standard C# way. To answer your question: > Can anyone suggest a realistic, > useful, example of an IEnumerable > object that wouldn't be able to > provide an efficient "Clone()" method? > Is it that there'd be a problem with > the "yield" construct? An IEnumerable can go anywhere in the world for its data. Here's an example that reads lines from the console: ``` IEnumerable<string> GetConsoleLines() { for (; ;) yield return Console.ReadLine(); } ``` There are two problems with this: firstly, a `Clone` function would not be particularly straightforward to write (and `Reset` would be meaningless). Secondly, the sequence is infinite - which is perfectly allowable. Sequences are lazy. Another example: ``` IEnumerable<int> GetIntegers() { for (int n = 0; ; n++) yield return n; } ``` For both these examples, the "workaround" you've accepted would not be much use, because it would just exhaust the available memory or hang up forever. But these are perfectly valid examples of sequences. To understand C# and F# sequences, you need to look at lists in Haskell, not lists in Scheme. In case you think the infinite stuff is a red herring, how about reading the bytes from a socket: ``` IEnumerable<byte> GetSocketBytes(Socket s) { byte[] buffer = new bytes[100]; for (;;) { int r = s.Receive(buffer); if (r == 0) yield break; for (int n = 0; n < r; n++) yield return buffer[n]; } } ``` If there is some number of bytes being sent down the socket, this will not be an infinite sequence. And yet writing Clone for it would be very difficult. How would the compiler generate the IEnumerable implementation to do it automatically? As soon as there was a Clone created, both instances would now have to work from a buffer system that they shared. It's possible, but in practice it isn't needed - this isn't how these kinds of sequences are designed to be used. You treat them purely "functionally", like values, applying filters to them recursively, rather than "imperatively" remembering a location within the sequence. It's a little cleaner than low-level `car`/`cdr` manipulation. **Further question:** > I wonder, what's the lowest level > "primitive(s)" I would need such that > anything I might want to do with an > IEnumerable in my Scheme interpreter > could be implemented in scheme rather > than as a builtin. The short answer I think would be to look in [Abelson and Sussman](http://mitpress.mit.edu/sicp/full-text/book/book.html) and in particular [the part about streams](http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#%_sec_3.5). `IEnumerable` is a stream, not a list. And they describe how you need special versions of map, filter, accumulate, etc. to work with them. They also get onto the idea of unifying lists and streams in section 4.2.
As a workaround, you could easily make an extension method for IEnumerator which did your cloning. Just create a list from the enumerator, and use the elements as members. You'd lose the streaming capabilities of an enumerator, though - since you're new "clone" would cause the first enumerator to fully evaluate.
Why can't IEnumerator's be cloned?
[ "", "c#", ".net", "ienumerable", "" ]
I am trying to decypher an absolute monstrosity of a stored procedure and i'm not having much luck. Are there any free tools that will help visualise the query or at least format the syntax into a more readable format ? Any hints and tips are also welcome. The type of database i am using is MS sql server 2005
Often it can help to run the individual parts of the stored procedure manually. It takes some work, but will likely help. Start by making the stored procedure into a standard sql by removing the sproc declaration and declaring and initializing each needed parameter. Run an incrementally bigger part of the sproc, and inspect the results to understand what happens. Do this by printing variables or temp tables, or just by modifying output to the screen rather than a temp source. And do make sure you document/split/rewrite what you find in the end - you don't want anyone else to have to do the same, right?
Find all of the tables which are being used and draw yourself an ERD to better understand.
A better way to understand stored procedures
[ "", "sql", "sql-server-2005", "stored-procedures", "" ]
I don't really know how to explain this in a understandable way but here goes. The project I'm working on is a web application that revolves around courses, and each course have a set of prerequisites, the problem is that I don't know a good way to present these for the user. Example: To take course4, the person must have sold at least 600 products AND worked at least 90 days. She must also complete (Course1 OR Course2) AND Course 3. Any ideas on how I should present this for the users in a simple way for them to understand. And how would I then go about and save it. The project is being built in php for the back, html/jquery for the front and mysql as the storage. /S
It sounds like you just need the UI help, right? My university always did something like a list: * One of: Course A, Course B, Course C * Course D * Course E Then you could add some nice classes to the list items for missing/completed requirements: ``` <ul class="prerequisites"> <li class="complete">One of: <a href="courseA">Course A</a>, <a href="courseB" class="complete">Course B</a>, <a href="courseC">Course C</a></li> <li class="complete"><a href="courseD" class="complete">Course D</a></li> <li><a href="courseE">Course E</a></li> </ul> ``` With some CSS doing things like... ``` ul.prerequisites { list-style-type: none; } ul.prerequisites li { background-image: url(images/incomplete.gif); /* a red X maybe? */ padding-left: 14px; } ul.prerequisites li.complete { background-image: url(images/complete.gif); /* maybe a green check */ } ul.prerequisites li a.complete { text-decoration: line-through; } ```
Another option would be to let the user select/enter the things they have done, eg. Type in how many products they have sold and how many days they have worked and select check boxes for the courses they have completed. Once you have that you can display which courses are available to them and possibly show what they need to do to qualify for the other ones
Need a way to present a prerequisites for an object
[ "", "php", "jquery", "mysql", "user-interface", "" ]
I am trying to call the "Run" function in a new thread. Right now, I have this code using openMP that doesn't actually run "Run" in a new thread. NOTE: I am not asking for help using OpenMP. This code was just a quick fix. I would prefer a CreateThread() method of going about this. ``` vector<ICommand*>* commands; string strInput; // For each command... for(vector<ICommand*>::iterator i = commands->begin(); i != commands->end(); ++i) { // ...if the current command we're examining is valid... if((*i)->ContainsCommand(strInput)) { // ...run it in a new thread and don't let ZChatInput handle it normally... #pragma omp sections nowait { #pragma omp section (*i)->Run(strInput); #pragma omp section bRet = false; } // ...and don't check any more commands. break; } } ``` So how would this be done using just standard and STL? Of course, I'm looking for a way that works :)
So I figured it out after double-checking the MSDN documentation. Here's how I did it, in case any of you are interested: ``` static vector<ICommand*>* commands; // This is what we pass to CommandOnThread. struct CommandParameter { string strInput; ICommand* command; }; int CommandOnThread(CommandParameter* cp) { cp->command->Run(cp->strInput); delete cp; return 0; } void foo() { string strInput; ... // For each command... for(vector<ICommand*>::iterator i = commands->begin(); i != commands->end(); ++i) { // ...if the current command we're examining is valid... if((*i)->ContainsCommand(strInput)) { // Put the CP on the stack. CommandParameter* temp = new CommandParameter; if(temp == NULL) { Print("Out of memory!"); bRet = false; break; } // ...set up the parameters to createthread... temp->strInput = strInput; temp->command = *i; // ...run it in a new thread... CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CommandOnThread, temp, NULL, NULL); // ...and don't check any more commands. bRet = false; break; } } } ```
How about using Boost.Thread? ``` if((*i)->ContainsCommand(strInput)) { boost::thread t( boost::bind( &ICommand::Run, *i ) ); } ``` This will run "Run" in a detached thread. (Note, I did not test this.)
Multithreading with Inheritance (C++)
[ "", "c++", "multithreading", "inheritance", "" ]
there is an **immutable** class: ``` Scope<Cmp extends Comparable<Cmp>> public Scope<Cmp> crop(Scope<Cmp> scope) { ... return new Scope<Cmp>(starts, ends); } ``` it has **many** similar methods is extended by: ``` Timerange extends Scope<Date> ``` and **many** others (also immutable). Id like them to return object of its type. For example: ``` timerange.crop(scope) ``` should return Timerange object, not Scope. Do I have to override every method (or use reflection)? Is there another way of doing this? Thanks in advance, Etam.
You need some kind of factory. In this case factory method works fine. ``` public abstract class Scope<E extends Comparable<E>> { abstract Scope<E> create(E start, E end); public Scope<E> crop(Scope<E> scope) { ... return create(starts, ends); } } public TimeRange extends Scope<Date> { Scope<Date> create(Date start, Date end) { return new TimeRange (...); } } ``` You may want to add a generic 'this' parameter to the base class: ``` public abstract class Scope<THIS extends Scope<THIS, E>, E extend Comparable<E>> { abstract THIS create(E start, E end); public THIS crop(Scope<E> scope) { ... return create(starts, ends); } } public TimeRange extends Scope<TimeRange,Date> { TimeRange create(Date start, Date end) { return new TimeRange (...); } } ``` This does add extra work to the client code.
You could try the following: ``` class Scope<Cpm extends Comparable<Cpm>, Derived extends Scope<Cpm, Derived>> { public Derived crop(Scope<Cmp, Derived> scope) } ``` TimeRange would be defined as ``` class TimeRange extends Scope<Date, Timerange> ``` and so `crop` would return a TimeRange object. When the deriving class is undefined, you can use generic wildcards (`Scope<Date, ?>`)
Generic return
[ "", "java", "generics", "polymorphism", "return", "" ]
I'm developing an ASP.NET app (C#) that connect to SQL Server 2008 using ADO.NET entity framework. The user of this app can select an image from his local hard drive to insert in SQL Server. How can I do this? I know how to store the image into SQL Server but I don't know how to upload the image to the server (using FileUpload server control?). Thank you!
For storing uploaded file to SQL server you can look at this answer of mine : [How do you store a picture in an image column?](https://stackoverflow.com/questions/744589/how-do-you-store-a-picture-in-an-image-column/744603#744603) In this example, **uploadInput** is a file input control, you can use it as FileUpload control in ASP.NET. For using File upload Control in ASP.NET [here is a good MSDN article](http://msdn.microsoft.com/en-us/library/aa479405.aspx).
Well, to upload to the web-server you just need an `<input type="file" .../>`. At ASP.NET, this should be available in the [`Request.Files`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.files.aspx) collection. In SQL Server, you'll want a `varbinary(max)` (or `image` in older versions). The big question before pushing them into SQL Server is: how big are they? If they aren't massive, you can just treat them as a `byte[]`; just buffer from the [`InputStream`](http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream.aspx) and send. Here's a fairly generic way of buffering a `Stream` to a single `byte[]`: ``` byte[] buffer = new byte[1024]; int bytesRead; MemoryStream ms = new MemoryStream(); while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, bytesRead); } byte[] data = ms.ToArray(); ``` For massive files (which perhaps don't belong in the db unless you are using the SQL 2008 filestream extensions), you'll want to chunk it. [Here's an old reply](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/6c9e5e75ae39826b#998c53ff8afb02eb) I used for chunking (before SQL 2005) - but it shows the overall idea.
How can I insert a file in SQL Server using ASP.Net?
[ "", "c#", "asp.net", "upload", "" ]
I wrote a program that forks some processes with fork(). I want to kill all child- and the mother process if there is an error. If I use exit(EXIT\_FAILURE) only the child process is killed. I am thinking about a system("killall [program\_name]") but there must be a better way... Thank you all! Lennart
Under UNIX, send SIGTERM, or SIGABRT, or SIGPIPE or sth. alike to the mother process. This signal will then be propagated to all clients automatically, if they do not explicitely block or ignore it. Use `getppid()` to get the PID to send the signal to, and `kill()` to send the signal. > getppid() returns the process ID of > the parent of the calling process. > > The kill() system call can be used to send any signal to any process group or process. Remarks: 1. Using `system` is evil. Use internal functions to send signals. 2. `killall` would be even more evil. Consider several instances of your program running at once.
See [How to make child process die after parent exits?](https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits) On Linux there's a `prctl()` call which is explicitly designed to send a signal to all of a process's children when the parent dies *for whatever reason*. I need to check and can't do it where I am at the second, but I'm really not sure that ypnos' assertion about `SIGPIPE`, `SIGTERM` and `SIGABRT` being propagated to all children is correct. However if you use `kill(-ppid)` (note the minus sign) then so long as the children are still in the parent process's process group then the kernel will deliver any signal to all of the children.
How can I kill all processes of a program?
[ "", "c++", "linux", "process", "kill", "" ]
Is there a managed system-level sequential number generator? DateTime.Now.Ticks won't do because the operations I'm doing sometimes occur more than once per tick. --- **Requirement Clarifications:** * Process agnostic - there's really only one process that would be accessing this. * Performance is critical! This is used for logging impressions on an adserver, which can reach 1k/sec It would need to be one of the following: * A 4-byte sequential number that resets every tick * A 12-byte sequential number - essentially adding 4 bytes of granularity to a DateTime
None that are intended for this, but you could use [System.Diagnostics.PerformanceCounter](http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx). You could also use the Registry but you'd need to serialize read/write access accross the processes. ``` System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("SeqCounter", "SeqInstance"); long myVal=pc.Increment(); ``` # Edit The more I think about this, I think this could be a nice solution. Increment will increase the counter by 1 through an atomic operation which should work accross all processes on a system. # Edit Based on your edits, I would not recommend using a performance counter. A performance counter was a way to cordinate accross multiple processes. I am not sure how the internal implemention is coded. Why can't you just use a static variable and increment it? Your going to have to lock something if you want this to be threadsafe. [System.Threading.Interlocked.Increment](http://msdn.microsoft.com/en-us/library/dd78zt0c.aspx) FYI: If you use the long version on a 32 bit system it won't nessecarilly be thread safe. --- Editing to show the implemention I used (DS): ``` public static class Int32Sequencer { private static Int32 lastSequence = Int32.MinValue; private static Object lockObject = new Object(); public static Int32 GetNextSequence() { lock (lockObject) { unchecked { lastSequence++; } return lastSequence; } } } ```
A Guid is as close as you're going to get, but those are "unique" and not necessarily sequential. If you really want sequential across multiple processes at the system level, you will probably have to roll your own. EDIT: Ok, so from your new requirements, I'm going to assume: 1. Only one process needs to do the work 2. You are appending to a database So here is what I would recommend: 1. At the process start-up, query the DB for the last (greatest) value (0 if none exist). 2. Use a simple long and increment for each DB row. You are going to want to insert in batches due to your high data rate. That should do it. Keep it simple. This has no locks, a slight (negligible) hit at start-up, and sequential numbers in your DB. This algorithm is also process-agnotic as long you only have one process running it.
Windows/C# system-level sequential number generator?
[ "", "c#", "sequence", "sequential-number", "" ]
In Java, do class objects have the same heritance relations as the classes they represent?
The `.class` property always returns a `Class` object. The `Class` class (weird) has a generic parameter. The generic parameter types are subclasses. ``` Class<String> stringClass = String.class; Class<Object> objectClass = Object.class; ``` And because with generics, `Type<foo>` is *NOT* a supertype of `Type<subtype_of_foo>` (see [the Java tutorials](http://java.sun.com/docs/books/tutorial/java/generics/subtyping.html)), this means, that the answer is "No".
`Class` objects in Java are all same Class. You can tell because if you look at the Javadoc you can see that the [`Class` class is `final`.](http://java.sun.com/javase/6/docs/api/java/lang/Class.html)
Is (the type of) String.class a subtype of (the type of) Object.class?
[ "", "java", "inheritance", "" ]
I have this following IEnumerable LINQ query: ``` var query = from p in Enumerable.Range(2, 1000000) let sumofPowers = from ch in p.ToString() let sumOfPowers = Math.Pow(Convert.ToDouble(ch.ToString()), 5) select sumOfPowers where p == sumofPowers.Sum() select p; ``` It finds the sum of all the numbers that can be written as the sum of fifth powers of their digits. It is the Project Euler [Problem 30](https://projecteuler.net/problem=30) It works fine as it is. I know it is nitpick, but the range annoys me. I have basically guessed that it has found the correct result at 1,000,000, so I let it stop there. In this scenario, the number was sufficient. But it is just a hardcoded "random" number. If you look at the code, you find that as soon as where `p == sumofPowers.Sum()` is true, **you don't really need to run through the loop anymore.** I know `yield` can do it in under other situations and `break` works in normal loops - so is there anything you can do in this situation?
You can use the First() operator to break out. Since LINQ does deferred calculation, this will go until you reach the point where p == sumofPowers.Sum(), and then return the first element. Just wrap the entire query in (...).First(); to return the first value. Also, while you're at it, there is no need to convert to a string then to a double - you can convert directly from int -> double, and avoid the string conversions.
``` class Program { static void Main(string[] args) { ulong sum, gh = 0; for (ulong i = 2; i <= 355000; i++) { string s = Convert.ToString(i); sum = 0; int ddd = s.Length; for (int j = 0; j < ddd; j++) { //sum +=(int)Math.Pow(Convert.ToInt32(s[j]), 4); ulong g = Convert.ToUInt64(Convert.ToString(s[j])); sum = sum + (ulong)Math.Pow(g, 5); } // Console.WriteLine(sum); if (sum == i) { gh += i; } } Console.WriteLine(gh); Console.ReadKey(); } } ```
break an IEnumerable<int> query which uses Enumerable.Range
[ "", "c#", "linq", "range", "ienumerable", "" ]
The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID. I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id? I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
``` $link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db'); mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')"); $id = mysqli_insert_id($link); ``` See [`mysqli_insert_id()`](http://au.php.net/mysqli.insert_id). Whatever you do, don't insert and then do a "`SELECT MAX(id) FROM mytable`". Like you say, it's a race condition and there's no need. `mysqli_insert_id()` already has this functionality. --- Another way would be to run both queries in one go, and using `MySQL`'s `LAST_INSERT_ID()` method, where both tables get modified at once (and PHP does not need any ID), like: ``` mysqli_query($link, "INSERT INTO my_user_table ...; INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())"); ``` > **Note** that Each connection keeps track of ID separately (so, conflicts are prevented already).
The MySQL function [`LAST_INSERT_ID()`](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id) does just what you need: it retrieves the id that was inserted during *this session*. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table. The PHP function [`mysql_insert_id()`](http://de.php.net/manual/en/function.mysql-insert-id.php) does the same as calling `SELECT LAST_INSERT_ID()` with `mysql_query()`.
PHP/MySQL insert row then get 'id'
[ "", "php", "mysql", "" ]
I have a list of callback functions that I need to invoke when an event is fired. Is this idiomatic python? ``` def first_callback(m): print 'first ' + m def second_callback(m): print 'second ' + m lst = [first_callback, second_callback] map(lambda x: x("event_info"),lst) #is this how you do it? ```
Use `map` only for functions without side effects (like `print`). That is, use it only for functions that just return something. In this case a regular loop is more idiomatic: ``` for f in lst: f("event_info") ``` **Edit**: also, as of Python 3.0, [`map`](http://docs.python.org/3.0/library/functions.html#map) returns an iterator instead of a list. Hence in Python 3.0 the code given in the question will not call *any* function, unless all elements in the generator are evaluated explicitly (e.g. by encapsulating the call to `map` inside [`list`](http://docs.python.org/3.0/library/functions.html#list)). Luckily the [2to3](http://docs.python.org/library/2to3.html) tool will warn about this: File `map.py`: ``` map(lambda x: x, range(10)) ``` `2to3-3.0 map.py` output: ``` RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma --- map.py (original) +++ map.py (refactored) @@ -1,1 +1,1 @@ -map(lambda x: x, range(10)) +list(map(lambda x: x, list(range(10)))) RefactoringTool: Files that need to be modified: RefactoringTool: map.py RefactoringTool: Warnings/messages while refactoring: RefactoringTool: ### In file map.py ### RefactoringTool: Line 1: You should use a for loop here ```
You could also write a list comprehension: ``` [f("event_info") for f in lst] ``` However, it does have the side-effect of returning a list of results.
What is the idiomatic way of invoking a list of functions in Python?
[ "", "python", "" ]
This is how I create XStream instance for XML: ``` XStream xstream = new XStream(); ``` This is for JSON: ``` private final XStream xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer writer) { return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE); } }); ``` Both of them are pretty-printing (indenting) the output. How can I ask the XStream to disable the pretty printing?
With some help from the community, I've figured out the answer. **For XML** you have to change the way how you serialize: The line: ``` xStream.toXML(o, new OutputStreamWriter(stream, encoding)); ``` changed to line ``` xStream.marshal(o, new CompactWriter(new OutputStreamWriter(stream, encoding))); ``` **For JSON** you only change the way how the XStream is created. So the initialization of the XStream is changed to: ``` private final XStream xstreamOut = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer writer) { return new JsonWriter(writer, new char[0], "", JsonWriter.DROP_ROOT_MODE); } }); ``` Note that the 4-parameter JsonWriter constructor is used.
Thanks, your posts helped!!! Here is what I use to convert to a String. ``` String strXML = ""; XStream xs = new XStream(); StringWriter sw = new StringWriter(); xs.marshal(this, new CompactWriter(sw)); strXML = sw.toString(); ```
How to disable pretty-printing(white space/newline) in XStream?
[ "", "java", "xml", "json", "xstream", "" ]
Assuming you have only the URL to a file (hosted on the same server as the app) that has been rewritten via mod\_rewrite rules. How would you read the contents of that file with PHP without having direct access to a .htaccess file or the rewrite rules used to building the original URL? I'm trying to extract all the script tags that have the "src" attribute set, retrieve the contents of the target file, merge all of them into one big javascript file, minify it and then serve that one instead. The problem is that reading all of the files via file\_get\_contents seems to slow the page down, so I was looking at alternatives and if I would be able to somehow read the files directly from the file system without having to generate other requests in the background, but to do this, I would have to find out the path to the files and some are accessed via URLs that have been rewritten.
You can't include it as if it were the original PHP, only [get the results](http://www.php.net/manual/en/features.remote-files.php "remote files") of the PHP's execution itself. If you've got fopen wrappers on, this is as easy as using [require](http://www.php.net/function.require "require"), [include](http://www.php.net/function.include "include") or [file\_get\_contents](http://www.php.net/manual/en/function.file-get-contents.php "file_get_contents") on the rewritten URL. Otherwise you have [fsockopen](http://www.php.net/manual/en/function.fsockopen.php "fsockopen") and [curl](http://www.php.net/manual/en/book.curl.php "cURL") as options to create the HTTP request for the result.
As you cannot say how the request would be handled, the only possible solution is to send a HTTP request to that server. But that would only get you the output of that file/script.
Reading rewrited (mod_rewrite) files from php
[ "", "php", "mod-rewrite", "readfile", "" ]
I'm building something similar to a price comparison site. This will be developed in ASP.NET/WebForms/C#/.NET 3.5. The site will be used by the public, so I have no control over the client side - and the application isn't so central to their lives that they'll go out of their way to make it work. I want to have a table/grid that displays products in rows, vendors in columns, and prices in the cells. Price updates will be arriving (at the server) continuously, and I'd like to "push" any updates to the clients' browsers - ideally only updating what has changed. So, if Vendor A changes their price on Product B, I'd want to immediately update the relevant cell in all the browsers that are viewing this information. I don't want to use any browser plug-ins (e.g. Silverlight). Javascript is fine. What's the best approach to take? Presumably my options are: 1) have the client page continuously poll the server for updates, locate the correct cell and update it; or 2) have the server be able to send updates to all the open browser pages which are listening for these updates. The first one would seem the most plausible, but I don't want to constrain the assembled wisdom of the SO community. I'm happy to purchase any third party components (e.g. a grid) that might help with this. I already have the DevExpress grid/ajax components if they provide anything useful.
you can possibly look at few so-called server side push technologies like - AjaxPush, Comet or even some commercial products like [kaazing gateway](http://www.kaazing.com/) & [lightstreamer](http://www.lightstreamer.com/)
I think your instinct is correct that the pull model is easier to construct. iWeasel mentioned Ajax, and I want point you to Dave Ward's post on [jQuery, Ajax and PageMethods](http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/) in Asp.Net. His blog has an excellent series that will help you achieve what you looking to do. For validation of Dave's approach, [Rick Strahl has a great article](http://www.west-wind.com/presentations/jQuery/jQueryPart2.aspx) on jQuery and Asp.net as well, and in his example he is displaying products in a grid like format. While I don't have experience with this jQuery plugin, you may want to investigate [jQuery Timer](http://jquery.offput.ca/every/) to help with your timing intervals.
How to "push" updates to individual cells in a (ASP.NET) web page table/grid?
[ "", "asp.net", "javascript", "ajax", "" ]
Is there a way to launch a C# application with the following features? 1. It determines by command-line parameters whether it is a windowed or console app 2. It doesn't show a console when it is asked to be windowed and doesn't show a GUI window when it is running from the console. For example, ``` myapp.exe /help ``` would output to stdout on the console you used, but ``` myapp.exe ``` by itself would launch my Winforms or WPF user interface. The best answers I know of so far involve having two separate exe and use IPC, but that feels really hacky. What options do I have and trade-offs can I make to get the behavior described in the example above? I'm open to ideas that are Winform-specific or WPF-specific, too.
Make the app a regular windows app, and create a console on the fly if needed. More details at [this link](http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvb/thread/875952fc-cd2c-4e74-9cf2-d38910bde613) (code below from there) ``` using System; using System.Windows.Forms; namespace WindowsApplication1 { static class Program { [STAThread] static void Main(string[] args) { if (args.Length > 0) { // Command line given, display console if ( !AttachConsole(-1) ) { // Attach to an parent process console AllocConsole(); // Alloc a new console } ConsoleMain(args); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } private static void ConsoleMain(string[] args) { Console.WriteLine("Command line = {0}", Environment.CommandLine); for (int ix = 0; ix < args.Length; ++ix) Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]); Console.ReadLine(); } [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AllocConsole(); [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AttachConsole(int pid); } } ```
I basically do that the way depicted in Eric's answer, additionally I detach the console with FreeConsole and use the SendKeys command to get the command prompt back. ``` [DllImport("kernel32.dll")] private static extern bool AllocConsole(); [DllImport("kernel32.dll")] private static extern bool AttachConsole(int pid); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeConsole(); [STAThread] static void Main(string[] args) { if (args.Length > 0 && (args[0].Equals("/?") || args[0].Equals("/help", StringComparison.OrdinalIgnoreCase))) { // get console output bool attachedToConsole = AttachConsole(-1); if (!attachedToConsole) AllocConsole(); ShowHelp(); // show help output with Console.WriteLine FreeConsole(); // detach console if (attachedToConsole) { // get command prompt back System.Windows.Forms.SendKeys.SendWait("{ENTER}"); } return; } // normal winforms code Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } ```
How do I create a C# app that decides itself whether to show as a console or windowed app?
[ "", "c#", ".net", "wpf", "winforms", "" ]
Given a function y = f(A,X): ``` unsigned long F(unsigned long A, unsigned long x) { return ((unsigned long long)A*X)%4294967295; } ``` How would I find the inverse function x = g(A,y) such that x = g(A, f(A,x)) for all values of 'x'? If f() isn't invertible for all values of 'x', what's the closest to an inverse? (F is an obsolete PRNG, and I'm trying to understand how one inverts such a function). * Updated If A is relatively prime to (2^N)-1, then g(A,Y) is just f(A-1, y). If A isn't relatively prime, then the range of y is constrained... Does g( ) still exist if restricted to that range?
You need to compute the inverse of `A mod ((2^N) - 1)`, but you might not always have an inverse given your modulus. See [this on Wolfram Alpha](http://www58.wolframalpha.com/input/?i=inverse+of+12343+mod+4294967295). Note that A = 12343 has an inverse (A^-1 = 876879007 mod 4294967295) but 12345 does not have an inverse. Thus, if A is [relatively prime](http://en.wikipedia.org/wiki/Coprime) with (2^n)-1, then you can easily create an inverse function using the [Extended Euclidean Algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm) where `g(A,y) = F(A^-1, y)`, otherwise you're out of luck. **UPDATE**: In response to your updated question, you still can't get a unique inverse in the restricted range. Even if you use CookieOfFortune's brute force solution, you'll have problems like `G(12345, F(12345, 4294967294)) == 286331152 != 4294967294`.
You need the [Extended Euclidean algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm). This gives you R and S such that ``` gcd(A,2^N-1) = R * A + S * (2^N-1). ``` If the gcd is 1 then R is the multiplicative inverse of A. Then the inverse function is ``` g(A,y) = R*y mod (2^N-1). ``` Ok, here is an **update** for the case where the G = Gcd(A, 2^N-1) is not 1. In that case ``` R*y mod (2^N-1) = R*A*x mod (2^N-1) = G*x mod (2^N-1). ``` If y was computed by the function f then y is divisible by G. Hence we can divide the equation above by G and get an equation modulo (2^N-1)/G. Thus the set of solutions is ``` x = R*y/G + k*(2^N-1)/G, where k is an arbitrary integer. ```
Inverse of A*X MOD (2^N)-1
[ "", "c++", "math", "prng", "" ]
I am new to jQuery and cannot get a selector to work using the id of the element. The code below works: ``` $(function() { /* $("#ShowBox").onclick = ShowAccessible; */ document.getElementById("ShowBox").onclick = ShowAccessible; /* $(".searchcheck").click = ShowAccessible; */ }); function ShowAccessible() { $("tr.hide").fadeOut(); } ``` However, neither of the two commented out lines work i.e. they do not apply the click event to a checkbox named "ShowBox" with a class of "searchcheck". Why is this?
JQuery uses functions rather than properties to set the handlers. ``` $("#ShowBox").click(ShowAccessible); ```
there is no onclick property for a jQuery object; when you use `$([selector])`, a jQuery object is returned, not an element. Use either ``` .click(function () { ...}); // can be an anonymous function or named function ``` or ``` .bind('click', function() { ... }); // can be an anonymous function or named function ``` like so ``` $("#ShowBox").click(ShowAccessible); $("#ShowBox").bind('click', ShowAccessible); ```
How does jQuery handle the click event?
[ "", "javascript", "jquery", "asp.net-mvc", "" ]
* All Points are Vectors, and all Vectors are Points. * All Directions are Vectors, NOT all Vectors are Directions (this shouldn't mean both way conversion shouldn't be allowed). I want to have the operators overridden once for all preferably since they're all completely identical. In C++ I can just define class Vector { float x,y,z; }, and do typedef Point = Vector, typedef Direction = Vector; In C# there is no equivalent ("using Point=Vector;" sucks as you have to place it in every single document you use, and it's not enforced by the compiler). I tried to define 3 different classes and override the operators for each, then do implicit type casting which would make the code run slower, etc. I tried defining just Vector, then Point:Vector and Direction:Vector, this way I only write the operators once but then I can't do implicit type casting Point <-> Vector or Direction <->Vector. I could simply define the Vector class and use that everywhere, but that would create ambiguity as to weather a variable is supposed to be a position in space (Point), a relative position in space (Vector) or a unit vector (Direction). For example the function: ``` Vector GetOrthogon(Vector a, Vector b) { // .... } ``` You can't know whether it's expecting any vectors or unit vectors. In C++ you could do that, so why not in C#? ***Note***: having structs instead of classes would be ideal if possible.
Mathematically, Points are Vectors. There are no absolute points in space. Points are defined as vectors from some arbitrary origin. So, I use Vectors for both points and differences between points. Because a direction is a unit vector, there's no need for a distinction there either. It's like trying to define different static types for the integer 1 and other integers. So I use vectors for both directions and differences between points. So, define a single Vector type. It'll make your life easier because you'll have fewer classes and overloaded operators/functions to write and test and will be mathematically "purer" (if that matters to you).
On a purist level, I'd argue that a `Vector` and a `Point` are *not* the same, by algebra: * `Point` + `Vector` => `Point` (translation) * `Vector` + `Vector` => `Vector` (addition) * `Point` + `Point` (not defined) I would have 2 immutable structs with implicit (where they are logically equivalent) or explicit (otherwise) conversion operators. I probably wouldn't have a `Direction` struct, though... I might have a `Direction` property on a `Vector` that scales it to unit, but that is about it... --- I've stubbed out a primitive `Vector` and `Point` to show the interactions; I haven't filled in all of `Point` (since it is simpler): ``` public struct Point { public Point(double x, double y) : this() { X = x; Y = y; } public double X { get; private set; } public double Y { get; private set; } // and more ;-p } public struct Vector : IEquatable<Vector> { public Vector(double x, double y) : this() { X = x; Y = y; } public Vector AsUnit() { if (X == 0 && Y == 0) throw new InvalidOperationException(); if (X == 0) return new Vector(0, X > 0 ? 1 : -1); if (Y == 0) return new Vector(Y > 0 ? 1 : -1, 0); double sqr = Math.Sqrt((X * X) + (Y * Y)); return new Vector(X / sqr, Y / sqr); } public double X { get; private set; } public double Y { get; private set; } public static explicit operator Point(Vector vector) { return new Point(vector.X, vector.Y); } public static explicit operator Vector(Point point) { return new Vector(point.X, point.Y); } public override string ToString() { return "(" + X.ToString() + "," + Y.ToString() + ")"; } public override int GetHashCode() { return 17 * X.GetHashCode() + Y.GetHashCode(); } public override bool Equals(object obj) { return obj == null ? false : Equals((Vector)obj); } public bool Equals(Vector vector) { return X == vector.X && Y == vector.Y; } public static bool operator ==(Vector a, Vector b) { return a.X == b.X && a.Y == b.Y; } public static bool operator !=(Vector a, Vector b) { return a.X != b.X || a.Y != b.Y; } public static Point operator +(Point point, Vector vector) { return new Point(point.X + vector.X, point.Y + vector.Y); } public static Point operator -(Point point, Vector vector) { return new Point(point.X - vector.X, point.Y - vector.Y); } public static Vector operator +(Vector a, Vector b) { return new Vector(a.X + b.X, a.Y + b.Y); } public static Vector operator -(Vector a, Vector b) { return new Vector(a.X - b.X, a.Y - b.Y); } } ```
Best Way of Implementing these 3 classes in C#: Vector, Direction (unit vector), Point
[ "", "c#", "class", "struct", "" ]
In my PHP code I have a date in my variable "$postedDate". Now I want to get the date after 7 days, 15 days, one month and 2 months have elapsed. Which date function should I use? Output date format should be in US format.
Use strtotime. ``` $newDate = strtotime('+15 days',$date) ``` $newDate will now be 15 days after $date. $date is unix time. <http://uk.php.net/strtotime>
try this ``` $date = date("Y-m-d");// current date $date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day"); $date = strtotime(date("Y-m-d", strtotime($date)) . " +1 week"); $date = strtotime(date("Y-m-d", strtotime($date)) . " +2 week"); $date = strtotime(date("Y-m-d", strtotime($date)) . " +1 month"); $date = strtotime(date("Y-m-d", strtotime($date)) . " +30 days"); ```
How can I get a date after 15 days/1 month in PHP?
[ "", "php", "date", "date-arithmetic", "" ]
How we can filter the object in List<> in C#?
Let's say we have a `List<string>` and you want only the items where the length of the string is greater than 5. The code below will return a `List<string>` with the results: ``` List<string> myList = new List<string>(); myList.Add("hello"); myList.Add("world!"); myList.Add("one"); myList.Add("large!!"); List<string> resultList = myList.FindAll(delegate(string s) { return s.Length > 5; }); ``` resultList will containt 'world!' and 'large!!'. This example uses an [anonymous method](http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx). It can also be written as: ``` List<string> myList = new List<string>(); // .. List<string> resultList = myList.FindAll(OnlyLargerThanFive); //.. private static bool OnlyLargerThanFive(string s) { return s.Length > 5; } ``` The delegate above, OnlyLargerThanFive, is also called a [Predicate](http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx).
The best solution is to use lambda: ``` List<Item> l; l.FindAll(n => n.Something == SomethingElse); ``` It may use internally foreach, but you can't really filter without iterating for whole list.
Filter List<> object without using foreach loop in C#2.0
[ "", "c#", "c#-2.0", "" ]
Okay so i have a semi weridish problem with re.sub. Take the following code: ``` import re str_to_be_subbed = r'somefile.exe -i <INPUT>' some_str = r'C:\foobar' s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed) print s ``` I would think it would give me: ``` somefile.exe -i C:\\foobar ``` But instead it gives me: ``` somefile.exe -i C:♀oobar ``` I know \f is an escape char, but even if i try to do it this way, which should escape the special characthers. Even if i do this: ``` print r'%s' % s ``` It still gives me this: ``` somefile.exe -i C:♀oobar ``` Why does it do this? And whats the best way to avoid this? Ninja Edit: If i look at the value of s it is: ``` 'somefile.exe -i C:\x0coobar' ``` Why did \f turn into \x0. Ugh. Edit: One more question, if i modify the code to this: ``` import re import os str_to_be_subbed = r'somefile.exe -i <INPUT>' some_str = os.path.abspath(r'C:\foobar') some_str s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed) print s ``` Gives me: ``` >>> import re >>> import os >>> str_to_be_subbed = r'somefile.exe -i <INPUT>' >>> some_str = os.path.abspath(r'C:\foobar') >>> some_str 'C:\\foobar' >>> s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed) >>> print s somefile.exe -i C:♀oobar ``` Now why is that. Since os.path.abspath escapes the \'s. Why does re.sub still mess up? Also this is a really small example, of this little problem that just cropped up randomly in an oldish application. I can't really go and change this to string.replace because of how its setup without spending a whole day. I am just really curious as to why it is doing this. For the above problem.
`\f` is the *form feed* character. Escape it and it works: ``` some_str = r'C:\\foobar' ``` Another solution: ``` s = re.sub(r'<INPUT>', some_str.encode("string_escape"), str_to_be_subbed) ```
Don't use regular expressions: ``` print str_to_be_subbed.replace("<INPUT>",some_str) ``` As the [documentation](http://docs.python.org/library/re.html#re.sub) says: > repl can be a string or a function; if > it is a string, any backslash escapes > in it are processed.
Regular Expression Sub Problems
[ "", "python", "regex", "" ]
C#: Which uses more memory overhead? A string or a char holding a sequence of a word? I know a char is basically an array of each char to make up a word (if more than one char), but which would ultimately cause you more memory overhead like when using a string vs. a char to hold something the length of a word?
It would depend how many times you used the thing in question. The way .Net does strings is that if you had multiple strings with the same value then that value is only stored in memory once and each string variable points to that value. However each char array used would have its own memory allocation even if the contents of the char array were identical. eg ``` //.Net Framework allocates memory space for "word" only once, all the three variables refer to this chunk of memory String s1, s2, s3; s1 = "word"; s2 = "word"; s3 = "word"; //.Net Framework allocates memory for each array char[] c1 = new char[] { 'w','o','r','d'}; char[] c2 = new char[] { 'w','o','r','d'}; char[] c3 = new char[] { 'w','o','r','d'}; ```
If you compare the memory storage of a `string` and a `char[]`, they are quite similar. They are both allocated on the heap (except literal strings which are created at compile time). They both contain a few variables (for the length and such), and a memory area containing an array of characters. However, depending on how the `string` is created, it's memory area may be larger than it's length requires, i.e. it has some unused bytes at the end of the memory area. The memory area of a `char[]` is always exactly as large as required by the data. If you for example use a StringBuilder to create a string, and the capacity is larger than it's length (but not more than twice), it returns a `string` object which contains unused bytes at the end. Example: ``` // set capacity to 8 StringBuilder s = new StringBuilder(8); // put four characters in it s.Append("Ouch"); // get the string string result = s.ToString(); ``` The `result` variable now points to a string object which has a memory area for the character data that is 16 bytes long, but only the first 10 are used (the four characters, plus an `\x0` character at the end).
C#: Which uses more memory overhead? A string or a char holding a sequence of a word?
[ "", "c#", ".net", "" ]
As the title says, is there a way to make the maximum value of a NumericUpDown control unlimited instead of having to specify a specific value its the Maximum property?
Set the NumericUpDown Maximum property to the MaxValue property of the data type it is representing.
``` NumericUpDown1.Maximum = Decimal.MaxValue; ```
Can I make the maximum value of a NumericUpDown control unlimited instead of specifying a value in its Maximum property?
[ "", "c#", ".net", "winforms", "controls", "" ]
I have some elements with (.) periods in them and I need to select them but I need some escape characters to do so I believe. How can I sure that my string that may have a period in it will be escaped properly. Something like this I guess? ``` var title = "User1.Title"; var string = //replace any periods with escape sequence? $('#'+string).show(); ``` It may have more than one (.) period, hopefully not but if I can replace all (.) periods so I can do my selection that would be great.
Do you mean this? ``` $('#'+string.replace(/\./g, "\\.")).show(); ```
You could do this... ``` $("[id="+string+"]").show(); ``` ...but the problem with this guy is that is not that fast since it will traverse the entire DOM tree looking for every guy with that id, not only one. You could also do this... ``` $('#'+string.replace(".", "\\.")).show(); ``` .. that jQuery will pre-parse that selector and use *document.getElementById* behind the scenes. You could also do this ``` $(document.getElementById(string)).show(); ``` ... wich yelds the same effect and you don't have to worry about CSS special characters. Just be careful with IE(6 and 7) and Opera wich selects elements not only by it's ID but also by it's name.
Replace any (.) periods with escape backslashes so I can select elements
[ "", "javascript", "jquery", "" ]
Ok, I have a very frustrating problem. I am parsing a webpage and need to have it execute the javascript in order to get the information I want. ``` Form f = new Form(); WebBrowser w = new WebBrowser(); w.Navigate(url); f.Controls.Add(w); f.ShowDialog(); HtmlElementCollection hc = w.Document.GetElementsByTagName("button"); ``` This works and I'm able to get the button elements fine, but then I get a popup everytime I run this. Very annoying. The popup is javascript based and I need to run Javascript to get the button element info. Here is the script for the popup. ``` <script> var evilPopup = (getCookieVar("markOpen","PromoPop") == 1); if (evilPopup != 1) { PromoPop = window.open('/browse/info.aspx?cid=36193','Advertisement', 'width=365,height=262,screenX=100,screenY=100'); if (PromoPop) { PromoPop.blur(); window.focus(); setCookieVar("markOpen","PromoPop","1"); } } </script> ``` I tried in vane to possibly add a cookie to the Forms.Webbrowser control but got frustrated and gave up. I tried setting the NoAllowNavagate property and everything else to no avail. Can anyone help? Also, there a way to get the DomDocument info from the Console.App without having to open a form? Thanks
The WebBrowser component has NewWindow event with CancelEventArgs. So just add a handler similar to: ``` void webBrowser1_NewWindow(object sender, CancelEventArgs e) { e.Cancel = true; } ``` When the javascript tries to open a popup window the event gets triggered and cancels it.
Can you inject Javascript into the document? You could add this: ``` window.open = function() { return false; } ```
Disable Javascript popups when using Windows.Forms.Webbrowser.Navigate()
[ "", ".net", "javascript", "popup", "webbrowser-control", "console-application", "" ]
this is a follow on question to a [previously asked question](https://stackoverflow.com/questions/834247/need-some-help-trying-to-do-a-simple-sql-insert-with-some-simple-data-checking). I have the following data in a single db table. ``` Name LeftId RightId ------------------------------------------ Cat 1 Cat 1 Dog 2 Dog 2 Dog 3 Dog 3 Gerbil 4 5 Cat Bird Cow 6 Cow Cow 7 Dog 8 9 ``` Note that some rows have NO data for for LeftId and RightId. Now, what i wish to do is find two different queries 1. All rows which have at least 1 Id in one of the two columns AND row with NO data in both of those two Id columns. eg. ``` Cat 1 Cow 6 (or 7 .. i'm not worried) ``` 2. All the rows where LeftId and RightId are NULL grouped by the same name. If another row (with the same name) has a value in the LeftId or RightId, this this name will not be returned. eg. ``` Bird ``` hmm.. EDIT: Reworded the first question properly.
For the first query, you want rows that answer to both of the following criteria: 1. The `Name` in the row appears in the table in the same row in which `LeftId` and `RightId` are both NULL. 2. The `Name` in the row appears in the table in same row where at at least one of `LeftId` and `RightId` is *not* NULL. Well, #1 is done by: ``` SELECT Name FROM Tbl WHERE (LeftId IS NULL) AND (RightId IS NULL) ``` And #2 is done by: ``` SELECT Name FROM Tbl WHERE (LeftId IS NOT NULL) OR (RightId IS NOT NULL) ``` You could **intersect** them to see which `Name`s appear in both lists: ``` SELECT Name FROM Tbl WHERE (LeftId IS NULL) AND (RightId IS NULL) INTERSECT SELECT Name FROM Tbl WHERE (LeftId IS NOT NULL) OR (RightId IS NOT NULL) ``` Which returns: ``` Name ---- Cat Cow ``` But you want the `LeftId` and `RightId`, and you don't care which, so I guess we'll aggregate on the Name: ``` SELECT Name, MIN(LeftId) AS LeftId, MIN(RightId) AS RightId FROM Tbl WHERE Tbl.Name IN ( SELECT Name FROM Tbl WHERE (LeftId IS NULL) AND (RightId IS NULL) INTERSECT SELECT Name FROM Tbl WHERE (LeftId IS NOT NULL) OR (RightId IS NOT NULL) ) GROUP BY Name ``` Which returns ``` Name LeftId RightId ---- ------ ------- Cat 1 Cow 6 7 ``` [lc](https://stackoverflow.com/questions/867030/how-to-clean-this-sql-data-up/867069#867069) already suggested using COALESE to turn those two IDs to a single one. So how about this: ``` SELECT Name, COALESCE(MIN(LeftId),MIN(RightId)) AS Id FROM Tbl WHERE Tbl.Name IN ( SELECT Name FROM Tbl WHERE (LeftId IS NULL) AND (RightId IS NULL) INTERSECT SELECT Name FROM Tbl WHERE (LeftId IS NOT NULL) OR (RightId IS NOT NULL) ) GROUP BY Name ``` Which returns: ``` Name Id ---- -- Cat 1 Cow 6 ``` --- For the second query, you want rows that obey the following criteria: 1. The `Name` appears only in rows that have no `LeftId` and `RightId` I can't think of a way to do that sort of self-referencing query in SQL in a single set of criteria, so I'll break it down to two criteria. *Both* must be obeyed to be acceptable: 1. The `Name` appears in rows that have no `LeftId` and `RightId` 2. The `Name` does *not* appear in rows that have either `LeftId` or `RightId` Doing #1 is simply: ``` SELECT Name FROM Tbl WHERE (LeftId IS NULL) AND (RightId IS NULL) ``` But #2 is tricky. Of course doing the opposite of #2 ("all the `Name` that appear in rows that have either `LeftId` or `RightId`) is just like before: ``` SELECT Name FROM Tbl WHERE (LeftId IS NOT NULL) OR (RightId IS NOT NULL) ``` Now comes the tricky bit - we want all the rows that obey #1 but don't obey the opposite of #2. This is where **EXCEPT** is useful: ``` SELECT Name FROM Tbl WHERE (LeftId IS NULL) AND (RightId IS NULL) EXCEPT SELECT Name FROM Tbl WHERE (LeftId IS NOT NULL) OR (RightId IS NOT NULL) ``` Which returns: ``` Name ---- Bird ``` Which is what we wanted!
If I understand you correctly then this is fairly trivial: 1: ``` SELECT * FROM your_table WHERE (LeftId IS NOT NULL AND RightId IS NULL) OR (LeftId IS NULL AND RightId IS NOT NULL) ``` 2: ``` SELECT * FROM your_table WHERE NOT EXISTS (SELECT * FROM your_table y1 WHERE (y1.LeftId IS NOT NULL OR y1.RightId IS NOT NULL) AND y1.name = your_table.name) ``` If this isn't right then perhaps you could clarify. Edit: updated
How to clean this Sql data up?
[ "", "sql", "sql-server", "" ]
I've got this code on my page: ``` header("Location: $page"); ``` $page is passed to the script as a GET variable, do I need any security? (if so what) I was going to just use addslashes() but that would stuff up the URL...
**I** could forward **your** users anywhere **I** like if I get them to click a link, which is definitely a big security flaw (Please login on www.yoursite.com?page=badsite.com). Now think of a scenario where badsite.com looks exactly like your site, except that it catches your user's credentials. You're better off defining a `$urls` array in your code and passing only the index to an entry in that array, for example: ``` $urls = array( 'pageName1' => '/link/to/page/number/1', 'pageNumber2' => '/link/to/page/number/2', 'fancyPageName3' => '/link/to/page/number/3', ); # Now your URL can look like this: # www.yoursite.com?page=pageName1 ```
This is a [code injection vulnerability](http://www.owasp.org/index.php/Code_Injection) by the book. The user can enter any value he wants and your script will obey without any complaints. But one of the most important rules – if even not *the* most important rule – is: > **Never trust the user data!** So you should check what value has been passed and validate it. Even though a [header injection vulnerability was fixed with PHP 4.4.2 and 5.1.2 respectivly](http://docs.php.net/header), you can still enter any valid URI and the user who calls it would be redirected to it. Even such cryptic like `?page=%68%74%74%70%3a%2f%2f%65%76%69%6c%2e%65%78%61%6d%70%6c%65%2e%63%6f%6d%2f` what’s URL encoded for `?page=http://evil.example.com/`.
php security for location header injection via $_GET
[ "", "php", "security", "" ]
Is there an easy way to check in a unit test that two arrays are equal (that is, have the same number of elements, and each element is the same?). In Java, I would use `assertArrayEquals (foo, bar);`, but there seems to be no equivalent for C#. I tried `Assert.AreEqual(new string[]{"a", "b"}, MyFunc("ab"));`, but even though the function returns an array with "a", "b" the check still fails This is using Visual Studio 2008 Team Suite, with the built-in unit test framework.
It's `CollectionAssert.AreEqual`, see also the [documentation for CollectionAssert](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert(VS.80).aspx).
Class1.cs: ``` namespace ClassLibrary1 { public class Class1 { Array arr1 = new[] { 1, 2, 3, 4, 5 }; public Array getArray() { return arr1; } } } ``` ArrayEqualTest.cs: ``` [TestMethod()] public void getArrayTest() { Class1 target = new Class1(); Array expected = new []{1,2,3,4,5}; Array actual; actual = target.getArray(); CollectionAssert.AreEqual(expected, actual); //Assert.IsTrue(expected.S actual, "is the test results"); } ``` Test Success,found the error: ``` CollectionAssert.AreEqual failed. (Element at index 3 do not match.) ```
Assert that arrays are equal in Visual Studio 2008 test framework
[ "", "c#", "visual-studio-2008", "unit-testing", "" ]
I am writing a custom ConfigurationElementCollection for a custom ConfigurationHandler in C#.NET 3.5 and I am wanting to expose the IEnumerator as a generic IEnumerator. What would be the best way to achieve this? I am currently using the code: ``` public new IEnumerator<GenericObject> GetEnumerator() { var list = new List(); var baseEnum = base.GetEnumerator(); while(baseEnum.MoveNext()) { var obj = baseEnum.Current as GenericObject; if (obj != null) list.Add(obj); } return list.GetEnumerator(); } ``` Cheers
I don't believe there's anything in the framework, but you could easily write one: ``` IEnumerator<T> Cast<T>(IEnumerator iterator) { while (iterator.MoveNext()) { yield return (T) iterator.Current; } } ``` It's tempting to just call `Enumerable.Cast<T>` from LINQ and then call `GetEnumerator()` on the result - but if your class already implements `IEnumerable<T>` and `T` is a value type, that acts as a no-op, so the `GetEnumerator()` call recurses and throws a `StackOverflowException`. It's safe to use `return foo.Cast<T>.GetEnumerator();` when `foo` is definitely a *different* object (which doesn't delegate back to this one) but otherwise, you're probably best off using the code above.
`IEnumerable<T>` already derives from `IEnumerable` so there's no need to do any conversion. You can simply cast to it...well actually it's implicit no cast necessary. ``` IEnumerable<T> enumerable = GetGenericFromSomewhere(); IEnumerable sadOldEnumerable = enumerable; return sadOldEnumerable.GetEnumerator(); ``` Going the other way round isn't much more difficult with LINQ: ``` var fancyEnumerable = list.OfType<GenericObject>(); return fancyEnumerable.GetEnumerator(); ```
What is the best way to convert an IEnumerator to a generic IEnumerator?
[ "", "c#", "enumeration", "ienumerator", "" ]
I am not very familiar with Tomcat, in my head it is basically abstracted as a cgi server that saves the JVM between calls -- I know it can do a lot more than that, though. I am looking for a way to launch a *background* thread when a Tomcat server starts, which would periodically update the Server Context (in my particular case this is a thread that listens to heartbeats from some other services and updates availability information, but one can imagine a variety of uses for this). Is there a standard way to do this? Both the launching, and the updating/querying of the Context? Any pointers to the relevant documentation and/or code samples would be much appreciated.
If you want to start a thread when your WAR is deployed, you can define a context listener within the web.xml: ``` <web-app> <listener> <listener-class>com.mypackage.MyServletContextListener</listener-class> </listener> </web-app> ``` Then implement that class something like: ``` public class MyServletContextListener implements ServletContextListener { private MyThreadClass myThread = null; public void contextInitialized(ServletContextEvent sce) { if ((myThread == null) || (!myThread.isAlive())) { myThread = new MyThreadClass(); myThread.start(); } } public void contextDestroyed(ServletContextEvent sce){ try { myThread.doShutdown(); myThread.interrupt(); } catch (Exception ex) { } } } ```
> I am looking for a way to launch a background thread when a Tomcat server starts I think you are looking for a way to launch a background thread when *your web application* is started by Tomcat. This can be done using a [ServletContextListener](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContextListener.html). It is registered in web.xml and will be called when your app is started or stopped. You can then created (and later stop) your Thread, using the normal Java ways to create a Thread (or ExecutionService).
Background Thread for a Tomcat servlet app
[ "", "java", "multithreading", "tomcat", "" ]
I am designing some immutable classes but I have to have some variables like say `.Count` to have the total count of the instances. But would having a static variable affect multi-threading? Because methods like Add, Remove, etc have to update the `.Count` value. Maybe I should make it lazy property?
If you're just doing a counter, interlocked operations may be an option as well instead of a lock. MSDN has a [nice example of this](http://msdn.microsoft.com/en-us/library/dd78zt0c.aspx) in the context of a reference count.
You might want to consider using functions from the Interlocked class, at least in the example you gave.
Immutability and static variables
[ "", "c#", ".net", "parallel-processing", "" ]
I'm a big fan of keeping application logic in the servlet, and keeping the JSP as simple as possible. One of the reasons for this is that any good web designer should be able to expand upon his HTML knowledge to build in a few JSTL tags to do simple iteration, access beans, etc. We also keep the more complex/ajax/js components behind a tag library (similar to displayTag but for our own components). Most of the time everything works out ok - The servlet does any SQL it needs to, and stores the results in beans for the JSP to access. Where we have a problem is when the records we wish to access are specified by the design. The clearest example would be the home page - it needs to be eye-catching and effective. It doesn't need to be uniform like rest of the site. There are lots of one-offs or "special cases" here, where we want to query a particular product record, or whatever. What the designer really wants is a way to get a product bean by the product id so he can access the properties as normal. We obviously don't want to query for all products, and I don't want to query in the presentation. I'm pretty sure I'm asking the impossible here and that I have to give something up. My question is what? **EDIT** Am I wrong in thinking that all application logic should be complete *before* calling the JSP? I was under the impression it was considered best practice to do all querying/calculating/processing in the servlet then pass (fairly) dumb beans to a (very) dumb JSP. There are a couple of methods whereby the actual complexity of the query can be encapsulated in another class (custom tag or bean), and the JSP can call it. This keeps the JSP simple (goal 1) but the JSP is still "triggering" the query - quite late in the process. * Have I got this totally wrong and it's fine to do this. * Is it a general rule, but perfectly ok to do this in this instance. * Might I run into problems? **EDIT - Example** I'm hoping this example will help: The home page isn't a "template" like the category/search pages - it is custom designed to work very well with say a marketing image and a couple of specific product images. It does however have information about those two products which should be obtained dynamically (so the name, and importantly price) stay in sync with the db. The servlet can't know which products these will be, because if the designer wants to change them/remove them/add more, he should only have to edit the JSP (and possibly XML as one answer suggested).
If I understand correctly, you have logic in the JSP that wants a particular product, but at this point you don't want to query from the DB, and its too late for the servlet to be aware of it. (A side note, while I respect your will to maintain separation of concerns, the fact that this is an issue clearly shows that your framework has too much logic in the presentation tier...but since we probably can't fix that...moving on). My recommendation is that your designer creates a configuration XML file that contains whatever special cases it needs for the frontend, and yours servlet can read that, then pass dumb beans back to the JSP. OR...you break things down into multiple requests using XMLHTTPRequest and call back to the servlet for each individual query, then assemble the page on the client.
It sounds like you need better separation between the display and database code. You should have separate classes that just deal with interacting with the database, and know nothing about display. Then you just create a method that will look up the product by id and return that bean so the display can pull out the attributes it wants.
Keeping queries out of JSP - how?
[ "", "sql", "jsp", "jstl", "" ]
I have the code below : ``` public class Anything { public int Data { get; set;} } public class MyGenericBase<T> { public void InstanceMethod(T data) { // do some job } public static void StaticMethod(T data) { // do some job } // others members... } public sealed class UsefulController : MyGenericBase<Anything> { public void ProxyToStaticMethod() { StaticMethod(null); } // others non derived members... } public class Container { public UsefulController B { get; set; } } public class Demo { public static void Test() { var c = new Container(); c.B.InstanceMethod(null); // Works as expected. c.B.StaticMethod(null); // Doesn't work. // Static method call on object rather than type. // How to get the static method on the base type ? c.B.ProxyToStaticMethod(); // Works as expected. } } ``` The compiler is very angry... I understand the error message but I don't know how to solve this. I was trying to get a type rather than an object to make my static method call, but I don't find the way to do it correctly. Moreover this results in something not elegant at all. Basically, the GenericBase is a class from a framework with a lot of static methods and some instance methods. The controller is typing this class and extending it. The container is a group of logical related controllers. Interesting thing : a Java version of this code compiles correctly, but with a warning. The execution is correct, too. Does it exist a design pattern to solve this ? Thanks for your inputs ! --- I found a way to get rid of this problem, thanks to your answers. It seems to work, but I can not tell if there are side effects right know. ``` public class GenericBase<T> : MyGenericBase<T> { // Create instance calls here for every base static method. } public sealed class UsefulController : GenericBase<Anything> { // others non derived members... } ```
A call to a static method will be compiled to call a specific static method on a specific class. In other words, it won't use the contents of B to determine which static method to call. So the call has to be resolvable at compile time, hence it complains, because for all it knows, you could replace the contents of that property with multiple concrete types, which would mean that the call to the static method would have to be resolved to a static method in either of these classes. The compiler does not have anything like a virtual or abstract static method, so for one you can't guarantee that all of those classes have that static method. And since the call has to be resolvable at compile time, it won't work like that. You can, as you've noticed, call an instance method of the object, which in turn calls the static method. This does not invalidate the above rules since when the compiler compiles that instance method, which static method it will call is constant and known.
To call the static method you need to refer to it from the class it's defined in, not an instance of that class. ``` MyGenericBase<Anything>.StaticMethod( null ); ```
C# Compiler : cannot access static method in a non-static context
[ "", "c#", "" ]
If we are to catch specific forms of `IOException`, or any other kind as a matter of fact, and we only try and catch a couple (and define definitive outputs for them) say `FileNotFoundException` `ZipException` should we always trail it off and cover all bases with a ``` catch(IOException e){ e.printStackTrace(); } ``` and then possibly go even further and catch `Exception e`, or is this a complete waste of time?
Generally, you only want to catch and handle exceptions you can do something with at a low level. Then at a higher level, catch any unhandled exceptions system wide, so you can record errors that occurred.
Generally, you should only catch exceptions you are going to handle explicitly. You should not catch Exception, IOException, et. al., unless you are an appropriately high level where you are doing your last ditch catch to report a general error to the user.
Is it good to catch a more general type of Exception?
[ "", "java", "exception", "" ]
In PHP, I have the following code for calculating the distance between two locations: ``` <?php function distance($lat1, $long1, $lat2, $long2) { // DEGREE TO RADIAN $latitude1 = $lat1/180*pi(); $longitude1 = $long1/180*pi(); $latitude2 = $lat2/180*pi(); $longitude2 = $long2/180*pi(); // FORMULA: e = ARCCOS ( SIN(Latitude1) * SIN(Latitude2) + COS(Latitude1) * COS(Latitude2) * COS(Longitude2-Longitude1) ) * EARTH_RADIUS $distance = acos(sin($latitude1)*sin($latitude2)+cos($latitude1)*cos($latitude2)*cos($longitude2-$longitude1))*6371; return $distance; } echo distance(9.9921962, 53.5534074, 9.1807688, 48.7771056); // Hamburg, DE - Stuttgart, DE ?> ``` But now, I want to select locations close to a given location via PHP from my MySQL database: * The user enters his hometown * My script gets the latitude/longitude values via the Google API * In my database, I have about 200 locations with a field for the latitude value and a field for the longitude value * I need a code for PHP and MySQL to select the 10 locations which are closest to the user's hometown I hope you can help me. Thanks in advance!
[MySQL Great Circle Distance (Haversine formula)](https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula) does exactly what you need. With only 200 records however you may as well just load them all and check them with code. The data set is really way too small to be worrying too much about database vs code or any other such optimizations. [Calculating distance between zip codes in PHP](https://stackoverflow.com/questions/407989/calculating-distance-between-zip-codes-in-php) has a couple of PHP implementations of this algorithm. [Geo Proximity Search](https://stackoverflow.com/questions/626024/geo-proximity-search) is pretty much the exact same problem you have.
Maybe something like ``` SELECT field1, field2, ..., ACOS(SIN(latitude / 180 * PI()) * SIN(:1) + COS(latitude / 180 * PI()) * COS(:2) * COS(:2 - longtidude)) * 6371 AS distance ORDER BY distance ASC; ``` or ``` SELECT field1, field2, ..., ACOS(SIN(RADIANS(latitude)) * SIN(:1) + COS(RADIANS(latitude)) * COS(:2) * COS(:2 - longtidude)) * 6371 AS distance ORDER BY distance ASC; ``` (directly translated from the PHP code) `:1` and `:2` is `$lat2/180*pi()` and `$long2/180*pi()` respectively.
PHP/MySQL: Select locations close to a given location from DB
[ "", "php", "mysql", "geolocation", "distance", "geography", "" ]
I have an issue and I have looked long and hard over the Internet for an answer but cant find anything. I have a little app that sucks in a web service. It then passes this web services results another applications via its own web service and stores the request in a table. What I am trying to do is quickly import the results to a table from the data set. Option 1 is that I loop through all the rows in the data set and use an insert on each. The issue with this is it is slow and will slow down the response of the little apps web service. Option 2 is to bulk upload the data set into sql. The bad news for me is I have no idea of how to do this!! Can any one help?
You can use [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx). A simple SqlBulkCopy might look like: ``` DataTable dtMyData = ... retrieve records from WebService using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) { bulkCopy.BulkCopyTimeout = 120; // timeout in seconds, default is 30 bulkCopy.DestinationTableName = "MyTable"; bulkCopy.WriteToServer(dtMyData); } ``` If you are processing a great deal of data you may also want to set the [BatchSize](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.batchsize.aspx) property.
It sounds like a mighty busy little web service. You might instead (or even in addition) consider making it asynchronous or multi-threaded. Otherwise you've just built in the coupling between the two web apps that you may have split them to avoid in the first place.
Updating a SQL database table with a webservice
[ "", "asp.net", "sql", "dataset", "bulkinsert", "" ]
Apologies if this has been asked before, I'm not quite sure of the terminology or how to ask the question. I'm wondering if there are libraries or best practices for implementing object models in C++. If I have a set of classes where instances of these classes can have relations to each other and can be accessed from each other via various methods, I want to pick a good set of underlying data structures to manage these instances and their inter-relationships. This is easy in Java since it handles the memory allocation and garbage collection for me, but in C++ I have to do that myself. HTML's [Document Object Model](http://en.wikipedia.org/wiki/Document_Object_Model) (DOM) is one example; as another (contrived) example, suppose I have these classes: * `Entity` * `Person` (subclass of `Entity`) * `Couple` (subclass of `Entity`) * `Property` * `House` (subclass of `Property`) * `Pet` (subclass of `Property`) * `Car` (subclass of `Property`) and these relationships: * `Entity` + has 1 `home` of class `House` + has 0 or more `pets` of class `Pet` + has 0 or more `cars` of class `Car` + has 0 or more `children` of class `Person` * `Person` + has 0 or 1 `spouse` of class `Person` + has 0 or 1 `marriage` of class `Couple` + has 0 or 1 `parents` of class `Entity` (in this model parents don't exist if they're not alive!) * `Couple` + has 2 `members` of class `Person` * `Property` + has 1 `owner` of class `Entity` Now that I've thought out these objects and their relationships, I want to start making data structures and methods and fields to handle them, and here's where I get lost, since I have to deal with memory allocation and lifetime management and all that stuff. You can run into problems like the following: I might want to put an object into a `std::map` or a `std::vector`, but if I do that, I can't store pointers to those objects since they can be relocated when the map or vector grows or shrinks. One approach I used when I was working with COM a lot, is to have a hidden collection that contained everything. Each object in the collection had a unique ID (either a number or name), by which it could be looked up from the collection, and each object had a pointer to the collection. That way, if you have an object which wants to point to another object, instead of literally holding a pointer to another object, I store the ID and can look it up via the hidden collection. I can use reference-counting to automatically deal with lifetime issues (except for the case of disjoint cycles, sometimes that's not a problem). Are there other approaches? Or are there libraries to make this kind of stuff easier in C++? **edit:** then you have other issues, such as the relationships between objects are likely to be mutable in many cases, and you have to think ahead about how references to objects should be stored, and what methods should be provided for accessing objects from each other. For example, if I have a handle to a `Person` X, and I want to represent the concept of "find X's child named George", then I have to store the name "George" rather than a child number: the children may be stored in a vector, and I may be able to call X.getChildCount() and X.getChild(0), but "George" may not always be child number 0, since other children may be inserted before "George" in the child vector. Or X may have two or three or four other children also named "George". Or "George" may change his name to "Anthony" or "Georgina". In all these cases it is probably better to use some kind of unique immutable ID. **edit 2:** (and I'll clean up my question a bit once I get this straightened out) I can deal with the choice of methods and property names, I can deal with whether to use a map or a list or a vector. That's fairly straightforward. The problems I'm trying to deal with specifically are: * how to have one object store a reference to another object, when those objects may be part of data structures that are reallocated * how to deal with object lifetime management, when there are reciprocal relationships between objects
You wrote about storing objects from your object model inside std::vector etc. and problems with using pointers to them. That reminds me that it's good to divide your C++ classes into two categories (I'm not sure about terminology here): 1. **Entity classes** which represent objects that are part of your object model. They are usually polymorphic or potentially will be in the future. They are created on heap and are always referenced by pointers or smart pointers. You never create them directly on stack, as class/struct members nor put them directly in containers like std::vectors. They don't have copy constructor nor operator= (you can make a new copy with some Clone method). You can compare them (their states) if it's meaningful to you but they are not interchangable because they have identity. Each two objects are distinct. 2. **Value classes** which implement primitive user defined types (like strings, complex numbers, big numbers, smart pointers, handle wrappers, etc). They are created directly on stack or as class/struct members. They are copyable with copy constructor and operator=. They are not polymorphic (polymorhism and operator= don't work well together). You often put their copies inside stl containers. You rarely store pointers to them in independent locations. They are interchangeable. When two instances have the same value, you can treat them as the same. (The variables that contain them are different things though.) There are many very good reasons to break above rules. But I observed that ignoring them from the start leads to programs that are unreadable, unreliable (especially when it comes to memory management) and hard to maintain. --- Now back to your question. If you want to store a data model with complex relationships and easy way to do queries like "find X's child named George", why not consider some in-memory relational database? Notice that when you are going to efficiently implement a) more complex bidirectional relationships and b) queries based on different object properties, then you will probably need to create indexed data structures that are very similar to what relational database does inside. Are your implementations (as there will be many, in single project) really going to be more effective and robust? Same goes for "collections of everything" and object ids. You'll need to track relationships between objects to avoid ids without objects anyway. How is it different from pointers? Other then getting meaningful errors instead of going crazy all over the memory, that is ;-) --- Some ideas for memory management: * Strong ownership: when you can declare that some entity lives only as long as its owner and there is no possibility of independently existing pointers to it, you can just delete it in owner's destructor (or with scoped\_ptr). * Someone already proposed smart\_ptr. They are great and can be used with stl containers. They are reference couter based though, so do not create cycles :-(. I am not aware of any widely used c++ automatic pointers that can handle cycles. * Maybe there is some top-level object which owns all other objects. Eg. often you can say that all pieces belong to a document or an algorithm or a transaction. They can be created in context of top-level object and then deleted automatically when their top-level object is deleted (when you remove document from memory or finish execution of algorithm). Of course you cannot share pieces between top level objects.
There are about a million (at a conservative estimate) approaches to this. You are really asking "how do I design software in C++". And the answer is, I'm afraid, "what is your software going to do?" - simply knowing that you want to deal with Persons and Houses is not enough.
libraries/approaches for implementing object models in C++
[ "", "c++", "oop", "memory-management", "" ]
How could one test whether a set of modules is installed, given the names of the modules. E.g. ``` modules = set(["sys", "os", "jinja"]) for module in modules: # if test(module exists): # do something ``` While it's possible to write out the tests as: ``` try: import sys except ImportError: print "No sys!" ``` This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this? I've tried eval("import %s"%module) but that complained of a compile error. I'm grateful for your thoughts and suggestions. Thank you.
You can use the [`__import__()`](http://docs.python.org/library/functions.html) function like this:: ``` for module in modules: try: __import__(module) except ImportError: do_something() ``` You can also use [`imp.find_module`](http://docs.python.org/library/imp.html) to determine whether a module can be found *without* importing it:: ``` import imp for module in modules: try: imp.find_module(module) except ImportError: do_something() ``` Oh, and the reason you can't use `eval()` is because `import` is a statement, not an expression. You *can* use `exec` if you *really* want to, though I wouldn't recommend it:: ``` for module in modules: try: exec 'import ' + module except ImportError: do_something() ```
What's wrong with this? ``` modules = set(["sys", "os", "jinja"]) for m in modules: try: __import__(m) except ImportError: # do something ``` The above uses the [`__import__`](http://docs.python.org/library/functions.html#__import__) function. Also, it is strictly testing whether it exists or not - its not actually saving the import anywhere, but you could easily modify it to do that.
Test for Python module dependencies being installed
[ "", "python", "reflection", "import", "module", "python-module", "" ]
I have been programming in .NET for four years (mostly C#) and I use IDiposable extensively, but I am yet to find a need for a finaliser. What are finalisers for?
A finalizer is a last ditch attempt to ensure that something is cleaned up correctly, and is usually reserved for objects that wrap **unmanaged** resources, such as unmanaged handles etc that won't get garbage collected. It is rare indeed to write a finalizer. Fortunately (and unlike `IDisposable`), finalizers don't need to be propagated; so if you have a `ClassA` with a finalizer, and a `ClassB` which wraps `ClassA`, then `ClassB` does not need a finalizer - but quite likely both `ClassA` and `ClassB` would implement `IDisposable`. For managed code, `IDisposable` is usually sufficient. Even if you don't clean up correctly, eventually the managed objects will get collected (assuming they are released).
Finalizers are only for freeing **unmanaged** resources like GDI bitmap handles for example. If you don't allocate any unmanaged resources then you don't need finalizers. In general it's a bad idea to touch any **managed** object in a finalizer because the order of finalization is not guaranteed. One other useful technique using a finalizer is to assert that Dispose has been called when the application is required to do so. This can help catch coding errors in a DEBUG build: ``` void Dispose() { GC.SuppressFinalize(this); } #if DEBUG ~MyClass() { Debug.Fail("Dispose was not called."); } #endif ```
What are finalisers for?
[ "", "c#", ".net", "vb.net", "finalizer", "" ]
Is it possible to sanitize all input sent by one method in PHP by simply doing ``` $var = mysql_real_escape_string($_POST); ``` and then access elements of $var as I would have of $\_POST ?
I don't think you can call [mysql\_real\_escape\_string](https://www.php.net/mysql_real_escape_string) on an array. But this would work ``` $cleanData = array_map('mysql_real_escape_string', $_POST); ``` [array\_map](https://www.php.net/manual/en/function.array-map.php) works by calling the function named in quotes on every element of the array passed to it and returns a new array as the result. Like [superUntitled](https://stackoverflow.com/questions/894724/sanitizing-form-data-in-php/894746#894746), I prefer to have a custom function that uses the built-in sanitizing functions as appropriate. But you could still use a custom function with array\_map to achieve the same result.
As a side note, I would recommend using a function to sanitize your results: ``` function escape($txt) { if (get_magic_quotes_gpc()) $txt = stripslashes($txt); if (!is_numeric($txt)) $txt = "'" . mysql_real_escape_string($txt) . "'"; return $txt; } ```
Sanitizing form data in PHP
[ "", "php", "" ]
I have a method that accepts an IEnumerable-decimals and performance various math functions. I want to use the same method on an IEnumerable-int-. How do I implement this? For example to find a simple sum? ``` void Calculate<T>(IEnumerable <T> ListOFNumbers) { int count= ListofNumbers.Count(); ?sum=?; } ```
This is all freely available in [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/). The `Operator` class provides access to generic arithmetic; and there are generic implementations (as extension methods) of `Sum`, `Average`, etc - and works with **any** type with suitable operators in addition to the primitives. So for example, you could use Sum with of [`Complex<T>`](http://csharpindepth.com/ViewNote.aspx?NoteID=50), etc. Note that it currently uses .NET 3.5; I did have a 2.0 version somewhere, but it isn't as tested.... A **simplified** example of sum is shown in the [usage document](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html): ``` public static T Sum<T>(this IEnumerable<T> source) { T sum = Operator<T>.Zero; foreach (T value in source) { if (value != null) { sum = Operator.Add(sum, value); } } return sum; } ``` Although IIRC the *actual* implementation has a bit more... As an aside, note that `dynamic` (in .NET 4.0 / C# 4.0) supposedly supports operators, but we'll have to wait for the beta to see what it does. From my previous looks at `dynamic` in the CTP, I *expect* it to be a bit slower than the MiscUtil code, but we shall see.
You can use the [IEnumerable.Sum](http://msdn.microsoft.com/en-us/library/bb534734.aspx) function
How to Implement Generic Method to do Math calculations on different value types
[ "", "c#", "generics", "" ]
I have created an singleton class, this class returns a database connection. So my question is this connection is also satisfying singleton criteria? If no, than how I can make it singleton. Here is the code. ``` public sealed class SingletonDB { static readonly SingletonDB instance = new SingletonDB(); static SqlConnection con =new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static SingletonDB() { } SingletonDB() { } public static SingletonDB Instance { get { return instance; } } public static SqlConnection GetDBConnection() { return con; } } ```
Your Singleton is still off. As far as the singleton pattern goes, please see Jon Skeet's very good and detailed description here : <http://www.yoda.arachsys.com/csharp/singleton.html> Using a Singleton for a SqlConnection object is a really, really bad idea. There is no reason to do this whatsoever. If you are attempting to avoid a performance hit of "new SqlConnection()" or "connection.Open()" be advised that there really is no performance hit there because of the connection pooling going on behind the scenes. Connection Pooling handles the opening/closing of the ***expensive*** connections. Not the SqlConnection object. You won't be able to open multiple SqlDataReaders/Commands with the connection at the same time and will run into thread blocking issues if you are trying to share the same connection object with multiple threads. The Singleton pattern is the most over used and abused pattern and there are many side effects of the singleton that you may not be aware of. Very good talk about the dangers of singletons here <http://www.youtube.com/watch?v=-FRm3VPhseI>
In .NET C# you can wrtie your singleton like this ``` public class Singleton{ public static readonly Singleton Instance= new Singleton(); private Singleton(){} ``` or for multi threaded environment: ``` using System; public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new Singleton(); } } return instance; } } } ```
getting db connection through singleton class
[ "", "c#", "design-patterns", "singleton", "" ]
I'm trying to serialize an object to XML that has a number of properties, some of which are readonly. ``` public Guid Id { get; private set; } ``` I have marked the class [Serializable] and I have implemented the ISerializable interface. Below is the code I'm using to serialize my object. ``` public void SaveMyObject(MyObject obj) { XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); TextWriter tw = new StreamWriter(_location); serializer.Serialize(tw, obj); tw.Close(); } ``` Unfortunately it falls over on the first line with this message. > InvalidOperationException was unhandled: > Unable to generate a temporary class (result=1). > error CS0200: Property or indexer 'MyObject.Id' cannot be assigned to -- it is read only If I set the Id property to public it works fine. Can someone tell me if I'm doing something, or at least if its even possible?
You could use `DataContractSerializer` (but note you can't use xml attributes - only xml elements): ``` using System; using System.Runtime.Serialization; using System.Xml; [DataContract] class MyObject { public MyObject(Guid id) { this.id = id; } [DataMember(Name="Id")] private Guid id; public Guid Id { get {return id;}} } static class Program { static void Main() { var ser = new DataContractSerializer(typeof(MyObject)); var obj = new MyObject(Guid.NewGuid()); using(XmlWriter xw = XmlWriter.Create(Console.Out)) { ser.WriteObject(xw, obj); } } } ``` Alternatively, you can implement `IXmlSerializable` and do everything yourself - but this works with `XmlSerializer`, at least.
You could use the `System.Runtime.Serialization.NetDataContractSerializer`. It is more powerful and fixes some issues of the classic Xml Serializer. Note that there are different attributes for this one. ``` [DataContract] public class X { [DataMember] public Guid Id { get; private set; } } NetDataContractSerializer serializer = new NetDataContractSerializer(); TextWriter tw = new StreamWriter(_location); serializer.Serialize(tw, obj); ``` **Edit:** Update based on Marc's comment: You should probably use `System.Runtime.Serialization.DataContractSerializer` for your case to get a clean XML. The rest of the code is the same.
Serializing private member data
[ "", "c#", ".net", "xml", "serialization", "serializable", "" ]
A few days ago VS 2010 went in Beta test and usually with new Visual Studio ,we get new C#. Since VS and .NET 4 is in Beta does that mean that C# version four is near to the finish? Edit: is C# v4 Beta included in the VS 2010 beta?
C# 4.0 is included in the VS2010 beta (you can try it right now; 'dynamic`, variance etc work), and will be shipped in VS2010 RTM and almost certainly (I assume) in the standalone .NET 4.0 RTM - but **when** that is is entirely up to Microsoft; in particular, [Soma highlights](http://blogs.msdn.com/somasegar/archive/2009/05/18/visual-studio-2010-and-net-fx-4-beta-1-ships.aspx) the need to get quality and performance right, and I would encourage them not to rush on either point (I want it fast and stable ;-p).
As far as I know, the official release date of Visual Studio 2010 has not yet been announced. We know that .NET 4.0 and C# 4.0 will be released at the same time however, whenever it happens to be. A fair estimate for the release date might be Q1 of 2010. (The team seems to be on track with things, but it's not going to be released any earlier than the start of next year.)
Visual studio 2010 and C# v.4
[ "", "c#", ".net", "visual-studio", "" ]
I am using a Richtext box control to post some data in one page. and I am saving the data to my db table with the HTML mark up Ex : This is <b >my bold </b > text I am displaying the first 50 characters of this column in another page. Now When i am saving, if i save a Sentence (with more than 50 chars )with bold tag applied and in my other page when i trim this (for taking first 50 chars) I would lost the closing b tag (</b>) .So the bold is getting applied to rest of my contents in that page. How can i solve this ? How can i check which all open tags are not closed ? is there anyeasy way to do this in PHP. Is there any function to remove my entire HTML tags / mark up and give me the sentence as plain text ?
<http://php.net/strip_tags> the strip\_tags function will remove any tags you might have.
Yes ``` $textWithoutTags = strip_tags($html); ```
PHP: HTML markup problem while displaying trimmed HTML markups
[ "", "php", "html", "markup", "" ]
After I thought that I've understood how they work, I tried this: ``` NSString *str1 = [NSString stringWithCString:"one"]; NSString *str2 = [NSString stringWithCString:"two"]; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3cc, one NSLog(@"str2: %x, %@", &str2, str2); //bfffd3c8, two str1 = str2; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3cc, two ``` The value of an pointer (like str1, str2) is a memory address. When you go to that address, you reach the "area" in memory where the object is stored. But: When I assign str2 to str1, str1 should have as an value the memory address of the same object that's referenced by str2, right? The strange thing here is, that the value of the pointer remains the same (bfffd3cc memory address), where the thing behind that address changes. that's actually completely unlogical to me ;) because I think that the memory address IS the object (or the home of the object in the memory brick, what ever). So I expected this: ``` NSString *str1 = [NSString stringWithCString:"one"]; NSString *str2 = [NSString stringWithCString:"two"]; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3cc, one NSLog(@"str2: %x, %@", &str2, str2); //bfffd3c8, two str1 = str2; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3c8, two ``` Otherwise, I still didn't get the point. The relation between the value of the "pointer variable" and the "real value", lets say the object that's sitting behind that memory address.
Remember that a pointer variable is a variable itself, so it has an address. So `&str1` results in the address of the pointer variable, and `str1` is an expression that results in whatever the pointer variable is holding - the address of the object it's pointing to. Assume that: * the object holding the NSString "one" is at address 0x00000100 * the object holding the NSString "two" is at address 0x00000200 Then your pointers might look something like this: At initialization: ``` str1 0xbfffd3c8 +---------------+ | | | 0x00000100 | | ("one") | +---------------+ str2 0xbfffd3cc +---------------+ | | | 0x00000200 | | ("two") | +---------------+ ``` ======================================= After the `str1 = str2;` assignment: ``` str1 0xbfffd3c8 +---------------+ | | | 0x00000200 | | ("two") | +---------------+ str2 0xbfffd3cc +---------------+ | | | 0x00000200 | | ("two") | +---------------+ ```
you are printing the reference of your pointer, which is the address of the pointer, not the value of the pointer.
Variables, Pointers, Objects and Memory Addresses: Why do I get this strange result?
[ "", "c++", "c", "objective-c", "pointers", "" ]
How can I get the number of items defined in an enum?
You can use the static method [`Enum.GetNames`](https://msdn.microsoft.com/en-us/library/system.enum.getnames) which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum ``` var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length; ```
The question is: > How can I get the number of items defined in an enum? The number of "items" could really mean two completely different things. Consider the following example. ``` enum MyEnum { A = 1, B = 2, C = 1, D = 3, E = 2 } ``` What is the number of "items" defined in `MyEnum`? Is the number of items 5? (`A`, `B`, `C`, `D`, `E`) Or is it 3? (`1`, `2`, `3`) The number of *names* defined in `MyEnum` (5) can be computed as follows. ``` var namesCount = Enum.GetNames(typeof(MyEnum)).Length; ``` The number of *values* defined in `MyEnum` (3) can be computed as follows. ``` var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count(); ```
Total number of items defined in an enum
[ "", "c#", ".net", "enums", "" ]
Is it possible to see when a record has been inserted in a SQL table without using a datetime column?
If your using SQL Server 2008 you can look into [Change Data Capture](http://msdn.microsoft.com/en-us/library/bb522489.aspx) which is a new auditing capability that I'd imagine would have this. Another possibility is to put an identity column on the table. Then you can just order by the column descending. You can also try the [DBCC Log](http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1173464,00.html) command. I don't know if this will give you what you want, it might take some work to get it to a point where you can interpret the data it gives you.
no. sql server doesn't have this functionality out of the box.
Last added records in SQL-Server table
[ "", "sql", "sql-server", "" ]
Do you know a good implementation of a (binary) [segment tree](http://en.wikipedia.org/wiki/Segment_tree) in Java?
This has been implemented within the open source [Layout Management SW Package project](http://code.google.com/p/layout-managment-sw-package/) Here is a [link to the sub package](http://code.google.com/p/layout-managment-sw-package/source/browse/#svn/trunk/LayoutManagmentSWPackage/src/DataModel/SegmentTree) You might find the code useful. I have neither verified it nor run it and I cannot find the license the code is provided under from a quick search of the code and website so Caveat Emptor. You may be able to contact the authors but the last activity appears to have been August 2008.
``` public class SegmentTree { public static class STNode { int leftIndex; int rightIndex; int sum; STNode leftNode; STNode rightNode; } static STNode constructSegmentTree(int[] A, int l, int r) { if (l == r) { STNode node = new STNode(); node.leftIndex = l; node.rightIndex = r; node.sum = A[l]; return node; } int mid = (l + r) / 2; STNode leftNode = constructSegmentTree(A, l, mid); STNode rightNode = constructSegmentTree(A, mid+1, r); STNode root = new STNode(); root.leftIndex = leftNode.leftIndex; root.rightIndex = rightNode.rightIndex; root.sum = leftNode.sum + rightNode.sum; root.leftNode = leftNode; root.rightNode = rightNode; return root; } static int getSum(STNode root, int l, int r) { if (root.leftIndex >= l && root.rightIndex <= r) { return root.sum; } if (root.rightIndex < l || root.leftIndex > r) { return 0; } return getSum(root.leftNode, l, r) + getSum(root.rightNode, l, r); } /** * * @param root * @param index index of number to be updated in original array * @param newValue * @return difference between new and old values */ static int updateValueAtIndex(STNode root, int index, int newValue) { int diff = 0; if(root.leftIndex==root.rightIndex && index == root.leftIndex) { // We actually reached to the leaf node to be updated diff = newValue-root.sum; root.sum=newValue; return diff; } int mid = (root.leftIndex + root.rightIndex) / 2; if (index <= mid) { diff= updateValueAtIndex(root.leftNode, index, newValue); } else { diff= updateValueAtIndex(root.rightNode, index, newValue); } root.sum+=diff; return diff; } } ```
Segment tree java implementation
[ "", "java", "algorithm", "segment-tree", "" ]
I got the Wrox.Beginning.JavaScript.3rd.Edition and wanted to start learning it from scratch, then my boss came along and said that why bother, learn jQuery. Can I understand jQuery and work with it although I am a newbie and have limited knowledge in ASP.net, vb.net, some C#, and basic HTML?!
jQuery *is* javascript. I think you're on the right path. Learn javascript well and you'll be able to make better use of jQuery.
So what's your question? JQuery is a *framework* built on the top of a *language* JavaScript. To use JQuery confidently, you should get familiar with JavaScript. JQuery contains a bunch of useful patterns and utils that mask the incompatibilities of the browsers. Using a JavaScript framework make sense as it allows you to focus on your problem instead of the problem of the JavaScript implementations of the browsers. For further details on JavaScript frameworks, see SO question [»Which Javascript framework (jQuery vs Dojo vs … )?«](https://stackoverflow.com/questions/394601/which-javascript-framework-jquery-vs-dojo-vs). For learning JavaScript, [learn the good parts](http://oreilly.com/catalog/9780596517748/).
Learning Javascript vs. jQuery
[ "", "javascript", "jquery", "" ]
I'm working on this homework that's kind of confusing me... I am provided with the following BinarySearchTree class ``` import java.util.NoSuchElementException; /** * * @param <T> The type of data stored in the nodes of the tree, must implement Comparable<T> with the compareTo method. */ public class BinarySearchTree<T extends Comparable<T>> { BinaryTree<T> tree; int size; public BinarySearchTree() { tree = new BinaryTree<T>(); size = 0; } public boolean isEmpty() { return tree.isEmpty(); } protected BinaryTree<T> recursiveSearch(BinaryTree<T> root, T key) { if (root == null) { return null; } int c = key.compareTo(root.data); if (c == 0) { return root; } if (c < 0) { return recursiveSearch(root.left, key); } else { return recursiveSearch(root.right, key); } } public T search(T key) { if (tree.isEmpty()) { return null; } return recursiveSearch(tree, key).data; } public void insert(T item) { if (tree.isEmpty()) { // insert here tree.makeRoot(item); size++; return; } // do an iterative descent BinaryTree<T> root = tree; boolean done=false; BinaryTree<T> newNode = null; while (!done) { int c = item.compareTo(root.data); if (c == 0) { // duplicate found, cannot be inserted throw new OrderViolationException(); } if (c < 0) { // insert in left subtree if (root.left == null) { // insert here as left child newNode = new BinaryTree<T>(); root.left = newNode; done=true; } else { // go further down left subtree root = root.left; } } else { // insert in right subtree if (root.right == null) { // insert here as right child newNode = new BinaryTree<T>(); root.right = newNode; done=true; } else { // go further down right subtree root = root.right; } } } // set fields of new node newNode.data = item; newNode.parent = root; size++; } /** * @param deleteNode Node whose parent will receive new node as right or left child, * depending on whether this node is its parent's right or left child. * @param attach The node to be attached to parent of deleteNode. */ protected void deleteHere(BinaryTree<T> deleteNode, BinaryTree<T> attach) { // deleteNode has only one subtree, attach BinaryTree<T> parent = deleteNode.parent; deleteNode.clear(); // clear the fields if (parent == null) { return; } if (deleteNode == parent.left) { // left child of parent, attach as left subtree parent.detachLeft(); parent.attachLeft(attach); return; } // attach as right subtree parent.detachRight(); parent.attachRight(attach); } protected BinaryTree<T> findPredecessor(BinaryTree<T> node) { if (node.left == null) { return null; } BinaryTree<T> pred = node.left; // turn left once while (pred.right != null) { // keep turning right pred = pred.right; } return pred; } public T delete(T key) { if (tree.isEmpty()) { // can't delete from an empty tree throw new NoSuchElementException(); } // find node containing key BinaryTree<T> deleteNode = recursiveSearch(tree, key); if (deleteNode == null) { // data not found, can't delete throw new NoSuchElementException(); } BinaryTree<T> hold; // case c: deleteNode has exactly two subtrees if (deleteNode.right != null && deleteNode.left != null) { hold = findPredecessor(deleteNode); deleteNode.data = hold.data; deleteNode = hold; // fall through to case a or b } // case a: deleteNode is a leaf if (deleteNode.left == null && deleteNode.right == null) { deleteHere(deleteNode, null); size--; return deleteNode.data; } // case b: deleteNode has exactly one subtree if (deleteNode.right != null) { hold = deleteNode.right; deleteNode.right = null; } else { hold = deleteNode.left; deleteNode.left = null; } deleteHere(deleteNode,hold); if (tree == deleteNode) { // root deleted tree = hold; } size--; return deleteNode.data; } public T minKey() { if (tree.data == null) { // tree empty, can't find min value throw new NoSuchElementException(); } BinaryTree<T> root = tree; T min=root.data; root = root.left; // turn left once while (root != null) { // keep going left to leftmost node min = root.data; root = root.left; } return min; } public T maxKey() { if (tree.getData() == null) { // tree empty, can't find max value throw new NoSuchElementException(); } BinaryTree<T> root=tree; T max=root.data; root = root.right; // turn right once while (root != null) { // keep going to rightmost node max = root.data; root = root.right; } return max; } public int size() { return size; } protected void recursivePreOrder(BinaryTree<T> root, Visitor<T> visitor) { if (root != null) { visitor.visit(root); recursivePreOrder(root.left, visitor); recursivePreOrder(root.right, visitor); } } public void preOrder(Visitor<T> visitor) { if (tree.isEmpty()) { return; } recursivePreOrder(tree, visitor); } protected void recursiveInOrder(BinaryTree<T> root, Visitor<T> visitor) { if (root != null) { recursiveInOrder(root.left, visitor); visitor.visit(root); recursiveInOrder(root.right, visitor); } } public void inOrder(Visitor<T> visitor) { if (tree.isEmpty()) { return; } recursiveInOrder(tree, visitor); } protected void recursivePostOrder(BinaryTree<T> root, Visitor<T> visitor) { if (root != null) { recursivePostOrder(root.left, visitor); recursivePostOrder(root.right, visitor); visitor.visit(root); } } public void postOrder(Visitor<T> visitor) { if (tree.isEmpty()) { return; } recursivePostOrder(tree, visitor); } } ``` ================================================================================ Now I have another class Student.... I want to create a binary search tree of Student objects.. ``` BinarySearchTree<Student> tree = new BinarySearchTree<Student>(); ``` However when I do that I get the following error: Bound mismatch: The type Student is not a valid substitute for the bounded parameter > of the type BinarySearchTree Any ideas what's happening here... I can't figure it out.
``` public class BinarySearchTree<T extends Comparable<T>> ``` A formal generics argument, in your case T, lists what's required for a class to be a valid T. In you case, you've said, "to be a valid T, a class must implement Comparable" (The keyword is "extends", but in practice that means "extends or implements".) In your instantiation, T is Student. If we substitute Student for T: ``` public class BinarySearchTree<Student extends Comparable<Student>> ``` is that a true statement? Does Student really implement Comparable? If it does, Student fits the requirement of being a T, and so you can use Student as the actual parameter for the formal parameter T. If not, you get the compiler's complaint you saw. Actually, to cover more complicated situations where a subclass's implementation of Comparable is done by a super class, the more general form would be: ``` public class BinarySearchTree<T extends Comparable<? super T > > ``` So you need to make Student implement Comparable< Student >. Note that I *didn't* say that the compiler's looking for a `Student.compareTo`. It doesn't even get that far. It's looking to see if T (in your case, Student) is declared as implementing Comparable< T> (in your case, Comparable< Student >). Now adding `implements Comparable< Student >` to Student will *also* make the compiler ensure that there's a `public int compareTo` method on Student. But without the "implements Comparable", even if the compiler knows there's a method `Student.compareTo`, it doesn't know that that `compareTo` is the `Comparable.compareTo`. (In other words, we're looking for declared implementation, not just that there happens to be a method with the right name and signature.)
Does the class Student implement Comparable?
Java Generic Binary Search Tree type issue
[ "", "java", "generics", "casting", "binary-search-tree", "" ]
Can I get a threads suspend count under Windows CE, using C or Visual C++, without calling resume or suspend functions? The only way I can see of doing it is something like ``` int Count = SuspendThread(ThreadHandle); ResumeThread(ThreadHandle); ``` This has a couple of problems, firstly, I'd rather not suspend the thread, and secondly the suspend might fail if the thread is running kernel code. I can work around this, but I feel there should be a more elegant solution. I could also reverse it using ``` int Count = ResumeThread(ThreadHandle); SuspendThread(ThreadHandle); ``` But this has similar problems. Any good alternative method of getting the suspend count from the handle?
I have a combined solution. Use WaitForSingleObject() to determine if the thread is suspended or not. If it's not suspended, the suspend count is obviously 0. If it's suspended, it's safe to call SuspendThread() to get the suspend count. Since it's already suspended you will not stall anything.
**You should not suspend any thread on any platform, ever.** You should instead add synchronization points in your threading code that explicitly waits for a flag to become signaled before it is allowed to continue. This way you *know* where it will be paused, or at least know that it will be paused at safe points. The following operations on threads should be banned, outright, from any platform for any programmer: * Suspend * Resume (since you don't need it if you can't suspend the thread) * Kill/Abort You should never, ever, forcibly impose your will from the outside on a thread. You have no guarantee what it is doing, what kind of resources it is currently locking. Always write threading in a cooperative mode. Your thread should be aware of its surroundings, and yield to wishes of the outside world to either exit in an orderly fashion, or pause until it can safely continue.
How do i know if a thread is suspended under Windows CE
[ "", "c++", "c", "multithreading", "windows-mobile", "" ]
It always feels wrong to me to write ``` if (MyObject) // do something ``` Or reversly ``` if (!MyObject) // do something ``` However you could argue that it is less verbose than ``` if (MyObject != null) // do something if (MyObject == null) // do something ``` Are there any **non-subjective** reasons to use one over the other?
In C#, you can't do ``` if (MyObject) ``` to check for `null`s. It's a compile time error (if the class doesn't have an implicit boolean conversion operator). ``` if (!MyObject) ``` is also invalid if the class doesn't overload `operator !` to return a boolean value (or a value that can be implicitly casted to a boolean). So you have to stick with `obj == null` and `obj != null`. To summarize, the non-subjective reason is being able to compile your code! ### UPDATE (story): Once upon a time, in ancient C, there was no `bool` type. Zero was considered `false` and every non-zero value was considered `true`. You could write ``` while(1) { } ``` to create an infinite loop. You could also do things like ``` int n = 10; while (n--) { } ``` to have a loop that executes `n` times. The problem with this strategy was: ``` int x = 10; if (x = 0) { // bug: meant to be x == 0 } ``` You missed a single character and you created a bug (most modern C compilers will issue a warning on this statement, but it's valid C, nevertheless). This is why you see code like ``` if (5 == variable) if (NULL == pObj) ``` in many places as it's not prone to the above mistake. C# designers decided to **require** a *boolean* expression as the condition for `if`, `while`, etc., and not allow casting of types (unless they explicitly declare an overloaded operator, which is discouraged) to boolean to reduce the chance of errors. So things like: ``` object x = null; if (x) { } int y = 10; if (y) { } while (y--) { } ``` that are valid in C, **do not compile in C# at all**. This is not a matter of style or agreement by any means.
> Are there any non-subjective reasons > to use one over the other? The fact that (1) and (2) don't compile is a non-subjective reason enough to not use them. So we are left with (3) and (4): ``` if (MyObject != null) // do something if (MyObject == null) // do something ``` Here it depends on whether you want to do something if MyObject is null (4), or if it is not null (3). **Clearly this is not a style choice.** It would be ridiculous to adopt always the same "style", because then if you wanted the *other* condition you'd have to do: ``` if (MyObject == null) // style policy { // nothing here } else { // do something } ``` Which isn't exactly what I'd call readable code.
What is the best syntax for checking for null value objects in C#
[ "", "c#", "" ]
I have two ListBoxes, lstAvailableColors and lstSelectedColors. Between each listbox are two buttons, Add and Remove. When a color or colors is selected in lstAvailableColors and the Add button is clicked, I want to remove them from lstAvailableColors and display them in lstSelectedColors. Also, if colors are selected in lstSelectedColors and the Remove button is clicked, I want to remove the colors from lstSelectedColors and add them back to lstAvailableColors. When I do this, I get the following error when it removes the item: Collection was modified; enumeration operation may not execute. Here is the code for the Add Button and the Remove Button: Add: ``` protected void btnAdd_Click(object sender, EventArgs e) { foreach (ListItem item in lstAvailableColors.Items) { if (item.Selected) { lstSelectedColors.Items.Add(item); lstAvailableColors.Items.Remove(item); } } } ``` Remove: ``` protected void btnRemove_Click(object sender, EventArgs e) { foreach (ListItem item in lstSelectedColors.Items) { if (item.Selected) { lstAvailableColors.Items.Add(item); lstSelectedColors.Items.Remove(item); } } } ```
It's not possible to modify a collection while you're enumerating it in .Net. You need to separate out your enumeration and remove code into different blocks. Here is a quick sample on how to do that in without LINQ ``` protected void btnAdd_Click(object sender, EventArgs e) { var selected = new List<ListItem>(); foreach (ListItem item in lstAvailableColors.Items) { if (item.Selected) { selected.Add(item); lstSelectedColors.Items.Add(item); } } foreach (ListItem item in selected) { lstAvailableColors.Items.Remove(item); } } ``` And here's a more concise version using LINQ ``` var selected = lstAvailableColors.Cast<ListItem>().Where(i => i.Selected).ToList(); selected.ForEach( x => { lstSelectedColors.Items.Add(x); }); selected.ForEach( x => { lstAvailableColors.Items.Remove(x);}); ``` **EDIT** The LINQ version works in two parts. The first part is the first line which finds the currently selected items and stores the value in a `List<ListItem>`. It's very important that the line contain the .ToList() call because that forces the query to execute immediately vs. being delayed executed. The next two lines iterate through each value which is selected and remove or add it to the appropriate list. Because the selected list is already stored we are no longer enumerating the collection when we modify it.
You cannot modify an collection while you are using an Enumerator for this collection, what the for each statement does. You have to loop over the data with a normal for loop and then you can modify the collection, but you must be careful to correctly update the current index if you insert or remove elements. If you just add or remove elements and don't insert some, iterating from the last element to the first will do. ``` protected void btnAdd_Click(object sender, EventArgs e) { for (Int32 i = lstAvailableColors.Items.Count; i >= 0; i--) { ListItem item = lstAvailableColors.Items[i]; if (item.Selected) { lstSelectedColors.Items.Add(item); lstAvailableColors.Items.Remove(item); } } } ```
Collection was modified; enumeration may not execute error when removing a ListItem from a LIstBox
[ "", "c#", ".net", "ienumerable", "" ]
I'm trying to map a one to "zero or one" relationship in Hibernate. I think I may have found a way using a many-to-one. ``` class A { private B b; // ... getters and setters } class B { private A a; } ``` Class A's mapping specifies: ``` <many-to-one name="b" class="B" insert="false" update="false" column="id" unique="true"/> ``` and Class B's mapping specifies: ``` <one-to-one name="a" class="A" constrained="true"/> ``` What I would like is for b to be null when no matching row for B was found in the database. So I can do this (in class A): ``` if (b == null) ``` However, it seems that b is never null. What can I do about this?
The answer was to add not-found="ignore" to the many-to-one statement in A: ``` <many-to-one name="b" class="B" not-found="ignore" insert="false" update="false" column="id" unique="true"/> ``` I tried simply adding lazy="false" to B as Rob H recommended, but that resulted in a HibernateObjectRetrievalFailureException everytime I loaded an A that had no B. See this thread for more information: <https://forum.hibernate.org/viewtopic.php?p=2269784&sid=5e1cba6e2698ba4a548288bd2fd3ca4e>
Like Boden said, the answer is to add `not-found="ignore"` to the many-to-one statement in A. Doing this with annotation: In Class A: ``` @ManyToOne @Cascade({ CascadeType.ALL }) @JoinColumn(name = "Id") @NotFound(action=NotFoundAction.IGNORE) private B b ``` in Class B: ``` @Id @GeneratedValue(generator = "myForeignGenerator") @org.hibernate.annotations.GenericGenerator( name = "myForeignGenerator", strategy = "foreign", parameters = @Parameter(name = "property", value = "a") ) private Long subscriberId; @OneToOne(mappedBy="b") @PrimaryKeyJoinColumn @NotFound(action=NotFoundAction.IGNORE) private A a; ```
Hibernate one to zero or one mapping
[ "", "java", "hibernate", "" ]
I'm coming to Java from C# & ASP.NET MVC, I'd love to find an equivalent in the Java world that I could use on the Google App Engine. I've already started to have a play with [FreeMarker](http://thatismatt.blogspot.com/2009/05/mvc-in-java-world.html) and even made the first steps towards writing a very simple framework. Ideally I wouldn't have to do all the hard work though, someone must have done this already! So my question is - what frameworks are there out there that would be familiar for me coming from ASP.NET MVC and I could use them on Google App Engine for Java. The key things I'd want are: * **Simple Routing** - `/products/view/1` gets mapped to the view action of the products controller with the productid of 1 * **Template Engine** - some way of easily passing 'ViewData' to the view, and from the view easily accessing it, ideally I'd love to avoid anything that is too XMLy (thus why I like [FreeMarker](http://freemarker.org/)).
I am currently working on a Google App Engine app using Spring MVC. It is a lot more mature than ASP.NET MVC so you shouldn't be disappointed. As an added bonus you have the whole IoC power of Spring. For the view layer I am trying out Velocity. It is pretty simple but I have yet to decide if I will prefer it over JSPs. I had a brief look at FreeMaker but didn't like what I saw. If you want to stay away from XML'y JSP templates than I recommend you give Velocity a spin. The only problem I have had with Spring on GAE is file uploading. The MultipartResolver implementations both rely on a temporary file directory. After writing my own implementation I'm back to seamless uploading of files in my models.
There are a couple of MVC frameworks that you should consider (that's what I'm doing now). Initially, I went with Spring MVC (3.0) and the cold start on GAE is horrendous! It takes about 10 seconds to start (and I'm not even using anything complex, like spring security, etc), so I need to use a cron job to keep it alive. So I don't recommend that you use Spring at all on GAE. Take a look at the following frameworks: [VRaptor](http://vraptor.caelum.com.br/en/) [Slim3](http://sites.google.com/site/slim3appengine/Home) [Google Sitebricks](http://code.google.com/p/google-sitebricks/) As for the templating, I use [Sitemesh](http://www.opensymphony.com/sitemesh/) -- used it for quite a while now, so don't see a need to switch. Hope this helps!
MVC in a Google App Engine Java world
[ "", "java", "model-view-controller", "google-app-engine", "frameworks", "" ]
How can I get the number of items listed in a combobox?
Try ``` var count = comboBox.Items.Count; ```
You should reference `Count` of the [`Items`](http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.items.aspx) property. ``` myComboBox.Items.Count ```
How to get the number of items in a combobox?
[ "", "c#", ".net", "winforms", "combobox", "" ]
I know we can explicitly call the constructor of a class in C++ using scope resolution operator, i.e. `className::className()`. I was wondering where exactly would I need to make such a call.
Most often, in a child class constructor that require some parameters : ``` class BaseClass { public: BaseClass( const std::string& name ) : m_name( name ) { } const std::string& getName() const { return m_name; } private: const std::string m_name; //... }; class DerivedClass : public BaseClass { public: DerivedClass( const std::string& name ) : BaseClass( name ) { } // ... }; class TestClass : { public: TestClass( int testValue ); //... }; class UniqueTestClass : public BaseClass , public TestClass { public: UniqueTestClass() : BaseClass( "UniqueTest" ) , TestClass( 42 ) { } // ... }; ``` ... for example. Other than that, I don't see the utility. I only did call the constructor in other code when I was too young to know what I was really doing...
You also sometimes explicitly use a constructor to build a temporary. For example, if you have some class with a constructor: ``` class Foo { Foo(char* c, int i); }; ``` and a function ``` void Bar(Foo foo); ``` but you don't have a Foo around, you could do ``` Bar(Foo("hello", 5)); ``` This is like a cast. Indeed, if you have a constructor that takes only one parameter, the C++ compiler will use that constructor to perform implicit casts. It is *not* legal to call a constructor on an already-existing object. That is, you cannot do ``` Foo foo; foo.Foo(); // compile error! ``` no matter what you do. But you can invoke a constructor without allocating memory - that's what *placement new* is for. ``` char buffer[sizeof(Foo)]; // a bit of memory Foo* foo = new(buffer) Foo(); // construct a Foo inside buffer ``` You give new some memory, and it constructs the object in that spot instead of allocating new memory. This usage is considered evil, and is rare in most types of code, but common in embedded and data structure code. For example, `std::vector::push_back` uses this technique to invoke the copy constructor. That way, it only needs to do one copy, instead of creating an empty object and using the assignment operator.
Why explicitly call a constructor in C++
[ "", "c++", "constructor", "" ]
I'm building an app on Google App Engine. I'm incredibly new to Python and have been beating my head against the following problem for the past 3 days. I have a class to represent an RSS Feed and in this class I have a method called setUrl. Input to this method is a URL. I'm trying to use the re python module to validate off of the RFC 3986 Reg-ex (<http://www.ietf.org/rfc/rfc3986.txt>) Below is a snipped which *should* work? ``` p = re.compile('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?') m = p.match(url) if m: self.url = url return url ```
An easy way to parse (and validate) URL's is the `urlparse` ([py2](https://docs.python.org/2/library/urlparse.html), [py3](https://docs.python.org/3.0/library/urllib.parse.html)) module. A regex is too much work. --- There's no "validate" method because almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL. Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible. For example `:::::` is a valid URL. The path is `":::::"`. A pretty stupid filename, but a valid filename. Also, `/////` is a valid URL. The netloc ("hostname") is `""`. The path is `"///"`. Again, stupid. Also valid. This URL normalizes to `"///"` which is the equivalent. Something like `"bad://///worse/////"` is perfectly valid. Dumb but valid. **Bottom Line**. Parse it, and look at the pieces to see if they're displeasing in some way. Do you want the scheme to always be "http"? Do you want the netloc to always be "www.somename.somedomain"? Do you want the path to look unix-like? Or windows-like? Do you want to remove the query string? Or preserve it? These are not RFC-specified validations. These are validations unique to your application.
Here's the complete regexp to parse a URL. ``` (?:https?://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?) \.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d +)){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA -F\d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d ]{2}))|[;:@&=])*))*)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d ]{2}))|[;:@&=])*))?)?)|(?:s?ftp://(?:(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(), ]|(?:%[a-fA-F\d]{2}))|[;?&=])*)(?::(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?: %[a-fA-F\d]{2}))|[;?&=])*))?@)?(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\ d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|( ?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d+))?))(?:/(?:(?:(?:(?:[a-zA-Z\d$\- _.+!*'(),]|(?:%[a-fA-F\d]{2}))|[?:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+! *'(),]|(?:%[a-fA-F\d]{2}))|[?:@&=])*))*)(?:;type=[AIDaid])?)?)|(?:news :(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[;/?:&=])+@(?: (?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?: (?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3})))|(?:[a-zA -Z](?:[a-zA-Z\d]|[_.+-])*)|\*))|(?:nntp://(?:(?:(?:(?:(?:[a-zA-Z\d](?: (?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA -Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d+))?)/(?:[a-zA-Z](?:[a- zA-Z\d]|[_.+-])*)(?:/(?:\d+))?)|(?:telnet://(?:(?:(?:(?:(?:[a-zA-Z\d$\ -_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[;?&=])*)(?::(?:(?:(?:[a-zA-Z\d$\-_.+! *'(),]|(?:%[a-fA-F\d]{2}))|[;?&=])*))?@)?(?:(?:(?:(?:(?:[a-zA-Z\d](?:( ?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA- Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d+))?))/?)|(?:gopher://(? :(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z ](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(? :\d+))?)(?:/(?:[a-zA-Z\d$\-_.+!*'(),;/?:@&=]|(?:%[a-fA-F\d]{2}))(?:(?: (?:[a-zA-Z\d$\-_.+!*'(),;/?:@&=]|(?:%[a-fA-F\d]{2}))*)(?:%09(?:(?:(?:[ a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[;:@&=])*)(?:%09(?:(?:[a-zA- Z\d$\-_.+!*'(),;/?:@&=]|(?:%[a-fA-F\d]{2}))*))?)?)?)?)|(?:wais://(?:(? :(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](? :(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d +))?)/(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))*)(?:(?:/(?:(?:[ a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))*)/(?:(?:[a-zA-Z\d$\-_.+!*'() ,]|(?:%[a-fA-F\d]{2}))*))|\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA- F\d]{2}))|[;:@&=])*))?)|(?:mailto:(?:(?:[a-zA-Z\d$\-_.+!*'(),;/?:@&=]| (?:%[a-fA-F\d]{2}))+))|(?:file://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA- Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)) |(?:(?:\d+)(?:\.(?:\d+)){3}))|localhost)?/(?:(?:(?:(?:[a-zA-Z\d$\-_.+! *'(),]|(?:%[a-fA-F\d]{2}))|[?:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'() ,]|(?:%[a-fA-F\d]{2}))|[?:@&=])*))*))|(?:prospero://(?:(?:(?:(?:(?:[a- zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d ]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d+))?)/(?:(?:( ?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[?:@&=])*)(?:/(?:(?:(? :[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[?:@&=])*))*)(?:(?:;(?:(?: (?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[?:@&])*)=(?:(?:(?:[a-zA -Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[?:@&])*)))*)|(?:ldap://(?:(?:(? :(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](? :(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d +))?))?/(?:(?:(?:(?:(?:(?:(?:[a-zA-Z\d]|%(?:3\d|[46][a-fA-F\d]|[57][Aa \d]))|(?:%20))+|(?:OID|oid)\.(?:(?:\d+)(?:\.(?:\d+))*))(?:(?:%0[Aa])?( ?:%20)*)=(?:(?:%0[Aa])?(?:%20)*))?(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a- fA-F\d]{2}))*))(?:(?:(?:%0[Aa])?(?:%20)*)\+(?:(?:%0[Aa])?(?:%20)*)(?:( ?:(?:(?:(?:[a-zA-Z\d]|%(?:3\d|[46][a-fA-F\d]|[57][Aa\d]))|(?:%20))+|(? :OID|oid)\.(?:(?:\d+)(?:\.(?:\d+))*))(?:(?:%0[Aa])?(?:%20)*)=(?:(?:%0[ Aa])?(?:%20)*))?(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))*)))*) (?:(?:(?:(?:%0[Aa])?(?:%20)*)(?:[;,])(?:(?:%0[Aa])?(?:%20)*))(?:(?:(?: (?:(?:(?:[a-zA-Z\d]|%(?:3\d|[46][a-fA-F\d]|[57][Aa\d]))|(?:%20))+|(?:O ID|oid)\.(?:(?:\d+)(?:\.(?:\d+))*))(?:(?:%0[Aa])?(?:%20)*)=(?:(?:%0[Aa ])?(?:%20)*))?(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))*))(?:(? :(?:%0[Aa])?(?:%20)*)\+(?:(?:%0[Aa])?(?:%20)*)(?:(?:(?:(?:(?:[a-zA-Z\d ]|%(?:3\d|[46][a-fA-F\d]|[57][Aa\d]))|(?:%20))+|(?:OID|oid)\.(?:(?:\d+ )(?:\.(?:\d+))*))(?:(?:%0[Aa])?(?:%20)*)=(?:(?:%0[Aa])?(?:%20)*))?(?:( ?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))*)))*))*(?:(?:(?:%0[Aa])?( ?:%20)*)(?:[;,])(?:(?:%0[Aa])?(?:%20)*))?)(?:\?(?:(?:(?:(?:[a-zA-Z\d$\ -_.+!*'(),]|(?:%[a-fA-F\d]{2}))+)(?:,(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:% [a-fA-F\d]{2}))+))*)?)(?:\?(?:base|one|sub)(?:\?(?:((?:[a-zA-Z\d$\-_.+ !*'(),;/?:@&=]|(?:%[a-fA-F\d]{2}))+)))?)?)?)|(?:(?:z39\.50[rs])://(?:( ?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z]( ?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\ d+))?)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))+)(?:\+(? :(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))+))*(?:\?(?:(?:[a-zA-Z\d $\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))+))?)?(?:;esn=(?:(?:[a-zA-Z\d$\-_.+!* '(),]|(?:%[a-fA-F\d]{2}))+))?(?:;rs=(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[ a-fA-F\d]{2}))+)(?:\+(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))+ ))*)?))|(?:cid:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[;? :@&=])*))|(?:mid:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[ ;?:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[;?: @&=])*))?)|(?:vemmi://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a- zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+) (?:\.(?:\d+)){3}))(?::(?:\d+))?)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(? :%[a-fA-F\d]{2}))|[/?:@&=])*)(?:(?:;(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(? :%[a-fA-F\d]{2}))|[/?:@&])*)=(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA -F\d]{2}))|[/?:@&])*))*))?)|(?:imap://(?:(?:(?:(?:(?:(?:(?:[a-zA-Z\d$\ -_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[&=~])+)(?:(?:;[Aa][Uu][Tt][Hh]=(?:\*| (?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[&=~])+))))?)|(?:( ?:;[Aa][Uu][Tt][Hh]=(?:\*|(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\ d]{2}))|[&=~])+)))(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2} ))|[&=~])+))?))@)?(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z \d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\ .(?:\d+)){3}))(?::(?:\d+))?))/(?:(?:(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),] |(?:%[a-fA-F\d]{2}))|[&=~:@/])+)?;[Tt][Yy][Pp][Ee]=(?:[Ll](?:[Ii][Ss][ Tt]|[Ss][Uu][Bb])))|(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{ 2}))|[&=~:@/])+)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2} ))|[&=~:@/])+))?(?:(?:;[Uu][Ii][Dd][Vv][Aa][Ll][Ii][Dd][Ii][Tt][Yy]=(? :[1-9]\d*)))?)|(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))| [&=~:@/])+)(?:(?:;[Uu][Ii][Dd][Vv][Aa][Ll][Ii][Dd][Ii][Tt][Yy]=(?:[1-9 ]\d*)))?(?:/;[Uu][Ii][Dd]=(?:[1-9]\d*))(?:(?:/;[Ss][Ee][Cc][Tt][Ii][Oo ][Nn]=(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[&=~:@/])+)) )?)))?)|(?:nfs:(?:(?://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a -zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+ )(?:\.(?:\d+)){3}))(?::(?:\d+))?)(?:(?:/(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_. !~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~* '(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))?)|(?:/(?:(?:(?:(?:(?:[a-zA -Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\ d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))|(?:(?:(?:(?:(?:[a -zA-Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA -Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))) ``` Given its complexibility, I think you should go the urlparse way. For completeness, here's the pseudo-BNF of the above regex (as a documentation): ``` ; The generic form of a URL is: genericurl = scheme ":" schemepart ; Specific predefined schemes are defined here; new schemes ; may be registered with IANA url = httpurl | ftpurl | newsurl | nntpurl | telneturl | gopherurl | waisurl | mailtourl | fileurl | prosperourl | otherurl ; new schemes follow the general syntax otherurl = genericurl ; the scheme is in lower case; interpreters should use case-ignore scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] schemepart = *xchar | ip-schemepart ; URL schemeparts for ip based protocols: ip-schemepart = "//" login [ "/" urlpath ] login = [ user [ ":" password ] "@" ] hostport hostport = host [ ":" port ] host = hostname | hostnumber hostname = *[ domainlabel "." ] toplabel domainlabel = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit toplabel = alpha | alpha *[ alphadigit | "-" ] alphadigit alphadigit = alpha | digit hostnumber = digits "." digits "." digits "." digits port = digits user = *[ uchar | ";" | "?" | "&" | "=" ] password = *[ uchar | ";" | "?" | "&" | "=" ] urlpath = *xchar ; depends on protocol see section 3.1 ; The predefined schemes: ; FTP (see also RFC959) ftpurl = "ftp://" login [ "/" fpath [ ";type=" ftptype ]] fpath = fsegment *[ "/" fsegment ] fsegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] ftptype = "A" | "I" | "D" | "a" | "i" | "d" ; FILE fileurl = "file://" [ host | "localhost" ] "/" fpath ; HTTP httpurl = "http://" hostport [ "/" hpath [ "?" search ]] hpath = hsegment *[ "/" hsegment ] hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ] search = *[ uchar | ";" | ":" | "@" | "&" | "=" ] ; GOPHER (see also RFC1436) gopherurl = "gopher://" hostport [ / [ gtype [ selector [ "%09" search [ "%09" gopher+_string ] ] ] ] ] gtype = xchar selector = *xchar gopher+_string = *xchar ; MAILTO (see also RFC822) mailtourl = "mailto:" encoded822addr encoded822addr = 1*xchar ; further defined in RFC822 ; NEWS (see also RFC1036) newsurl = "news:" grouppart grouppart = "*" | group | article group = alpha *[ alpha | digit | "-" | "." | "+" | "_" ] article = 1*[ uchar | ";" | "/" | "?" | ":" | "&" | "=" ] "@" host ; NNTP (see also RFC977) nntpurl = "nntp://" hostport "/" group [ "/" digits ] ; TELNET telneturl = "telnet://" login [ "/" ] ; WAIS (see also RFC1625) waisurl = waisdatabase | waisindex | waisdoc waisdatabase = "wais://" hostport "/" database waisindex = "wais://" hostport "/" database "?" search waisdoc = "wais://" hostport "/" database "/" wtype "/" wpath database = *uchar wtype = *uchar wpath = *uchar ; PROSPERO prosperourl = "prospero://" hostport "/" ppath *[ fieldspec ] ppath = psegment *[ "/" psegment ] psegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] fieldspec = ";" fieldname "=" fieldvalue fieldname = *[ uchar | "?" | ":" | "@" | "&" ] fieldvalue = *[ uchar | "?" | ":" | "@" | "&" ] ; Miscellaneous definitions lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" alpha = lowalpha | hialpha digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" safe = "$" | "-" | "_" | "." | "+" extra = "!" | "*" | "'" | "(" | ")" | "," national = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`" punctuation = "" | "#" | "%" | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f" escape = "%" hex hex unreserved = alpha | digit | safe | extra uchar = unreserved | escape xchar = unreserved | reserved | escape digits = 1*digit ```
How do you validate a URL with a regular expression in Python?
[ "", "python", "regex", "google-app-engine", "" ]
I am trying to construct a LINQ query, with expression trees, to do the following: I have a field in my ItemCode table called Labels, an example of the data contained in this field is "lamps lighting chandelier". I want to allow the user to type in some text, i.e. "Red Lamp", and be able to search the Labels field, of the ItemCode, table where the text contains "Red" or "Lamp". I am trying to recommend selections to the user, and this, while basic, is a good first step ... just need some help constructing the query. I am using CSLA as my framework, here is an example of the code I currently have: ``` IQueryable<Data.ItemCode> query = ctx.DataContext.ItemCodes; // // ItemCodeId // if (criteria.Name != null) query = query.Where(row => row.ItemCodeId.Contains(criteria.ItemCodeId)); // // Name // if (criteria.Name != null) query = query.Where(row => row.Name.Contains(criteria.Name)); var data = query.Select(row => ItemCodeInfo.FetchItemCodeInfo(row)); this.AddRange(data); ``` Thanks in advance!
We have decided you go the stored procedure route for this advanced functionality. Thanks for everyone's input!
EDIT: Updated to reflect your example code Assuming your Criteria object has a field called Labels, which is the search string (eg 'Red Lamp') then: ``` var rows = query.ToList() // work around for local sequences error .Where(row => row.Labels.Split(' ') .Intersect(Criteria.Labels.Split(' ')) .Count()>0); this.AddRange(rows); ``` This will select rows where the labels field contains any of the words in the criteria search string. It assumes that words are separated by spaces in both the Labels field and the criteria string. It won't do partial word matching eg it won't find a record with a label of 'redlamp' if the search string provided is 'red lamp'
How to search a varchar field, using LINQ, to build a list of recommendations
[ "", "c#", "sql-server", "linq", "linq-to-sql", "" ]
I'm trying to add details to a database by using ajax and table dynamic rows. e.g. ---- {Customer: dropdown menu} | {Description: textarea} | *delete* **Add New Customer** --- When the user clicks it shows the drop down menu of all available customers. when you click away it just shows the select customer name (not the dropdown menu) Similarly with the description i want on click to allow them to edit the description of the text area but when you click away it only shows the text you just entered. (not the text area outline) Add new customer button creates a new empty row. What libraries or examples can help me get started with this? I saw this recently in an application recently. In this application it was possible to add new items/rows via ajax and dynamic HTML.
You should be able to do that easily enough using jQuery (look at the selectors, events & manipulation in their docs). For example, for the dropdown ``` <span id="customer-name"></span> <select name="customer-list" id="customer-list"> <option class="name" value="cust-1">Frank Frankson</option> <option class="name" value="cust-2">John Johnson</option> </select> ``` And the jQuery : ``` $('.name').click(function(){ $('#customer-name').text($(this).text()); $('#customer-list').hide(); }); ``` In that function you could do something with the option element value if needed (an ajax post or whatever). The principal for changing the Text Area description would be the same (you could grab the text out of the textarea, add it to a div & hide the textarea; if they need to edit again, just show the textarea & hide the div)
Use jQuery. Use the [tokenizing autocomplete plugin for jQuery](http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry/) For the inplace edit use [Jeditable](http://www.appelsiini.net/projects/jeditable). I'd stay away from drop downs, they are almost always bad design, whether in a menu or selecting from a long list of options. For something like a list of customers which is hopefully likely to be long it is an awful choice of a UI component. The only time that it really makes sense to use a drop down is when the list of options is short **and** well known. So for it to be acceptable it probably has to be a list of options which rarely if ever changes, is less than 10 or so items long, and is used frequently (so it is well known). Drop downs are painful.
Create editable new rows to a table
[ "", "javascript", "jquery", "html", "ajax", "" ]
Say I've got an array of `User`: ``` class User : IUserDowngraded { public Int32 Id { get; set; } } ``` ... with downgraded functionality done by casting the objects to a specific interface: ``` interface IUserDowngraded { Int32 Id { get; } // removes set functionality from property } ``` ... how would I cast those downgraded objects (`IUserDowngraded`) to `User` objects in a single line of code, using LINQ? What I'm trying to avoid is this: ``` // pseudo-code alert: IUserDowngraded[] downgradedUsers { IUserDowngraded, IUserDowngraded, ... }; var upgradedUsers = new User[downgradedUsers.Count()]; Int32 i = 0; foreach (IUserDowngraded du in downgradedUsers) { upgradedUsers[i] = (User)user; i++; } ```
``` var upgradedUsers = downgradedUsers.Cast<User>(); ``` Append a call to `ToArray()` if you want `upgradedUsers` as an array, of course.
[use the cast method....](http://www.linqexchange.com/post/2008/05/How-to-Convert-a-Collection-From-One-Type-to-Another-Type-Using-LINQ-Cast.aspx) ``` SampleIntList = SampleStringList.Cast<int>().Select(x => Convert.ToInt32(x)).ToList(); ```
Typecast each object in an array on a single line of code, using LINQ
[ "", "c#", "linq", "" ]
Because this is my first attempt at an extension method that seems quite useful to me, I just want to make sure I'm going down the right route ``` public static bool EqualsAny(this string s, string[] tokens, StringComparison comparisonType) { foreach (string token in tokens) { if (s.Equals(token, comparisonType)) { return true; } } return false; } ``` Called by ``` if (queryString["secure"].EqualsAny(new string[] {"true","1"}, StringComparison.InvariantCultureIgnoreCase)) { parameters.Protocol = Protocol.https; } ``` **EDIT:** Some excellent suggestions coming through, exactly the sort of thing I was looking for. Thanks **EDIT:** I have decided on the following implementation ``` public static bool EqualsAny(this string s, StringComparison comparisonType, params string[] tokens) { // for the scenario it is more suitable for the code to continue if (s == null) return false; return tokens.Any(x => s.Equals(x, comparisonType)); } public static bool EqualsAny(this string s, params string[] tokens) { return EqualsAny(s, StringComparison.OrdinalIgnoreCase, tokens); } ``` I preferred using params over IEnumerable because it simplified the calling code ``` if (queryString["secure"].EqualsAny("true","1")) { parameters.Protocol = Protocol.https; } ``` A far cry on the previous ``` if (queryString["secure"] != null) { if (queryString["secure"] == "true" || queryString["secure"] == "1") { parameters.Protocal = Protocal.https; } } ``` Thank you again!
``` public static bool EqualsAny( this string s, StringComparison comparisonType, params string[] tokens) { foreach (string token in tokens) { if (s.Equals(token, comparisonType)) { return true; } } return false; } ``` With params, you don't have to force your strings into an array first. ``` var match = "loool".EqualsAny(StringComparison.Ordinal, "hurf", "Durf"); ``` Linq-ified (JC + me) with a NRE (framework standard): ``` public static bool EqualsAny( this string s, StringComparison comparisonType, params string[] tokens) { if(s == null) throw new NullReferenceException("s"); return tokens.Any(x=> s.Equals(x, comparisonType)); } ```
Yes! First, you need to check s for null. Also, let it accept any `IEnumerable<string>` for tokens rather than just an array, and then use other linq operators to do the check: ``` public static bool EqualsAny(this string s, IEnumerable<string> tokens, StringComparison comparisonType) { if (s== null) return false; return tokens.Any(t => s.Equals(t, comparisonType)); } ``` --- Thinking about how to handle a `null` value for s, there's a third option no one's used yet: ``` public static bool EqualsAny(this string s, IEnumerable<string> tokens, StringComparison comparisonType) { if (s== null) return tokens.Any(t => t == null); return tokens.Any(t => s.Equals(t, comparisonType)); } ``` --- Finally, regarding your chosen implementation: if you're going to have overloads, you might as well have IEnumerable overloads as well, and have your `params` code call those.
My first extension method, could it be written better?
[ "", "c#", "c#-3.0", "extension-methods", "" ]
I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files. I run the following Sed script called replace unsuccessfully ``` s/Masi/Bond/ ``` in Zsh by ``` sed -f PATH/replace PATH2/project/** ``` It gives me all files, also the ones which do not have Masi, as an output. Sed is not necessarily the best tool for the task. I am interested in Python and Perl. **How would you do the replacement in Sed/Perl/Python,** such that only the file contents are changed?
**To replace the word in all files found in the current directory and subdirectories** ``` perl -p -i -e 's/Masi/Bond/g' $(grep -rl Masi *) ``` The above won't work if you have spaces in filenames. Safer to do: ``` find . -type f -exec perl -p -i -e 's/Masi/Bond/g' {} \; ``` or in Mac which has spaces in filenames ``` find . -type f -print0 | xargs -0 perl -p -i -e 's/Masi/Bond/g' ``` **Explanations** * -p means print or die * -i means "do not make any backup files" * -e allows you to run perl code in command line
Why not just pass the `-i` option (`man sed`) to sed and be done with it? If it doesn't find Masi in a file, the file will just be rewritten with no modification. Or am I missing something? If you don't want to replace the files' contents inline (which is what the `-i` will do) you can do exactly as you are now, but throw a `grep` & `xargs` in front of it: ``` grep -rl Masi PATH/project/* | xargs sed -f PATH/replace ``` Lots of options, but do **not** write an entire perl script for this (I'll give the one-liner a pass ;)). `find`, `grep`, `sed`, `xargs`, etc. will always be more flexible, IMHO. In response to comment: ``` grep -rl Masi PATH/project/* | xargs sed -n -e '/Masi/ p' ```
Unable to replace the word in a given folder's contents by Sed/Python/Perl
[ "", "python", "perl", "sed", "replace", "" ]
Because I've overloaded the `operator++` for an iterator class ``` template<typename T> typename list<T>::iterator& list<T>::iterator::operator++() { //stuff } ``` But when I try to do ``` list<int>::iterator IT; IT++; ``` I get a warning about there being no postifx `++`, using prefix form. How can I specifically overload the prefix/postifx forms?
Write a version of the same operator overload, but give it a parameter of type `int`. You don't have to do anything with that parameter's value. If you're interested in some history of how this syntax was arrived out, [there's a snippet of it here](http://groups.google.com/group/comp.lang.c++.moderated/msg/6da0765460749c4f?dmode=source).
<http://www.devx.com/tips/Tip/12515> ``` class Date { //... public: Date& operator++(); //prefix Date& operator--(); //prefix Date operator++(int unused); //postfix Date operator--(int unused); //postfix }; ```
How to differentiate (when overloading) between prefix and postfix forms of operator++? (C++)
[ "", "c++", "operator-overloading", "postfix-operator", "prefix-operator", "" ]
I want to create a method that takes in an `Enum` type, and returns all it's members in an array, How to create such a function? Take for example, I have these two enums: ``` public enum Family { Brother, Sister, Father } public enum CarType { Volkswagen, Ferrari, BMW } ``` How to create a function `GetEnumList` so that it returns 1. `{Family.Brother, Family.Sister, Family.Father}` for the first case. 2. `{CarType.Volkswagen, CarType.Ferrari, CarType.BMW}` for the second case. I tried : ``` private static List<T> GetEnumList<T>() { var enumList = Enum.GetValues(typeof(T)) .Cast<T>().ToList(); return enumList; } ``` But I got an `InvalidOperationException`: > System.InvalidOperationException : Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true. > at System.Reflection.RuntimeMethodInfo.ThrowNoInvokeException() > at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) > at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) > at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) **Edit: The above code is working fine-- the reason I got an exception was because profiler caused me the bug. Thank you all for your solutions.**
Same as the other answer but updated for modern C#: ``` public static List<TEnum> GetEnumList<TEnum>() where TEnum : Enum => ((TEnum[])Enum.GetValues(typeof(TEnum))).ToList(); ```
Here is the full code: ``` public enum Family { Brother, Sister, Father } public enum CarType { Volkswagen, Ferrari, BMW } static void Main(string[] args) { Console.WriteLine(GetEnumList<Family>()); Console.WriteLine(GetEnumList<Family>().First()); Console.ReadKey(); } private static List<T> GetEnumList<T>() { T[] array = (T[])Enum.GetValues(typeof(T)); List<T> list = new List<T>(array); return list; } ```
How to get all values of an enum?
[ "", "c#", "enums", "" ]
I am wondering how in practice other SOers tend to deal with and/or prevent exceptions. In what situations do you prevent exceptions, and how? In what situations do you catch exceptions? I usually prevent 'NullPointerExceptions' (and other similar ones) by, well, essentially saying `if(foo!=null) {...}` I find that in most situations this is less bulky than everything involved in using a try-catch block. I use try-catch blocks when the potential exceptions are more complex, or more numerous.
In my opinion, it only makes sense to prevent a NullPointerException (for example) when a reference being null (again, for example) actually represents a **valid program state**. If it does not, you should **not** prevent it from happening, because in that case you **want** the program to die hard. In Java in particular, certain exceptions descending from RuntimeException (such as IllegalArgumentException) are really meant to signal programming errors, conditions that should not happen if your program is correct. I try to follow this. If I am writing a method that places restrictions on its arguments, I will not try to avoid throwing an exception. I will throw one aggressively.
If you can prevent exceptions, then it's better programming practice to do so. For example, any NullPointerException usually indicates a programming error, IMO. (Which is one reason it's a RuntimeException.) Exceptions are more useful when you expect to be able to detect a failure condition in one layer of code, but you don't want to handle the failure condition there but instead at a somewhat higher level of code. That is, you intend to throw the Exception more than one frame up the stack -- or all of the way up the stack. Exceptions are also useful when you do not expect the program to be able to meaningfully handle the problem.
Preventing exceptions vs. catching exceptions in Java
[ "", "java", "exception", "error-handling", "" ]
I want to do a one time callback registration within Observer. I don't want to do the registration inside init or other function. I don't know if there is a class level equivalent for init ``` class Observer: @classmethod def on_new_user_registration(new_user): #body of handler... # first I try NewUserRegistered().subscribe \ (Observer.on_new_user_registration) #gives NameError for Observer #so I try NewUserRegistered().subscribe(on_new_user_registration) #says not callable #neither does this work NewUserRegistered().subscribe(__metaclass__.on_new_user_registration) class BaseEvent(object): _subscriptions = {} def __init__(self, event_info = None): self.info = event_info def fire(self): for callback in self._subscriptions[event_type]: callback(event_info) def subscribe(self, callback): if not callable(callback): raise Exception(str(callback) + 'is not callable') existing = self._subscriptions.get(self.__class__, None) if not existing: existing = set() self._subscriptions[self.__class__] = existing existing.add(callback) class NewUserRegistered(BaseEvent): pass ```
I've come to accept that python isn't very intuitive when it comes to functional programming within class definitions. See [this question](https://stackoverflow.com/questions/707090/decorators-and-in-class). The problem with the first method is that Observer doesn't exist as a namespace until the class has been built. The problem with the second is that you've made a class method that doesn't really do what it's supposed to until after the namespace has been created. (I have no idea why you're trying the third.) In both case neither of these things occurs until after the class definition of Observer has been populated. This might sound like a sad constraint, but it's really not so bad. Just register *after* the class definition. Once you realize that it's not bad style to perform certain initialization routines on classes in the body of the module but outside the body of the class, python becomes a lot friendlier. Try: class Observer: ``` # Define the other classes first class Observer: @classmethod def on_new_user_registration(new_user): #body of handler... NewUserRegistered().subscribe(Observer.on_new_user_registration) ``` Because of the way modules work in python, you are guaranteed that this registration will be performed once and only once (barring process forking and maybe some other irrelevant boundary cases) wherever Observer is imported.
I suggest to cut down on the number of classes -- remember that Python isn't Java. Every time you use `@classmethod` or `@staticmethod` you should stop and think about it since these keywords are quite rare in Python. Doing it like this works: ``` class BaseEvent(object): def __init__(self, event_info=None): self._subscriptions = set() self.info = event_info def fire(self, data): for callback in self._subscriptions: callback(self.info, data) def subscribe(self, callback): if not callable(callback): raise ValueError("%r is not callable" % callback) self._subscriptions.add(callback) return callback new_user = BaseEvent() @new_user.subscribe def on_new_user_registration(info, username): print "new user: %s" % username new_user.fire("Martin") ``` If you want an Observer class, then you can do it like this: class Observer: ``` @staticmethod @new_user.subscribe def on_new_user_registration(info, username): print "new user: %s" % username ``` But note that the static method does not have access to the protocol instance, so this is probably not very useful. You can not subscribe a method bound to an object instance like this since the object wont exist when the class definition is executed. But you can of course do this: ``` class Observer: def on_new_user_registration(self, info, username): print "new user: %s" % username o = Observer() new_user.subscribe(o.on_new_user_registration) ``` where we use the bound `o.on_new_user_registration` as argument to subscribe.
How do I refer to a class method outside a function body in Python?
[ "", "python", "" ]
I'm allowing authenticated users to upload image files with my PHP application. Assume I've built in the necessary security to make sure the file itself is valid, is there a possibility of the http transmitted file to be intercepted in some way? If so, how can I protect the transmission of the file? Would HTTPS be the way to go? Also, the web server the application resides on can only be accessed by authenticated users. Does this mean that the http stream of data is also protected? It would seem to me that it is.
If you use HTTPS, the whole communication after establishing the connection will be transfered encrypted over SSL. Thus the file uploads will be sent encrypted too.
If there is [Main in The Middle](http://en.wikipedia.org/wiki/Man-in-the-middle_attack), he can sniff the contents of the transmitted file. You must use a secure connection in order to prevent this. So HTTPS would be the answer.
How do I make data uploaded by PHP safe during transmission?
[ "", "php", "security", "http", "file", "https", "" ]
I'm relatively new to working with XML and am working with some rather large documents using the `javax.xml.parsers.SAXParser` . The thing is: The information I need is near the top of the XML file and I don't *need* to parse the entire document. -- What is the "best" way to stop parsing a file when the relevant information has been identified? (So far the only way I can think of is to throw an exception.)
Throwing an exception is the only way to stop it. See [this IBM XML tip](http://www.ibm.com/developerworks/xml/library/x-tipsaxstop/) for an example. You should probably implement your own exception to signal an intention to stop further processing. That way you will be able to distinguish between an intentional halt to processing, and an unintentional halt (when encountering some unexpected scenario etc.)
You can use StAX. It actually stops the parsing process any time without throwing any exception. Check out: http ://www.xml.com/pub/a/2003/09/17/stax.html http ://jcp.org/en/jsr/detail?id=173
SAX Premature End to a Parse?
[ "", "java", "xml", "sax", "" ]
The official Python 2.5 on Windows was build with Visual Studio.Net 2003, which uses 32 bit time\_t. So when the year is > 2038, it just gives exceptions. Although this is fixed in Python 2.6 (which changed time\_t to 64 bit with VS2008), I'd like to use 2.5 because many modules are already compiled for it. So here's my question - is there any solution to easily let my program handle year > 2038 and still using official Python 2.5? For example some pre-made libraries like `"time64"` or "longtime" etc... Please do not tell me to upgrade to 2.6+ or forget about the bug - I have my reason to need to make it work, that's why I post the question here.
The best solution I've found is to get a source copy of Python 2.5, and re-compile the time module with compilers which defaults time\_t to 64 bit, for example VS2005 or VS2008 (may also configure the C runtime to prevent side-by-side issue).
The `datetime` module in the standard library should work fine for you. What do you need from module `time` that `datetime` doesn't offer?
How to use time > year 2038 on official Windows Python 2.5
[ "", "python", "time", "python-2.5", "time-t", "year2038", "" ]
I'm attempting to issue a 301 redirect when a user requests <http://www.mysite.com/Default.aspx> to <http://www.mysite.com/> The issue I'm having is that every property I can find within Request (Request.Url, Request.RawUrl, etc) is identical for those two requests. Edit for further clarification: This is on a shared web host, I can't install ISAPI extensions. One more edit. Apparently the first tech support guy I talked to at the host didn't know what he was talking about, they have ISAPI rewrite installed.
Just use a url rewriting ISAPI filter. It's painless. [This page on Scott Gu's blog](http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx) contains pretty much all the info you need.
[Steve Wortham's Blog](http://swortham.blogspot.com/2008/12/redirecting-default-page-defaultaspx-to.html) describes how he addressed the same issue. He used [Ionic's free Isapi Rewrite Filter](http://www.codeplex.com/IIRF)
How do you tell when IIS is applying the "Default Page" setting in ASP.NET (C#)
[ "", "c#", "asp.net", "iis", "" ]
I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you can do it like this: ``` def read_file(file, delete_after = false) # code end ``` Does this work in JavaScript? ``` function read_file(file, delete_after = false) { // Code } ```
From [ES6/ES2015](https://www.ecma-international.org/ecma-262/6.0/), default parameters are in the language specification. ``` function read_file(file, delete_after = false) { // Code } ``` just works. Reference: [Default Parameters - MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters) > Default function parameters allow formal parameters to be initialized with default values if **no value** or **undefined** is passed. In ES6, you can [simulate default *named* parameters via destructuring](http://exploringjs.com/es6/ch_parameter-handling.html#sec_named-parameters): ``` // the `= {}` below lets you call the function without any parameters function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A) // Use the variables `start`, `end` and `step` here ··· } // sample call using an object myFor({ start: 3, end: 0 }); // also OK myFor(); myFor({}); ``` **Pre ES2015**, There are a lot of ways, but this is my preferred method — it lets you pass in anything you want, including false or null. (`typeof null == "object"`) ``` function foo(a, b) { a = typeof a !== 'undefined' ? a : 42; b = typeof b !== 'undefined' ? b : 'default_b'; ... } ```
``` function read_file(file, delete_after) { delete_after = delete_after || "my default here"; //rest of code } ``` This assigns to `delete_after` the value of `delete_after` if it is not a *falsey* value otherwise it assigns the string `"my default here"`. For more detail, check out [Doug Crockford's survey of the language and check out the section on Operators](http://crockford.com/javascript/survey.html). This approach does not work if you want to pass in a *falsey* value i.e. `false`, `null`, `undefined`, `0` or `""`. If you require *falsey* values to be passed in you would need to use the method in [Tom Ritter's answer](https://stackoverflow.com/questions/894860/how-do-i-make-a-default-value-for-a-parameter-to-a-javascript-function/894877#894877). When dealing with a number of parameters to a function, it is often useful to allow the consumer to pass the parameter arguments in an object and then *merge* these values with an object that contains the default values for the function ``` function read_file(values) { values = merge({ delete_after : "my default here" }, values || {}); // rest of code } // simple implementation based on $.extend() from jQuery function merge() { var obj, name, copy, target = arguments[0] || {}, i = 1, length = arguments.length; for (; i < length; i++) { if ((obj = arguments[i]) != null) { for (name in obj) { copy = obj[name]; if (target === copy) { continue; } else if (copy !== undefined) { target[name] = copy; } } } } return target; }; ``` to use ``` // will use the default delete_after value read_file({ file: "my file" }); // will override default delete_after value read_file({ file: "my file", delete_after: "my value" }); ```
Set a default parameter value for a JavaScript function
[ "", "javascript", "function", "parameters", "arguments", "default-parameters", "" ]
**When using HTML custom attributes it doesn't works in Chrome.** What I mean is, suppose I have this HTML: ``` <div id="my_div" my_attr="1"></div> ``` If I try to get this attribute with JavaScript in Chrome, I get *undefined* ``` alert( document.getElementById( "my_div" ).my_attr ); ``` In IE it works just fine.
Retrieving it via getAttribute(): ``` alert(document.getElementById( "my_div" ).getAttribute("my_attr")); ``` Works fine for me across IE, FF and Chrome.
IE is about the only browser I've seen that honor attributes that do not conform to the HTML DTD schema. <http://www.webdeveloper.com/forum/showthread.php?t=79429> However, if you're willing to write a custom DTD, you can get this to work. This is a good article for getting started down that direction: * <http://www.alistapart.com/articles/scripttriggers/>
HTML Custom Attributes Not Working in Chrome
[ "", "javascript", "html", "google-chrome", "" ]
I'm almost done with this, just a few last hiccups. I now need to delete all records from a table except for the top 1 where readings\_miu\_id is the "DISTINCT" column. In other words words i need to delete all records from a table other than the first DISTINCT readings\_miu\_id. I am assuming all I need to do is modify the basic delete statement: ``` DELETE FROM analyzedCopy2 WHERE readings_miu_id = some_value ``` But I can't figure out how to change the some\_column=some\_value part to something like: ``` where some_column notequal to (select top 1 from analyzedCopy2 as A where analyzedCopy2.readings_miu_id = A.readings_miu_id) ``` and then I need to figure out how to use an UPDATE statement to update a table (analyzedCopy2) from a query (which is where all of the values I want stored into column RSSI in table analyzedCopy2 are currently located). I've tried this: ``` UPDATE analyzedCopy2 from testQuery3 SET analyzedCopy2.RSSI = (select AvgOfRSSI from testQuery3 INNER JOIN analyzedCopy2 on analyzedCopy2.readings_miu_id = testQuery3.readings_miu_id where analyzedCopy2.readings_miu_id = testQuery3.readings_miu_id) where analyzedCopy2.readings_miu_id = testQuery3.readings_miu_id ``` but apparently I can't use FROM inside of an update statement. Any thoughts? I'm sure I'm going about this a very nonstandard (and possibly if not probably the flat out wrong) way but I'm not being allowed to use vb.net2008 to pull and manipulate then store the data like I would like to so I'm stuck right now using sql statements in ms-access which is a good learning experience (Even if trying to do such odd things as I've been having to do in sql statements is making me beat my head against my deck *figuratively of course*)
MS Access UPDATE sql statements cannot reference queries, but they can reference tables. So the thing to do is store the query results into a table. ``` SELECT YourQuery.* INTO TempTable1 FROM YourQuery ``` Now you can use TempTable1 in an UPDATE query: ``` UPDATE TargetTable INNER JOIN TempTable1 ON TempTable1.TargetTableId = TargetTable.Id SET TargetTable.TargetField = TempTable1.SourceField ``` See [my answer to this question](https://stackoverflow.com/questions/871905/use-select-inside-a-update-query).
I don't have a copy of access on this machine, and it's been a few years since I dabbled in access, so I'm taking a wild stab here, but can you do a ``` delete from analyzedCopy2 where readings_miu_id not in (select top 1 readings_miu_id from analyzedCopy2 order by...) ``` (you'll need the order by to get the proper top 1 record, order by the id maybe?) I've got no hope of helping you with the second one without a copy of access. I know how I'd do it in TSQL, but access is a whole different kettle of wtf's :-)
MS-ACCESS: Deleting all rows except for top 1 and updating a table from a query
[ "", "sql", "ms-access", "sql-update", "" ]
I'm trying to write a web service client in c# which the webservice is Java Axis 1.4. Axis service requires the **Authorization: Basic Base64EncodedToken** header value in the HTTP Headers. I can't find a way to set this header in standart ways of consuming web services in visual studio.net, like normal WSDL generated refernce nor with WSE3.0 I can't use WCF as the project is developed using .net 2.0. Is there any way to do this ?
It seems the original author has found their solution, but for anyone else who gets here looking to add actual custom headers, if you have access to mod the generated Protocol code you can override `GetWebRequest`: ``` protected override System.Net.WebRequest GetWebRequest(Uri uri) { System.Net.WebRequest request = base.GetWebRequest(uri); request.Headers.Add("myheader", "myheader_value"); return request; } ``` Make sure you remove the `DebuggerStepThroughAttribute` attribute if you want to step into it.
Are we talking WCF here? I had issues where the service calls were not adding the http authorization headers, wrapping any calls into this statement fixed my issue. ``` using (OperationContextScope scope = new OperationContextScope(RefundClient.InnerChannel)) { var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(RefundClient.ClientCredentials.UserName.UserName + ":" + RefundClient.ClientCredentials.UserName.Password)); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; PaymentResponse = RefundClient.Payment(PaymentRequest); } ``` This was running SOAP calls to IBM ESB via .NET with basic auth over http or https. I hope this helps someone out because I had massive issues finding a solution online.
How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service
[ "", "c#", "web-services", "wsdl", "axis", "" ]
Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like ``` import svn from almighty_ctype_subversion_bindings svn.get( "\\rep\\project" ) ``` And how is this connected to pysvn project? Is this a same technology, or different technologies?
You need the Subversion source distribution, Python (>= 2.5), and [ctypesgen](http://code.google.com/p/ctypesgen/). Instructions for building the ctypes bindings are [here](http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/README). You will end up with a package called `csvn`, examples of it's use are [here](http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/examples/).
The whole point of ctypes is that you shouldn't need to have to compile anything anywhere. That said, the readme for the bindings mentions some dependencies and a build step. The bindings can be found in the Subversion source distribution at least, in `subversion/bindings/ctypes-python/`, with a distutils setup.py. They seem to be a successor / alternative of sorts to pysvn.
How to use subversion Ctypes Python Bindings?
[ "", "python", "svn", "" ]
In a SQL statement ( or procedure ) I want to collapse the rows of this table into a single comma delimited string. ``` simpleTable id value -- ----- 1 "a" 2 "b" 3 "c" ``` Collapse to: ``` "a, b, c" ```
You can concatenate using an embedded 'set' statement in a query: ``` declare @combined varchar(2000) select @combined = isnull(@combined + ', ','') + isnull(value,'') from simpleTable print @combined ``` (Note that the first isnull() initialises the string, and the second isnull() is especially important if there's any chance of nulls in the 'value' column, because otherwise a single null could wipe out the whole concatenation) (edited code and explanation after comments) **Edit (ten years later):** SQL Server 2017 introduced the [STRING\_AGG()](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017) function which provides an official way of concatenating strings from different rows. Like other aggregation functions such as COUNT(), it can be used with GROUP BY. So for the example above you could do: ``` select string_agg(value, ', ') from simpleTable ``` If you had some other column and you wanted to concatenate for values of that column, you would add a 'group by' clause, e.g: ``` select someCategory, string_agg(value, ', ') as concatValues from simpleTable group by someCategory ``` Note string\_agg will only work with SQL 2017 and above.
This will only work in MSSQL 2005+ ``` select value + ',' from simpletable for xml path ('') ``` ..one way to prevent the extra comma: ``` select case(row_number() over (order by id)) when 1 then value else ',' + value end from simpletable for xml path ('') ```
What is the best way to collapse the rows of a SELECT into a string?
[ "", "sql", "sql-server", "" ]
I have a Search Form that can search by a few different fields. The problem field is birthDate. On the form it is a string. In the SQL 2005 db it is a DateTime that can be null. The code below is sequential as far as declaring the variable on the form and then setting it. Then the call to the BLL and then the call to the DAL. On this line --> ``` dgvSearchResults.DataSource =ConnectBLL.BLL.Person.Search(_firstName,_middleName,_lastName,_sSN, (DateTime)_birthDate,_applicationID,_applicationPersonID,_fuzzy); ``` I am getting a *"Nullable object must have value"* error. I assume because I didn't give a Date param and then tried to Cast to a non-nullable DateTime. Correct? What can I do about it? There has to be a way around it. This exact same BLL & DAL work on the web app version. ## EDIT 1 A few things to note. I was under the impression that `DateTime?` was the same as `Nullable<DateTime>` Correct? Also, I don't see how I can put in an arbitrary value for a field like BirthDate. I suppose I could build in a bunch of filters in my business layer but that seems tho "Hack" way. Maybe not. Also, it bothers me that this same BLL and DAL with this same DB allow nulls in the BirthDate field in the WebApp version of this program. Any ideas there? The DB has *null* in it for those entries with out a date. ***Search.cs*** ``` public DateTime? _birthDate; _birthDate = null; if (datBirthDate.Text != string.Empty) _birthDate = Convert.ToDateTime(datBirthDate.Text); dgvSearchResults.DataSource=ConnectBLL.BLL.Person.Search(_firstName,_middleName,_lastName,_sSN, (DateTime)_birthDate,_applicationID,_applicationPersonID,_fuzzy); ``` ***ConnectBLL --> Person.vb*** ``` Public Shared Function Search(ByVal firstName As String, ByVal middleName As String, ByVal lastName As String, ByVal SSN As String, ByVal birthDate As Date, ByVal applicationId As Integer, ByVal applicationPersonId As String, ByVal fuzzy As Boolean) As Data.DataTable Try Dim tbl As Data.DataTable = DAL.Connect.SearchPerson(firstName, middleName, lastName, SSN, birthDate, applicationId, applicationPersonId, fuzzy) If tbl.Rows.Count > 0 Then tbl.DefaultView.Sort = "Last Name ASC, First Name ASC, Middle Name ASC" End If Return tbl Catch Throw End Try ``` End Function ***ConnectDAL --> Connect.vb*** ``` Public Shared Function SearchPerson(ByVal _FirstName As String, ByVal _MiddleName As String, ByVal _LastName As String, ByVal _SSN As String, ByVal _BirthDate As Date, ByVal _ApplicationID As Integer, ByVal _ApplicationPersonID As String, ByVal _Fuzzy As Boolean) As Data.DataTable Dim test As New clsSqlResponseTime Dim dt As New Data.DataTable Try Using cnn As New SqlClient.SqlConnection(ConnectROConnectionString) Dim cmd As New SqlClient.SqlCommand() cmd.Connection = cnn If _Fuzzy Then cmd.CommandText = strSearchPersonFuzzyStoredProcedure Else cmd.CommandText = strSearchPersonStoredProcedure End If cmd.CommandType = CommandType.StoredProcedure If Not IsNothing(_FirstName) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@FirstName", _FirstName)) If Not IsNothing(_MiddleName) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@MiddleName", _MiddleName)) If Not IsNothing(_LastName) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@LastName", _LastName)) If Not IsNothing(_SSN) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@SSN", _SSN)) If Not (_BirthDate = Date.MinValue) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@BirthDate", _BirthDate)) If Not IsNothing(_ApplicationPersonID) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@ApplicationID", _ApplicationID)) If Not IsNothing(_ApplicationPersonID) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@ApplicationPersonID", _ApplicationPersonID)) Dim da As New SqlClient.SqlDataAdapter(cmd) da.Fill(dt) End Using Catch Throw End Try test.Log("SearchPerson", "Connect") Return dt ``` End Function
It appears to me that you're not using the birthDate value at all until the third function, where it's being added to a Parameters collection. In that third function it's already being tested against Date.MinValue before adding it. Simply change the first function to this: ``` public DateTime _birthDate; if (string.IsNullOrEmpty(datBirthDate.Text)) _birthDate = DateTime.MinValue; else _birthDate = Convert.ToDateTime(datBirthDate.Text); dgvSearchResults.DataSource=ConnectBLL.BLL.Person.Search(_firstName,_middleName,_lastName,_sSN,_birthDate,_applicationID,_applicationPersonID,_fuzzy); ``` That's the easiest way out, but not necessarily the most correct. I would change all three functions to use a Nullable DateTime like so: Function 1 ``` public DateTime? _birthDate = null; if (!string.IsNullOrEmpty(datBirthDate.Text)) _birthDate = Convert.ToDateTime(datBirthDate.Text); dgvSearchResults.DataSource=ConnectBLL.BLL.Person.Search(_firstName,_middleName,_lastName,_sSN,_birthDate,_applicationID,_applicationPersonID,_fuzzy); ``` Function 2 and 3 definitions should look like: ``` Public Shared Function Search(ByVal firstName As String, ByVal middleName As String, ByVal lastName As String, ByVal SSN As String, ByVal birthDate As Nullable(Of Date), ByVal applicationId As Integer, ByVal applicationPersonId As String, ByVal fuzzy As Boolean) As Data.DataTable Public Shared Function SearchPerson(ByVal _FirstName As String, ByVal _MiddleName As String, ByVal _LastName As String, ByVal _SSN As String, ByVal _BirthDate As Nullable(Of Date), ByVal _ApplicationID As Integer, ByVal _ApplicationPersonID As String, ByVal _Fuzzy As Boolean) As Data.DataTable ``` And the line in Function 3 that uses the birthDate: ``` If (_BirthDate.HasValue) Then cmd.Parameters.Add(New SqlClient.SqlParameter("@BirthDate", _BirthDate.Value)) ```
You can do something like this: ``` dgvSearchResults.DataSource=ConnectBLL.BLL.Person.Search(_firstName,_middleName,_lastName,_sSN, _birthDate.HasValue ? _birthDate.Value : new DateTime() ,_applicationID,_applicationPersonID,_fuzzy); ``` Basically, if it's null, just default it to whatever the default of DateTime is (I believe it's 1/1/0001).
DateTime nullable exception as a parameter
[ "", "c#", "vb.net", "winforms", "parameters", "null", "" ]
I'm fixing a bug with Windows Vista 64 bits of a 32bit application, when I try to use the function Wow64DisableWow64FsRedirection(...) the compiler says 'undeclared identifier...'. I'm including the Windows.h header file and set \_WIN32\_WINNT to 0x0501. Any ideas? Thanks. EDIT: We're using MS Visual Studio 2003
Can you see this API in the header file? May be the Visual Studio you are using is not having updated header file, in which case you will need to do a LoadLibrary for Kernel32.dll and then GetProcAddress for the required function.
Your platform SDK files are probably too old to have that function. That function first appeared in the XP 64 bit platform SDK. You can get the latest SDK here: <http://www.microsoft.com/downloads/details.aspx?FamilyID=e6e1c3df-a74f-4207-8586-711ebe331cdc&displaylang=en> Even though it says it's "The Windows SDK for Windows Server® 2008" it is just the latest SDK and will have all the backwards compatible files you need. After you install it, depending on your compiler you'll probably have to point the include directory to it.
I can't build a library that needs WOW64 Api
[ "", "c++", "winapi", "wow64", "" ]
The project I'm currently working on generates 30+ warnings each time it gets build. They were ignored from the beginning of the projects. I guess due to the lack of policy about warnings. How do you usually handle this? Ignore them altogether? Try to fix them all at once (this requires some time)? Or just fix bit by bit along the way?
There are only 30 of them it's 2 hours work man just fix them. I completely disagree with anyone who says a deadline supercedes fixing these warnings. You will waste more time churning later on problems in the post code completion stages than if you fixed your problems now. Ignore your manager he probably is a moron who wants to look good to his boss. Initial quality and a correct design is more important than his arbitrary deadlines (within reason). The fact that you have warnings in the first place means that someone was sloppy with the code. Double check the areas where there are warnings exist for correctness. If you are using code analysis or are writing C/C++ then warnings are sometimes really not valid. In that case pragma them out (C/C++) or System.Diagnostics.CodeAnalysis.SuppressMessage. This can be done automatically from VS2008. I have not seen any .net warnings that were not valid outside of code analysis.
I highly recommend building with the setting to treat warnings as errors. This will cause the project to stop building, of course, but it's the only way to enforce a reasonable error policy. Once you've done that, you can examine the warnings you have and make some reasonable decisions. There are probably some warnings that are benign and which you don't care about, so add these to the list of warnings to ignore. Fix the rest of them. If you don't have time to fix them all now, add a #pragma (or the C# equiv) to ignore the specific warnings that occur in every file, and file a bug for each of these to make sure they are addressed later.
Best practices for handling warnings
[ "", "c#", "warnings", "" ]
I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?
You can't frequently run all your tests, because they're too slow. This is an inevitable consequence of your project getting bigger, and won't go away. Sure, you may be able to run the tests in parallel and get a nice speedup, but the problem will just come back later, and it'll never be as it was when your project was small. For productivity, you need to be able to code, and run relevant unit tests and get results within a few seconds. If you have a hierarchy of tests, you can do this effectively: run the tests for the module you're working on frequently, the tests for the component you're working on occasionally, and the project-wide tests infrequently (perhaps before you're thinking of checking it in). You may have integration tests, or full system tests which you may run overnight: this strategy is an extension of that idea. All you need to do to set this up is to organize your code and tests to support the hierarchy.
See py.test, which has the ability to pass unit tests off to a group of machines, or Nose, which (as of trunk, not the currently released version) supports running tests in parallel with the multiprocessing module.
distributed/faster python unit tests
[ "", "python", "unit-testing", "" ]
How can I call a specific event manually from my own code?
I think you want [wx.PostEvent](https://docs.wxpython.org/wx.functions.html#wx.PostEvent). There's also some info about posting events from other thread for [long running tasks on the wxPython wiki](http://wiki.wxpython.org/LongRunningTasks).
Old topic, but I think I've got this figured out after being confused about it for a long time, so if anyone else comes through here looking for the answer, this might help. To manually post an event, you can use ``` self.GetEventHandler().ProcessEvent(event) ``` (wxWidgets docs [here](http://docs.wxwidgets.org/stable/wx_wxevthandler.html#wxevthandlerprocessevent), wxPython docs [here](http://www.wxpython.org/docs/api/wx.EvtHandler-class.html)) or ``` wx.PostEvent(self.GetEventHandler(), event) ``` ([wxWidgets docs](http://docs.wxwidgets.org/stable/wx_miscellany.html#wxpostevent), [wxPython docs](http://www.wxpython.org/docs/api/wx-module.html#PostEvent)) where `event` is the event you want to post. Construct the event with e.g. ``` wx.PyCommandEvent(wx.EVT_BUTTON.typeId, self.GetId()) ``` if you want to post a EVT\_BUTTON event. Making it a [PyCommandEvent](http://www.wxpython.org/docs/api/wx.PyCommandEvent-class.html) means that it will propagate upwards; other event types don't propagate by default. You can also create custom events that can carry whatever data you want them to. Here's an example: ``` myEVT_CUSTOM = wx.NewEventType() EVT_CUSTOM = wx.PyEventBinder(myEVT_CUSTOM, 1) class MyEvent(wx.PyCommandEvent): def __init__(self, evtType, id): wx.PyCommandEvent.__init__(self, evtType, id) myVal = None def SetMyVal(self, val): self.myVal = val def GetMyVal(self): return self.myVal ``` (I think I found this code in a mailing list archive somewhere, but I can't seem to find it again. If this is your example, thanks! Please add a comment and take credit for it!) So now, to Post a custom event: ``` event = MyEvent(myEVT_CUSTOM, self.GetId()) event.SetMyVal('here is some custom data') self.GetEventHandler().ProcessEvent(event) ``` and you can bind it just like any other event ``` self.Bind(EVT_CUSTOM, self.on_event) ``` and get the custom data in the event handler ``` def on_event(self, e): data = e.GetMyVal() print 'custom data is: {0}'.format(data) ``` Or include the custom data in the event constructor and save a step: ``` class MyEvent(wx.PyCommandEvent): def __init__(self, evtType, id, val = None): wx.PyCommandEvent.__init__(self, evtType, id) self.myVal = val ``` etc. Hope this is helpful to someone.
wxPython: Calling an event manually
[ "", "python", "user-interface", "events", "wxpython", "" ]
I have been wondering about the reload() function in python, which seems like it can lead to problems if used without care. Why would you want to reload a module, rather than just stop/start python again? I imagine one application might be to test changes to a module interactively.
reload is useful for reloading code that may have changed in a Python module. Usually this means a plugin system. Take a look at this link: <http://www.codexon.com/posts/a-better-python-reload> It will tell you the shortcomings of reload and a possible fix.
> I imagine one application might be to test changes to a module interactively. That's really the only use for it. From the [Python documentation](http://docs.python.org/library/functions.html#reload): > This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
what are the applications of the python reload function?
[ "", "python", "" ]
For hobby purposes, I have a shared space on a hosting server that is providing, as many of them are, both PHP and Perl CGI. I have read on several places that CGI scripts are obsolete now, I think mainly for performance issues (like [Is PHP or vanilla Perl CGI faster?](https://stackoverflow.com/questions/313083/is-php-or-vanilla-perl-cgi-faster)). But since I just started studying Perl, I wouldn't want to waste time on implementing solutions in PHP that are way easier (or only possible) in Perl. Also there are the boilerplate issues, I'm aware of CPAN (that is the existence, not yet the content), but not familiar with PHP libraries (although I have no doubt they exist). I'm not prepared to write a login-procedure or basic user administration from scratch for the 10^10th time. I don't the luxury at this point to waste a lot of time in research for hobby projects either, so I thought, let's ask the experts for a headstart.
The "obsolete"-ness of CGI is really only a factor if you are doing big, complex sites with lots of page views. Many people push the idea that CGI is obsolete don't really understand what CGI is. There is a widespread misconception that CGI is an inherently Perl-based technology. Many people attack CGI as a way to pad out cultic attacks on Perl in support of whatever language they support. If you want to be a real technologist, you need to understand the fundamental issues and make a choice based on the facts of the situation. CGI is an interface with a webserver that allows you to write interactive pages in any language--[even befunge](http://quadium.net/funge/name.bf). When a server gets a request for a page controlled by a CGI script, the server runs the script and returns the results to the requester. If your programming language requires a VM, interpreter or compiler to load each time it executes, then this start-up time will be required each time your page is accessed. CGI accelerators like FastCGI, mod\_php, mod\_perl and so forth, keep an interpreter/VM in memory at all times, may keep libraries loaded, and even cache bytecode from scripts to reduce script start-up overhead. If you are making a simple, personal or hobby site, CGI will be fine. So will PHP. If your site should grow to need a faster technology, you can move to mod\_perl, FastCGI, or other CGI acceleration technologies. What language you use should be determined by the tools it provides and how they fit with your needs. 1. Make a list of the capabilities you need. 2. Make a list of deal breakers. 3. Now check each of your possible toolsets against these two lists. 4. Which one comes out the best? Test it. 5. Does it suck? Cross it off your list, and go back to step 4. Also, I recommend against using [befunge](http://en.wikipedia.org/wiki/Befunge). Just because it is possible, it doesn't mean you should use it. --- **Update:** As mpeters points out, mod\_perl, mod\_php, mod\_ruby, et alia are much more than mere CGI accelerators; they provide access to the Apache API. They act as CGI accelerators, but can do much, much, more. FastCGI is a pure CGI accelerator. **Update 2:** PHP and CGI are not mutually exclusive. [PHP can be installed as a CGI](https://www.php.net/security.cgi-bin). PHP is often used with FastCGI.
This is a fairly subjective issue for deciding what to use for a hobby. I decided to learn Perl as a hobby after looking into PHP and not liking the fact that I could not read most of the PHP out there and being daunted by the list of builtin functions. The first few things I did were CGI scripts for contact forms and a photo album generator. I was on a cheapo shared hosting plan and I was not getting any performance problems so the performance issue never came into play. Instead, the existence of comp.lang.perl.misc and CPAN ensured that I never reconsidered my decision not to delve into PHP. In the mean time, I realized most of the content on my web sites is static once generated, so now I write Perl scripts to generate the content offline. So, my answer is, pick a small project, anything will do, and implement it using Perl and appropriate CPAN modules and see if you like it.
When should I use Perl CGI instead of PHP (or vice versa)?
[ "", "php", "perl", "cgi", "cpan", "" ]
I have a JFrame and I open a JDialog from it and another JDialog from that dialog - which menas i have 3 windows visible (JFrame, JDialog1, Jdialog2). When I close both dialogs and run a garbage collectior few times (from netbeans profiler) I can see that JDialog2 (the one opened from JDialog1) is garbage collected but JDialog1 (opened from JFrame) is still hanging in live objects pool. I create new objects every time - so after some time I have an OutOfMemoryError doue to memory leak. Do I have to treat JDialogs in som special way so they don't leak ? by the way i do `setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE)` on both dialogs,
In order to release allocated resources you have to call the dispose method. Simply hiding the dialog is not enough.
Have you unregistered all of your listeners on the dialog (including any of it's components)? Leaving listeners registered can be a major source of memory leaks.
Why do my JDialogs leak?
[ "", "java", "swing", "" ]
I'm creating a C api that hides some functionality in a DLL file. Since everything is C++ on the inside most of the functions works against handles which maps directly to this pointers on the inside of the API. To get a some degree of type safety for those handles I define them like this: ``` typedef struct MyType1* MyType1Handle; typedef struct MyType2* MyType2Handle; ``` I don't actually define MyType1 or MyType2 at any place since I only use them as pointers and do a type cast on the inside of the api to the actual pointer type. My problem is that when using my library in a clr project in visual studio I get this `warning: unresolved typeref token (token) for 'type'; image may not run.` <http://msdn.microsoft.com/en-us/library/h8027ys9(VS.80).aspx> It's no big deal since it works, but it looks unprofessional. I don't like using void\*: ``` typedef void* MyType1Handle; typedef void* MyType2Handle; ``` This makes it possible to call a function wanting a MyType1Handle with a MyType2Handle since they are actually the same type. Another approach I don't want to use is something like this ``` typedef int MyType1Handle; typedef int MyType2Handle; ``` This would work fine as long as int's and pointers have the same size, but that's not always the case and it seems like there is no foolproof way of getting a platform specific pointer sized integer. It has the same type safety problems as the void\* as well. Another approach I tried was to do it like this: ``` struct MyType1{}; typedef struct MyType1* MyType1Handle; ``` This didn't work in C since empty structs is invalid C code. I could of course extend my struct with a dummy member, but it seems like there should be a better way of doing this. So my question boils down to: How do you generally specify this kind of types in the most compatible way?
If you look at how Microsoft defines it's winapi handles (winnt.h) it actually looks like this: ``` struct HWND__ { int unused; }; typedef struct HWND__ *HWND ``` in fact they have a macro for this: ``` #define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name ``` so.. this seems to be a common practice to do so. Unfortunately I can't make another suggestion except this one, which you already mentioned, but I hope it helps you anyway.
Use an opaque struct. This is a good idea in many cases when defining the interface to a library in C: it improves modularity, hides unnecessary detail As JamieH said, you get an opaque struct by declaring - but not defining - a struct. It's perfectly valid to have, and pass, pointers to the opaque struct into the libraries functions as arguments and return them as values. Users of library however cannot create or modify objects of the opaque struct since it's size and content is unknown. The C standard library, and many others, already use this approach so it should be familiar. The cannonical example is the use of `FILE *`: `fopen()` creates and initialises the struct and returns a pointer to it, `fclose()` cleans up and releases it and all other i/o functions get their context from the passed in `FILE *`.
The right type for handles in C interfaces
[ "", "c++", "c", "api", "" ]
I have a database that I have created using SQL Server Developer 2008. I want to script it to a file so that it can be recreated by anyone at any time. Any Ideas?
To recreate the structure, right-click on the database and use Tasks --> Generate Scripts. Walk your way through the wizard, selecting those objects that you want to have created by your script. This TechNet [article](http://technet.microsoft.com/en-us/library/ms178078.aspx) will serve as a good starting point for exploring how to do this if the process isn't obvious. If you need both structure and data, you might want to consider using the [Red Gate SQL Packager](http://www.red-gate.com/products/SQL_Packager/index.htm) to script the data.
You can follow the steps at Pinal's site. Be careful to select all the options you want: <http://blog.sqlauthority.com/2007/08/21/sql-server-2005-create-script-to-copy-database-schema-and-all-the-objects-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/>
How Do I Script a Database To a Text File So That It Can Be Created Again By Anyone?
[ "", "sql", "sql-server", "database", "" ]
Does anyone know or care to speculate why implicit typing is limited to local variables? ``` var thingy = new Foo(); ``` But why not... ``` var getFoo() { return new Foo(); } ```
Eric Lippert did an entire blog post on the subject. * <https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-no-var-on-fields> In summary, the main problem is that it would have required a major re-architecture of the C# compiler to do so. Declarations are currently processed in a single pass manner. This would require multiple passes because of the ability to form cycles between inferred variables. VB.NET has roughly the same problem.
Jared has a fantastic link in his answer, to a fantastic topic. I think it does not answer the question explicitly. **Why not?** ``` var getFoo() { return new Foo(); } ``` The reason for this is: **What if?** ``` class Foo {} var GetFoo() { return GetBar(); } var GetBar() { return GetBaz(); } var GetBaz() { return new Foo(); } ``` You could deduce that `GetFoo` is going to return `Foo`, but you will have to trace through **all** the calls that method makes and its **children** makes just to infer the type. As it stands the C# compiler is not designed to work in this way. It needs method and field types early in the process before the code that infers types can run. On a purely aesthetic level I find the var definitions on methods confuse things. Its one place where I think being explicit **always** helps, it protects you from shooting your self in the foot by accidentally returning a type that causes your signature and a ton of other dependent method signatures to change. Worst still, you could potentially change all you signatures of a method chain without even knowing you did so if you return the value of a method that returns object and happened to be lucky. I think var methods are best left for dynamic languages like Ruby
Implicit typing; why just local variables?
[ "", "c#", ".net", "variables", "implicit-typing", "" ]
I am trying to join two tables; the purpose being able to search and display event information for an artist that is entered by the user. The tables are as follows: artist table: [id],[name] events table: [id],[artist\_id],[venue\_name],[city],[state],[date],[time] I created a search engine, but what I want to do is when an artist name is entered into the text box, the code will go out to my database and will look through the artist table to see what name was entered and then grab the id that matches the entered name and then go to the events table to find that distinct artist\_id and display all of the event information for the certain artist that was entered. I would really like help with how to do this and I'm not the greatest at this, but I am trying! Thanks:)
``` SELECT * FROM artist LEFT JOIN events ON artist.id = events.artist_id WHERE artist.name = 'your search text' ```
``` select e.venue_name, e.city, e.state, e.date, e.time from artist_table a join events_table e on a.id = e.artist_id where a.name = @userInput ``` or something like that... Or am I missing something? Is this a homework question?
Question about joining two mysql tables
[ "", "php", "mysql", "database", "join", "search-engine", "" ]
I'm using XSLT and having great success, just got a couple of problems. **Warning: DOMDocument::loadXML() [domdocument.loadxml]: Entity 'Aring' not defined in Entity** Basically for some non-standard characters I am getting the above type of error. I really want to fix this once and for all. I know about character mapping but I cannot possibly write down every possible combination of special characters.
Include a DTD that defines the entities, like [this one](http://www.utoronto.ca/webdocs/HTMLdocs/HTML_Spec/html4.01/HTMLlat1.ent) Here's a [post at PHP.net](http://www.php.net/manual/en/book.xsl.php#49694) that hints at how to succesfully include it. The DTD above should probably cover you; &Aring; is an HTML entity, and the DTD above covers all HTML 4.01 entities.
When used without a DTD, XML only supports a very limited number of named entities. (`&lt;`, `&gt;`, `&amp;`, and `&quot;`, as I recall.) To include other out-of-charset characters without using a DTD, simply refer to them with a numeric entity instead. For example, `&Aring;` corresponds to Unicode character U+00C5, "Latin Capital Letter A With Ring Above". You can therefore use `&#xC5;` (leading zeroes can be omitted) to include it in your document. If you're on Windows, the Character Map tool (on XP: Start > Programs > Accessories > System Tools) is a big help.
XSLT character encoding - entity not defined
[ "", "php", "xml", "xslt", "" ]
I'm trying to launch a website url in a new tab using python in that way, but it didn't worked in these both ways: Method 1: ``` os.system('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http://www.google.com/'); ``` and Method 2: ``` os.startfile('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http://www.google.com/'); ``` If I don't add the parameters (-new-tab <http://www.google.com/>) it works, opening the default page.
You need to use the [`webbrowser`](http://docs.python.org/library/webbrowser.html) module ``` import webbrowser webbrowser.open('http://www.google.com') ``` [**edit**] If you want to open a url in a non-default browser try: ``` webbrowser.get('firefox').open_new_tab('http://www.google.com') ```
If you want to start a program with parameters the [subprocess](http://docs.python.org/library/subprocess.html) module is a better fit: ``` import subprocess subprocess.call([r'C:\Program Files\Mozilla Firefox\Firefox.exe', '-new-tab', 'http://www.google.com/']) ```
Launch a webpage on a Firefox (win) tab using Python
[ "", "python", "windows", "command-line", "" ]
My script is acting strange. After a foreach loop, the script stops. I don't have any error, any warning or notice from Apache. This is the code: ``` foreach($clientFact as $line) { $cliTemp1[] = $line["idcliente"]; echo "qwerty"; } echo "123"; ``` If I add an "echo(qwerty")" inside the loop, it will show the "qwerty" but, right after the end of the loop it will not do anything. Am I missing something?! Thanks
Apache wouldnt return an error as its a PHP error. Adding ``` error_reporting(E_ALL | E_STRICT); ``` on the top of your page is a very good idea so you can see every error that happens. It could also be your error handler that is not displaying the error and just ending the script. If it is a problem with your error handler, add ``` restore_error_handler(); ``` before the error\_reporting function Edit: read your comment about the array index. It definately sounds like a memory limit being reached in PHP if it stops at a specific index every time. You could use: ``` ini_set('memory_limit', '100M'); ``` to change your memory limit to 100megs. Not recommended but if it works, its a problem with not enough memory. Try to refactor your program so it uses less memory
The syntax above looks fine, so as a complete shot in the dark here - how big is the `$clientFact` array? Is it possible that the `$cliTemp1` array is getting so large it's tripping a memory limit? Maybe rather than echoing "qwerty", echo out the contents of `$line["idcliente"]` on each iteration to be sure you're successfully getting through all elements in `$clientFact`.
My script stops after a foreach loop
[ "", "php", "foreach", "" ]
I'm looking for a way to allow a property in a C# object to be set once only. It's easy to write the code to do this, but I would rather use a standard mechanism if one exists. ``` public OneShot<int> SetOnceProperty { get; set; } ``` What I want to happen is that the property can be set if it is not already set, but throw an exception if it has been set before. It should function like a Nullable value where I can check to see if it has been set or not.
There is direct support for this in the TPL in .NET 4.0; (edit: the above sentence was written in anticipation of `System.Threading.WriteOnce<T>` which existed in the "preview" bits available at the time, but this seems to have evaporated before the TPL hit RTM/GA) until then just do the check yourself... it isn't many lines, from what I recall... something like: ``` public sealed class WriteOnce<T> { private T value; private bool hasValue; public override string ToString() { return hasValue ? Convert.ToString(value) : ""; } public T Value { get { if (!hasValue) throw new InvalidOperationException("Value not set"); return value; } set { if (hasValue) throw new InvalidOperationException("Value already set"); this.value = value; this.hasValue = true; } } public T ValueOrDefault { get { return value; } } public static implicit operator T(WriteOnce<T> value) { return value.Value; } } ``` Then use, for example: ``` readonly WriteOnce<string> name = new WriteOnce<string>(); public WriteOnce<string> Name { get { return name; } } ```
You can roll your own (see the end of the answer for a more robust implementation that is thread safe and supports default values). ``` public class SetOnce<T> { private bool set; private T value; public T Value { get { return value; } set { if (set) throw new AlreadySetException(value); set = true; this.value = value; } } public static implicit operator T(SetOnce<T> toConvert) { return toConvert.value; } } ``` You can use it like so: ``` public class Foo { private readonly SetOnce<int> toBeSetOnce = new SetOnce<int>(); public int ToBeSetOnce { get { return toBeSetOnce; } set { toBeSetOnce.Value = value; } } } ``` **More robust implementation below** ``` public class SetOnce<T> { private readonly object syncLock = new object(); private readonly bool throwIfNotSet; private readonly string valueName; private bool set; private T value; public SetOnce(string valueName) { this.valueName = valueName; throwIfGet = true; } public SetOnce(string valueName, T defaultValue) { this.valueName = valueName; value = defaultValue; } public T Value { get { lock (syncLock) { if (!set && throwIfNotSet) throw new ValueNotSetException(valueName); return value; } } set { lock (syncLock) { if (set) throw new AlreadySetException(valueName, value); set = true; this.value = value; } } } public static implicit operator T(SetOnce<T> toConvert) { return toConvert.value; } } public class NamedValueException : InvalidOperationException { private readonly string valueName; public NamedValueException(string valueName, string messageFormat) : base(string.Format(messageFormat, valueName)) { this.valueName = valueName; } public string ValueName { get { return valueName; } } } public class AlreadySetException : NamedValueException { private const string MESSAGE = "The value \"{0}\" has already been set."; public AlreadySetException(string valueName) : base(valueName, MESSAGE) { } } public class ValueNotSetException : NamedValueException { private const string MESSAGE = "The value \"{0}\" has not yet been set."; public ValueNotSetException(string valueName) : base(valueName, MESSAGE) { } } ```
Is there a way of setting a property once only in C#
[ "", "c#", ".net", "" ]
is there any javascript library that provides me with a custom event as soon as a certain element becomes visible in the browser canvas? the basic idea is, as soon as the last element in a list becomes visible on the screen, i want to load the next 10 elements so that the user does not need to click on the "next page" button. to achieve this, a onBecomesVisible event that fires as soon as the last element is shown would be handy. is there something like this? [Slashdot](http://slashdot.org) does its front-page loading this way.
You could write your own simple plugin using jQuery. ``` $.belowViewport = function(elem){ var port = $(window).scrollTop() + $(window).height(); return port <= $(elem).offset().top; } $.fn.onBecomeVisible = function( fn ){ var obj = this; $(window).scroll( function() { obj.each( function() { if(!$.belowViewport(this) && !$(this).data('scrollEventFired')){ $(this).data('scrollEventFired', true); fn(this); } }); }); return this; } ``` And then use it like this ``` $('.elements:last').onBecomeVisible( function(elem){ loadNewElems(); } ); ``` The script will bind fn to each of the matched ellements. The function will be fired when any of the matched elements scrolls into view. The function will also be passed which element has fired the event. Note that you can not bind this event using live so you will have to rebind it after adding new elements (presuming you want the event on the last one of those too.). **EDIT** I was wrong here, :visible does not return wether or not an element is in the viewport. However I have edited the source so it now does check if an element is in the viewport. The function checks if the element is below the viewport, we assume that if it isn't below the viewport it has been scrolled into view and that we should execute the function. **EDIT2** Tested this in google chrome 1.0, firefox 3.0.10 and IE7
You may want to look at endless scrolling: <http://plugins.jquery.com/project/endless-scroll>
onBecomesVisible in Javascript for clickless pagination?
[ "", "javascript", "ajax", "pagination", "" ]
The following class serve as generic tester for equals/hashCode contract. It is a part of a home grown testing framework. * What do you think about? * How can I (strong) test this class? * It is a good use of Junit theories? The class: ``` @Ignore @RunWith(Theories.class) public abstract class ObjectTest { // For any non-null reference value x, x.equals(x) should return true @Theory public void equalsIsReflexive(Object x) { assumeThat(x, is(not(equalTo(null)))); assertThat(x.equals(x), is(true)); } // For any non-null reference values x and y, x.equals(y) // should return true if and only if y.equals(x) returns true. @Theory public void equalsIsSymmetric(Object x, Object y) { assumeThat(x, is(not(equalTo(null)))); assumeThat(y, is(not(equalTo(null)))); assumeThat(y.equals(x), is(true)); assertThat(x.equals(y), is(true)); } // For any non-null reference values x, y, and z, if x.equals(y) // returns true and y.equals(z) returns true, then x.equals(z) // should return true. @Theory public void equalsIsTransitive(Object x, Object y, Object z) { assumeThat(x, is(not(equalTo(null)))); assumeThat(y, is(not(equalTo(null)))); assumeThat(z, is(not(equalTo(null)))); assumeThat(x.equals(y) && y.equals(z), is(true)); assertThat(z.equals(x), is(true)); } // For any non-null reference values x and y, multiple invocations // of x.equals(y) consistently return true or consistently return // false, provided no information used in equals comparisons on // the objects is modified. @Theory public void equalsIsConsistent(Object x, Object y) { assumeThat(x, is(not(equalTo(null)))); boolean alwaysTheSame = x.equals(y); for (int i = 0; i < 30; i++) { assertThat(x.equals(y), is(alwaysTheSame)); } } // For any non-null reference value x, x.equals(null) should // return false. @Theory public void equalsReturnFalseOnNull(Object x) { assumeThat(x, is(not(equalTo(null)))); assertThat(x.equals(null), is(false)); } // Whenever it is invoked on the same object more than once // the hashCode() method must consistently return the same // integer. @Theory public void hashCodeIsSelfConsistent(Object x) { assumeThat(x, is(not(equalTo(null)))); int alwaysTheSame = x.hashCode(); for (int i = 0; i < 30; i++) { assertThat(x.hashCode(), is(alwaysTheSame)); } } // If two objects are equal according to the equals(Object) method, // then calling the hashCode method on each of the two objects // must produce the same integer result. @Theory public void hashCodeIsConsistentWithEquals(Object x, Object y) { assumeThat(x, is(not(equalTo(null)))); assumeThat(x.equals(y), is(true)); assertThat(x.hashCode(), is(equalTo(y.hashCode()))); } // Test that x.equals(y) where x and y are the same datapoint // instance works. User must provide datapoints that are not equal. @Theory public void equalsWorks(Object x, Object y) { assumeThat(x, is(not(equalTo(null)))); assumeThat(x == y, is(true)); assertThat(x.equals(y), is(true)); } // Test that x.equals(y) where x and y are the same datapoint instance // works. User must provide datapoints that are not equal. @Theory public void notEqualsWorks(Object x, Object y) { assumeThat(x, is(not(equalTo(null)))); assumeThat(x != y, is(true)); assertThat(x.equals(y), is(false)); } } ``` usage: ``` import org.junit.experimental.theories.DataPoint; public class ObjectTestTest extends ObjectTest { @DataPoint public static String a = "a"; @DataPoint public static String b = "b"; @DataPoint public static String nullString = null; @DataPoint public static String emptyString = ""; } ```
One thing to consider: testing an object's conformance to the equals contract should involve instances of other types. In particular, problems are likely to appear with instances of a subclass or superclass. Joshua Bloch gives an excellent explanation of the related pitfalls in [Effective Java](http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf) (I'm reusing duffymo's link, so he should get credit for it) -- see the section under Transitivity involving the Point and ColorPoint classes. True, your implementation doesn't prevent someone from writing a test that involves instances of a subclass, but because `ObjectTest` is a generic class it gives the impression that all data points should come from a single class (the class being tested). It might be better to remove the type parameter altogether. Just food for thought.
Joshua Bloch lays out the contract for hash code and equals in [chapter 3 of "Effective Java"](http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf). Looks like you covered a great deal of it. Check the document to see if I missed anything.
JUnit theory for hashCode/equals contract
[ "", "java", "unit-testing", "junit", "" ]