Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
On our web application, the search results are displayed in sortable tables. The user can click on any column and sort the result. The problem is some times, the user does a broad search and gets a lot of data returned. To make the sortable part work, you probably need all the results, which takes a long time. Or I can retrieve few results at a time, but then sorting won't really work well. What's the best practice to display sortable tables that might contain lots of data? --- Thanks for all the advises. I will certainly going over these. We are using an existing Javascript framework that has the sortable table; "lots" of results means hundreds. The problem is that our users are at some remote site and a lot of delay is the network time to send/receive data from the data center. Sorting the data at the database side and only send one page worth of results at a time is nice; but when the user clicks some column header, another round trip is done, which always add 3-4 seconds. Well, I guess that might be the network team's problem :)
Using sorting paging at the database level is the correct answer. If your query returns 1000 rows, but you're only going to show the user 10 of them, there is no need for the other 990 to be sent across the network. Here is a mysql example. Say you need 10 rows, 21-30, from the 'people' table: ``` SELECT * FROM people LIMIT 21, 10 ```
You should be doing paging back on the database server. E.g. on SQL 2005 and SQL 2008 there are paging techniques. I'd suggest looking at paging options for whatever system you're looking at.
Best approach for sortable table with a lot of data
[ "", "javascript", "database", "jquery-ui-sortable", "" ]
In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?
In SQL 2005, You can use the following: ``` select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108) ``` Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part. If the column is more than 24 hours, this will roll over, if you want days and then hours in that case just do something like: ``` case when SecondsColumn> (24*60*60) then cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4)) + 'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108) else convert(varchar(8), dateadd(second, SecondsColumn, 0), 108) end ```
Every database does it differently. I use PostgreSQL and it does it like so: ``` select to_char(my_date - my_other_date, 'HH:MM:SS'); ``` You'll have to consult the manual for the database you are using.
How to convert in SQL the number of seconds into a human-readable duration?
[ "", "sql", "int", "duration", "" ]
Is there a good method for writing C / C++ function headers with default parameters that are function calls? I have some header with the function: ``` int foo(int x, int y = 0); ``` I am working in a large code base where many functions call this function and depend on this default value. This default value now needs to change to something dynamic and I am looking for a way to do: ``` int foo(int x, int y = bar()); ``` Where bar() is some function that generates the default value based on some system parameters. Alternatively this function prototype would look like: ``` int foo(int x, int y = baz.bar()); ``` Where baz is a function belonging to an object that has not been instantiated within the header file.
Go figure! It does work. [Default arguments in C++ functions](http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr237.htm)
I would use two overloaded functions: `int foo(int x, int y);` `int foo(int x){return foo(x,bar);}` If you allow the forwarding function to be inlined, then the performance penalty is likely to small to zero. If you keep the body of it out of line in a non-header file there may be a performance cost (likely to be small), but much more flexibility in implementation and reduced coupling.
Can the result of a function call be used as a default parameter value?
[ "", "c++", "parameters", "default-value", "" ]
How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table? For example: ``` nr 1 2 3 4 5 ``` I would like to use only MySQL for this (not PHP or other languages).
If you need the records in a table and you want to avoid concurrency issues, here's how to do it. First you create a table in which to store your records ``` CREATE TABLE `incr` ( `Id` int(11) NOT NULL auto_increment, PRIMARY KEY (`Id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ``` Secondly create a stored procedure like this: ``` DELIMITER ;; CREATE PROCEDURE dowhile() BEGIN DECLARE v1 INT DEFAULT 5; WHILE v1 > 0 DO INSERT incr VALUES (NULL); SET v1 = v1 - 1; END WHILE; END;; DELIMITER ; ``` Lastly call the SP: ``` CALL dowhile(); SELECT * FROM incr; ``` Result ``` Id 1 2 3 4 5 ```
Here is one way to do it set-based without loops. This can also be made into a view for re-use. The example shows the generation of a sequence from 0 through 999, but of course, it may be modified to suit. ``` INSERT INTO myTable ( nr ) SELECT SEQ.SeqValue FROM ( SELECT (HUNDREDS.SeqValue + TENS.SeqValue + ONES.SeqValue) SeqValue FROM ( SELECT 0 SeqValue UNION ALL SELECT 1 SeqValue UNION ALL SELECT 2 SeqValue UNION ALL SELECT 3 SeqValue UNION ALL SELECT 4 SeqValue UNION ALL SELECT 5 SeqValue UNION ALL SELECT 6 SeqValue UNION ALL SELECT 7 SeqValue UNION ALL SELECT 8 SeqValue UNION ALL SELECT 9 SeqValue ) ONES CROSS JOIN ( SELECT 0 SeqValue UNION ALL SELECT 10 SeqValue UNION ALL SELECT 20 SeqValue UNION ALL SELECT 30 SeqValue UNION ALL SELECT 40 SeqValue UNION ALL SELECT 50 SeqValue UNION ALL SELECT 60 SeqValue UNION ALL SELECT 70 SeqValue UNION ALL SELECT 80 SeqValue UNION ALL SELECT 90 SeqValue ) TENS CROSS JOIN ( SELECT 0 SeqValue UNION ALL SELECT 100 SeqValue UNION ALL SELECT 200 SeqValue UNION ALL SELECT 300 SeqValue UNION ALL SELECT 400 SeqValue UNION ALL SELECT 500 SeqValue UNION ALL SELECT 600 SeqValue UNION ALL SELECT 700 SeqValue UNION ALL SELECT 800 SeqValue UNION ALL SELECT 900 SeqValue ) HUNDREDS ) SEQ ```
Generating a range of numbers in MySQL
[ "", "sql", "mysql", "" ]
Is SQL case sensitive? I've used [MySQL](https://en.wikipedia.org/wiki/MySQL) and [SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) which both seem to be case insensitive. Is this always the case? Does the standard define case-sensitivity?
The SQL keywords are case insensitive (`SELECT`, `FROM`, `WHERE`, etc), but they are often written in all caps. However, in some setups, table and column names are case sensitive. MySQL has a configuration option to enable/disable it. Usually case sensitive table and column names are the default on Linux [MySQL](https://en.wikipedia.org/wiki/MySQL) and case insensitive used to be the default on Windows, but now the installer asked about this during setup. For [SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) it is a function of the database's collation setting. Here is the [MySQL page about name case-sensitivity](http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html) Here is the [article in MSDN about collations for SQL Server](http://msdn.microsoft.com/en-us/library/ms143503(SQL.90).aspx)
This isn't strictly SQL language, but in SQL Server if your database collation is case-sensitive, then all table names are case-sensitive.
Is SQL syntax case sensitive?
[ "", "sql", "case-sensitive", "" ]
What would you consider best practice for organizing JUnit tests in a project, and why? For example, do you keep your tests next to the classes they test? Do you put them in a separate but parallel package structure? Do you use a different organization strategy entirely?
I use a separate but parallel package structure for several reasons. 1. It keeps tests organized the same way as the application code.- I can easily build just the application files for distribution.- Test code still has access to my application code.- It's not as cluttered as having test code mixed with application code.
I put my tests in a seperate but similar/parallel package structure. This is how Maven likes things and it works well with IDEs too. I like it this way because I don't have my test code mixed up with my application code, yet I can still access package-private things for the purpose of mocking and state-verification.
Organization of JUnit tests in projects
[ "", "java", "junit", "" ]
Why do I get compiler errors with this Java code? ``` 1 public List<? extends Foo> getFoos() 2 { 3 List<? extends Foo> foos = new ArrayList<? extends Foo>(); 4 foos.add(new SubFoo()); 5 return foos; 6 } ``` Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface. Errors I get with this code: * On Line 3: "Cannot instantiate ArrayList<? extends Foo>" * On Line 4: "The method add(capture#1-of ? extends Foo) in the type List<capture#1-of ? extends Foo> is not applicable for the arguments (SubFoo)" **Update:** Thanks to Jeff C, I can change Line 3 to say "new ArrayList<Foo>();". But I'm still having the issue with Line 4.
Use this instead: ``` 1 public List<? extends Foo> getFoos() 2 { 3 List<Foo> foos = new ArrayList<Foo>(); /* Or List<SubFoo> */ 4 foos.add(new SubFoo()); 5 return foos; 6 } ``` Once you declare foos as `List<? extends Foo>`, the compiler doesn't know that it's safe to add a SubFoo. What if an `ArrayList<AltFoo>` had been assigned to `foos`? That would be a valid assignment, but adding a SubFoo would pollute the collection.
Just thought I'd add to this old thread, by summarising the properties of List parameters instantiated with types or wildcards.... When a method has a parameter/result which is a List, the use of type instantiation or wildcards determines 1. Types of List which can be passed to the method as an argument 2. Types of List which can be populated from the method result 3. Types of elements which can be written to list within the method 4. Types which can be populated when reading elements from list within the method ## Param/Return type: `List< Foo>` 1. Types of List which can be passed to the method as an argument: * `List< Foo>` 2. Types of List which can be populated from the method result: * `List< Foo>` * `List< ? super Foo>` * `List< ? super SubFoo>` * `List< ? extends Foo>` * `List< ? extends SuperFoo>` 3. Types of elements which can be written to list within the method: * `Foo` & subtypes 4. Types which can be populated when reading elements from list within the method: * `Foo` & supertypes (up to `Object`) ## Param/Return type: `List< ? extends Foo>` 1. Types of List which can be passed to the method as an argument: * `List< Foo>` * `List< Subfoo>` * `List< SubSubFoo>` * `List< ? extends Foo>` * `List< ? extends SubFoo>` * `List< ? extends SubSubFoo>` 2. Types of List which can be populated from the method result: * `List< ? extends Foo>` * `List< ? extends SuperFoo>` * `List< ? extends SuperSuperFoo>` 3. Types of elements which can be written to list within the method: * None! Not possible to add. 4. Types which can be populated when reading elements from list within the method: * `Foo` & supertypes (up to `Object`) ## Param/Return type: `List<? super Foo>` 1. Types of List which can be passed to the method as an argument: * `List< Foo>` * `List< Superfoo>` * `List< SuperSuperFoo>` * `List< ? super Foo>` * `List< ? super SuperFoo>` * `List< ? super SuperSuperFoo>` 2. Types of List which can be populated from the method result: * `List< ? super Foo>` * `List< ? super SubFoo>` * `List< ? super SubSubFoo>` 3. Types of elements which can be written to list within the method: * `Foo` & supertypes 4. Types which can be populated when reading elements from list within the method: * `Foo` & supertypes (up to `Object`) ## Interpretation/Comment * needs of external callers drive the design of the method declaration i.e. the public API (normally the primary consideration) * needs of internal method logic drive any additional decisions re actual data types declared and constructed internally (normally the secondary consideration) * use `List<Foo>` if caller code is always focused on manipulating the Foo class, as it maximises flexibility for both read and write * use `List<? extends UpperMostFoo>` if there could be many different types of caller, focused on manipulating a different class (not always Foo) and there is a single uppermost class in the Foo type hierarchy, and if the method is to internally write to the list and caller list manipulation is reading. Here the method may internally use `List< UpperMostFoo>` and add elements to it, before returning `List< ? extends UpperMostFoo>` * if there could be many different types of caller, focused on manipulating a different class (not always Foo) and if reading and writing to list is required and there is a single lowest class in the Foo type hierarchy, then it makes sense to use `List< ? super LowerMostFoo>`
How can elements be added to a wildcard generic collection?
[ "", "java", "generics", "" ]
I've got a relatively large .Net system that consists of a number of different applications. Rather than having lots of different app.config files, I would like to share a single configuration file between all the apps. I would also like to have one version when developing on my machine, one version for someone else developing on their machine, one version for a test system and one version for a live system. Is there an easy way of doing this?
For large amounts of configuration which is needed by multiple applications, I would put this configuration into a central repository, e.g. a database, file in a common location. To use different versions of a configuration file for different environments, create a build configuration for each of the different environments and a config file named after the environment, e.g: production production.app.config test test.app.config You can then use a pre build event to copy the correct config over the default app.config in your project. This will then get copied to your output directory as normal. The pre build event would look similar to the above, just use $(Configuration) to get the appropriate file for the environment you want. You could combine this with the above to copy the overall build specific config files into each project.
You could use a Post-build event (Properties -> Build Events) on your "child" projects to copy a config file from a master project to others, like this: ``` copy /Y c:\path\to\master\project\app.config $(TargetPath).config exit 0 ``` (The "exit 0" as the last line prevents a build error). To have separate config files for different build targets ("RELEASE", "DEBUG", etc), you can edit the .csproj file (or .vbproj) in NOTEPAD.EXE to add an AppConfig tag for each of the target groups, like this: ``` <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>.\bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <AppConfig>debug.app.config</AppConfig> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>.\bin\Devel\</OutputPath> <DefineConstants>TRACE</DefineConstants> <AppConfig>release.app.config</AppConfig> </PropertyGroup> ``` Notice the new **<AppConfig>** tags present in each group.
How can I share application configuration in a .net application?
[ "", "c#", ".net", "app-config", "" ]
I'm building a form with php/mysql. I've got a table with a list of locations and sublocations. Each sublocation has a parent location. A column "parentid" references another locationid in the same table. I now want to load these values into a dropdown in the following manner: ``` --Location 1 ----Sublocation 1 ----Sublocation 2 ----Sublocation 3 --Location 2 ----Sublocation 4 ----Sublocation 5 ``` etc. etc. Did anyone get an elegant solution for doing this?
NOTE: This is only psuedo-code.. I didn't try running it, though you should be able to adjust the concepts to what you need. ``` $parentsql = "SELECT parentid, parentname FROM table"; $result = mysql_query($parentsql); print "<select>"; while($row = mysql_fetch_assoc($result)){ $childsql = "SELECT childID, childName from table where parentid=".$row["parentID"]; $result2 = mysql_query($childsql); print "<optgroup label=\".$row["parentname"]."\">"; while($row2 = mysql_fetch_assoc($result)){ print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n"; } print "</optgroup>"; } print "</select>"; ``` With BaileyP's valid criticism in mind, here's how to do it WITHOUT the overhead of calling multiple queries in every loop: ``` $sql = "SELECT childId, childName, parentId, parentName FROM child LEFT JOIN parent ON child.parentId = parent.parentId ORDER BY parentID, childName"; $result = mysql_query($sql); $currentParent = ""; print "<select>"; while($row = mysql_fetch_assoc($result)){ if($currentParent != $row["parentID"]){ if($currentParent != ""){ print "</optgroup>"; } print "<optgroup label=\".$row["parentName"]."\">"; $currentParent = $row["parentName"]; } print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n"; } print "</optgroup>" print "</select>"; ```
Are you looking for something like the [OPTGROUP](http://www.w3schools.com/TAGS/tag_optgroup.asp) tag?
Nested dropdown
[ "", "php", "mysql", "html", "forms", "" ]
Java has some very good open source static analysis tools such as [FindBugs](http://findbugs.sf.net/), [Checkstyle](http://checkstyle.sf.net/) and [PMD](http://pmd.sf.net/). Those tools are easy to use, very helpful, runs on multiple operating systems and *free*. Commercial C++ static analysis products are available. Although having such products are great, the cost is just way too much for students and it is usually rather hard to get trial version. The alternative is to find open source C++ static analysis tools that will run on multiple platforms (Windows and Unix). By using an open source tool, it could be modified to fit certain needs. Finding the tools has not been easy task. Below is a short list of C++ static analysis tools that were found or suggested by others. * C++ Check <http://sf.net/projects/cppcheck/> * Oink <http://danielwilkerson.com/oink/index.html> * C and C++ Code Counter <http://sourceforge.net/projects/cccc/> * [Splint](https://splint.org/) (from answers) * Mozilla's Pork (from answers) (This is now part of Oink) * Mozilla's Dehydra (from answers) * Use option `-Weffc++` for GNU g++ (from answers) What are some **other** portable open source C++ static analysis tools that anyone knows of and can be recommended? Some related links. * <http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis> * <http://www.chris-lott.org/resources/cmetrics/> * [A free tool to check C/C++ source code against a set of coding standards?](https://stackoverflow.com/questions/93260/a-free-tool-to-check-cc-source-code-against-a-set-of-coding-standards) * <http://spinroot.com/static/> * [Choosing a static code analysis tool](https://stackoverflow.com/questions/2873/choosing-a-static-code-analysis-tool)
Oink is a tool built on top of the Elsa C++ front-end. Mozilla's Pork is a fork of Elsa/Oink. See: <http://danielwilkerson.com/oink/index.html>
[CppCheck](http://sourceforge.net/p/cppcheck/wiki/Home/) is open source and cross-platform. Mac OSX: ``` brew install cppcheck ```
What open source C++ static analysis tools are available?
[ "", "c++", "static-analysis", "" ]
From the MSDN article on STAThread: > Indicates that the COM threading model for an application is single-threaded apartment (STA). (For reference, that's [the entire article](http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx).) Single-threaded apartment... OK, that went over my head. Also, I read somewhere that unless your application uses COM interop, this attribute actually does nothing at all. So what exactly does it do, and how does it affect multithreaded applications? Should multithreaded applications (which includes anything from anyone using `Timer`s to asynchronous method calls, not just threadpools and the like) use MTAThread, even if it's 'just to be safe'? What does STAThread and MTAThread actually do?
Apartment threading is a COM concept; if you're not using COM, and none of the APIs you call use COM "under the covers", then you don't need to worry about apartments. If you do need to be aware of apartments, then the details can get [a little complicated](http://msdn.microsoft.com/en-us/library/ms693344(VS.85).aspx); a probably-oversimplified version is that COM objects tagged as STA must be run on an STAThread, and COM objects marked MTA must be run on an MTA thread. Using these rules, COM can optimize calls between these different objects, avoiding marshaling where it isn't necessary.
What that does it it ensures that `CoInitialize` is called specifying COINIT\_APARTMENTTHREADED as the parameter. If you do not use any COM components or ActiveX controls it will have no effect on you at all. If you do then it's kind of crucial. Controls that are apartment threaded are effectively single threaded, calls made to them can only be processed in the apartment that they were created in. Some more detail from MSDN: > Objects created in a single-threaded > apartment (STA) receive method calls > only from their apartment's thread, so > calls are serialized and arrive only > at message-queue boundaries (when the > Win32 function PeekMessage or > SendMessage is called). > > Objects created on a COM thread in a > multithread apartment (MTA) must be > able to receive method calls from > other threads at any time. You would > typically implement some form of > concurrency control in a multithreaded > object's code using Win32 > synchronization primitives such as > critical sections, semaphores, or > mutexes to help protect the object's > data. > > When an object that is configured to > run in the neutral threaded apartment > (NTA) is called by a thread that is in > either an STA or the MTA, that thread > transfers to the NTA. If this thread > subsequently calls CoInitializeEx, the > call fails and returns > RPC\_E\_CHANGED\_MODE.
STAThread and multithreading
[ "", "c#", ".net", "multithreading", "sta", "" ]
### What are some methods of utilising Eclipse for Dependency Management?
I really like the [The Maven Integration for Eclipse (m2eclipse, Eclipse m2e)](http://maven.apache.org/eclipse-plugin.html). I use it purely for the dependency management feature. It's great not having to go out and download a bunch of new jars new each time I set up a project.
A simpler way to go is the [Maven Eclipse plugin](http://maven.apache.org/plugins/maven-eclipse-plugin/) (as opposed to a Maven plugin for Eclipse). It's simply a maven plugin that generates the .project and .classpath file based on the contents of the pom, you just run `mvn eclipse:eclipse` and you're done. It uses a classpath variable in Eclipse to locate the local maven repo. I personally prefer this approach most of the time because you have more control over when the maven plugin updates are done. It's also one less Eclipse plugin to deal with. The GUI features of the m2eclipse plugin in the latest version is pretty nice, though. There's also an alternative to the m2eclipse plugin called [Q4E](http://code.google.com/p/q4e/), now called [Eclipse IAM](http://www.eclipse.org/iam/).
Eclipse: Dependency Management
[ "", "java", "eclipse", "maven-2", "eclipse-plugin", "dependencies", "" ]
In Windows, is there an easy way to tell if a folder has a subfile that has changed? I verified, and the last modified date on the folder does not get updated when a subfile changes. Is there a registry entry I can set that will modify this behavior? If it matters, I am using an NTFS volume. I would ultimately like to have this ability from a C++ program. **Scanning an entire directory recursively will not work for me because the folder is much too large.** **Update: I really need a way to do this without a process running while the change occurs. So installing a file system watcher is not optimal for me.** **Update2: The archive bit will also not work because it has the same problem as the last modification date. The file's archive bit will be set, but the folders will not.**
This [article](http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx) should help. Basically, you create one or more notification object such as: ``` HANDLE dwChangeHandles[2]; dwChangeHandles[0] = FindFirstChangeNotification( lpDir, // directory to watch FALSE, // do not watch subtree FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes if (dwChangeHandles[0] == INVALID_HANDLE_VALUE) { printf("\n ERROR: FindFirstChangeNotification function failed.\n"); ExitProcess(GetLastError()); } // Watch the subtree for directory creation and deletion. dwChangeHandles[1] = FindFirstChangeNotification( lpDrive, // directory to watch TRUE, // watch the subtree FILE_NOTIFY_CHANGE_DIR_NAME); // watch dir name changes if (dwChangeHandles[1] == INVALID_HANDLE_VALUE) { printf("\n ERROR: FindFirstChangeNotification function failed.\n"); ExitProcess(GetLastError()); } ``` and then you wait for a notification: ``` while (TRUE) { // Wait for notification. printf("\nWaiting for notification...\n"); DWORD dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE, INFINITE); switch (dwWaitStatus) { case WAIT_OBJECT_0: // A file was created, renamed, or deleted in the directory. // Restart the notification. if ( FindNextChangeNotification(dwChangeHandles[0]) == FALSE ) { printf("\n ERROR: FindNextChangeNotification function failed.\n"); ExitProcess(GetLastError()); } break; case WAIT_OBJECT_0 + 1: // Restart the notification. if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE ) { printf("\n ERROR: FindNextChangeNotification function failed.\n"); ExitProcess(GetLastError()); } break; case WAIT_TIMEOUT: // A time-out occurred. This would happen if some value other // than INFINITE is used in the Wait call and no changes occur. // In a single-threaded environment, you might not want an // INFINITE wait. printf("\nNo changes in the time-out period.\n"); break; default: printf("\n ERROR: Unhandled dwWaitStatus.\n"); ExitProcess(GetLastError()); break; } } } ```
This is perhaps overkill, but the [IFS kit](http://www.microsoft.com/whdc/devtools/ifskit/default.mspx) from MS or the [FDDK](http://www.osr.com/toolkits_fddk.shtml) from OSR might be an alternative. Create your own filesystem filter driver with simple monitoring of all changes to the filesystem.
How to see if a subfile of a directory has changed
[ "", "c++", "windows", "filesystems", "ntfs", "" ]
In our application, we are using RMI for client-server communication in very different ways: 1. Pushing data from the server to the client to be displayed. 2. Sending control information from the client to the server. 3. Callbacks from those control messages code paths that reach back from the server to the client (sidebar note - this is a side-effect of some legacy code and is not our long-term intent). What we would like to do is ensure that all of our RMI-related code will use only a known specified inventory of ports. This includes the registry port (commonly expected to be 1099), the server port and any ports resulting from the callbacks. Here is what we already know: 1. LocateRegistry.getRegistry(1099) or Locate.createRegistry(1099) will ensure that the registry is listening in on 1099. 2. Using the UnicastRemoteObject constructor / exportObject static method with a port argument will specify the server port. These points are also covered in this [Sun forum post](http://forums.sun.com/thread.jspa?threadID=370039&messageID=1566073). What we don't know is: how do we ensure that the client connections back to the server resulting from the callbacks will only connect on a specified port rather than defaulting to an anonymous port? EDIT: Added a longish answer summarizing my findings and how we solved the problem. Hopefully, this will help anyone else with similar issues. SECOND EDIT: It turns out that in my application, there seems to be a race condition in my creation and modification of socket factories. I had wanted to allow the user to override my default settings in a Beanshell script. Sadly, it appears that my script is being run significantly after the first socket is created by the factory. As a result, I'm getting a mix of ports from the set of defaults and the user settings. More work will be required that's out of the scope of this question but I thought I would point it out as a point of interest for others who might have to tread these waters at some point....
You can do this with a custom RMI Socket Factory. The socket factories create the sockets for RMI to use at both the client and server end so if you write your own you've got full control over the ports used. The client factories are created on the server, Serialized and then sent down to the client which is pretty neat. [Here's a guide at Sun telling you how to do it.](http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/socketfactory/)
You don't need socket factories for this, or even multiple ports. If you're starting the Registry from your server JVM you can use port 1099 for everything, and indeed that is what will happen by default. If you're not starting the registry at all, as in a client callback object, you can provide port 1099 when exporting it. The part of your question about 'the client connections back to the server resulting from callbacks' doesn't make sense. They are no different from the original client connections to the server, and they will use the same server port(s).
How do I ensure that RMI uses only a specific set of ports?
[ "", "java", "rmi", "" ]
I've worked on many projects where I've been given code by others to update. More often than not I compile it and get about 1,000+ compiler warnings. When I see compiler warnings they make me feel dirty, so my first task is to clean up the code and remove them all. Typically I find about a dozen problems like uninitialized variables such. I don't understand why people leave them in and don't have perfectly clean compiles with no warnings. Am I missing something? Is there any valid reason to just leave them? Any horror stories to share?
I would clean up any warning. Even the ones that you know are harmless (if such a thing exists) will give a bad impression of you to whoever will compile the code. It one of the "smelly" signs I would look for if I had to work on someone else code. If not real errors or potential future issues, it would be a sign of sloppiness
Clean 'em up, even if they don't indicate a real problem. Otherwise, if a warning that **does** indicate a real problem shows up, you won't see it through all the noise.
C / C++ compiler warnings: do you clean up all your code to remove them or leave them in?
[ "", "c++", "c", "compiler-construction", "warnings", "" ]
I have two collections which have property `Email` in both collections. I need to get a list of the items in the first list where `Email` does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done? So far I have a join, like... ``` var matches = from item1 in list1 join item2 in list2 on item1.Email equals item2.Email select new { Email = list1.Email }; ``` But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.
I don't know if this will help you but.. ``` NorthwindDataContext dc = new NorthwindDataContext(); dc.Log = Console.Out; var query = from c in dc.Customers where !(from o in dc.Orders select o.CustomerID) .Contains(c.CustomerID) select c; foreach (var c in query) Console.WriteLine( c ); ``` from [The NOT IN clause in LINQ to SQL](https://web.archive.org/web/20120321161927/https://www.programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx) by [Marco Russo](https://web.archive.org/web/20110805143247/http://introducinglinq.com/blogs/marcorusso/default.aspx)
You want the Except operator. ``` var answer = list1.Except(list2); ``` Better explanation here: <https://learn.microsoft.com/archive/blogs/charlie/linq-farm-more-on-set-operators> **NOTE:** This technique works best for primitive types only, since you have to implement an [IEqualityComparer](https://learn.microsoft.com/dotnet/api/system.collections.generic.iequalitycomparer-1) to use the `Except` method with complex types.
How would you do a "not in" query with LINQ?
[ "", "c#", "linq", "" ]
Coming from a C# background the naming convention for variables and methods are usually either camelCase or PascalCase: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen snake\_case being used: ``` # python example this_is_my_variable = 'a' def this_is_my_function(): ``` Is there a more preferable, definitive coding style for Python?
See Python [PEP 8: Function and Variable Names](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names): > Function names should be [lowercase, with words separated by underscores](https://en.wikipedia.org/wiki/Snake_case) as necessary to improve readability. > > Variable names follow the same convention as function names. > > [mixedCase](https://en.wikipedia.org/wiki/MixedCase) is allowed only in contexts where that's already the prevailing style (e.g. [threading.py](https://docs.python.org/library/threading.html)), to retain backwards compatibility.
The [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html#316-naming) has the following convention: > `module_name`, `package_name`, `ClassName`, `method_name`, `ExceptionName`, `function_name`, `GLOBAL_CONSTANT_NAME`, `global_var_name`, `instance_var_name`, `function_parameter_name`, `local_var_name`. A similar naming scheme should be applied to a `CLASS_CONSTANT_NAME`
What is the naming convention in Python for variables and functions?
[ "", "python", "naming-conventions", "camelcasing", "pascalcasing", "snakecasing", "" ]
I intend to develop a system that is entirely based on modules. The system base should have support for finding out about plugins, starting them up and being able to provide ways for those modules to communicate. Ideally, one should be able to put in new modules and yank out unused modules at will, and modules should be able to use each other's funcionality if it is available. This system should be used as a basis for simulation systems where a lot of stuff happens in different modules, and other modules might want to do something based on that. The system I intend to develop is going to be in Java. The way I see it, I intend to have a folder with a subfolder for each module that includes a XML that describes the module with information such as name, maybe which events it might raise, stuff like that. I suppose I might need to write a custom ClassLoader to work this stuff out. The thing is, I don't know if my idea actually holds any water and, of course, I intend on building a working prototype. However, I never worked on a truly modular system before, and I'm not really sure what is the best way to take on this problem. Where should I start? Are there common problems and pitfalls that are found while developing this kind of system? How do I make the modules talk with each other while maintaining isolation (i.e, you remove a module and another module that was using it stays sane)? Are there any guides, specifications or articles I can read that could give me some ideas on where to start? It would be better if they were based on Java, but this is not a requirement, as what I'm looking for right now are ideas, not code. Any feedback is appreciated.
You should definitely look at [OSGi](http://www2.osgi.org/Specifications/HomePage). It aims at being *the* component/plugin mechanism for Java. It allows you to modularize your code (in so-called bundles) and update bundles at runtime. You can also completely hide implementation packages from unwanted access by other bundles, eg. only provide the API. Eclipse was the first major open-source project to implement and use OSGi, but they didn't fully leverage it (no plugin installations/updates without restarts). If you start from scratch though, it will give you a very good framework for a plugin system. [Apache Felix](http://felix.apache.org) is a complete open-source implementation (and there are others, such as [Eclipse Equinox](http://www.eclipse.org/equinox/)).
Another option is the [ServiceLoader](http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html) added in Java 1.6.
How should I start when developing a system based on modules or plugins?
[ "", "java", "events", "plugins", "module", "" ]
How can I send an email from C++? Is there a good cross-platform (MS Windows, Linux etc) library that I can use? I'm using GCC (cygwin on MS Windows).
Check out jwSMTP - a cross-platform SMTP class. <http://johnwiggins.net/jwsmtp/>
Check out [C-Client](http://www.washington.edu/imap/) * Apache license * Very established library ( makers of Pine email reader, UW-IMAP Server, etc. ) * Supports IMAP, POP, SMTP, and NNTP * Unix and Windows
How to send Email through a C++ program?
[ "", "c++", "email", "gcc", "" ]
In a C++ file, I have code like this: ``` #if ACTIVATE # pragma message( "Activated" ) #else # pragma message( "Not Activated") #endif ``` I want to set this ACTIVE define to 1 with the MSBuild command line. It tried this, but it doesn't work: ``` msbuild /p:DefineConstants="ACTIVATE=1" ``` How can I do it?
The answer to ponder is: ***you cannot***
Our solution was to use an environment variable with `/D` defines in it, combined with the *Additional Options* box in Visual Studio. 1. In Visual Studio, add an environment variable macro, `$(ExternalCompilerOptions)`, to the Additional Options under project options → *C/C++* → *Command Line* (remember both *Debug* and *Release* configurations) 2. Set the environment variable prior to calling MSBuild. Use the `/D` compiler option to define your macros ``` cd c:\ set ExternalCompilerOptions=/DFOO /DBAR msbuild ``` Item #1 ends up looking like this in the *.vcxproj* file: ``` <ClCompile> <AdditionalOptions>$(ExternalCompilerOptions) ... </AdditionalOptions> </ClCompile> ``` This works for me with [Visual Studio 2010](https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2010). We drive MSBuild from various build scripts, so the environment variable ugliness is hidden a bit. Note that I have not tested if this works when you need to set the define to specific value (`/DACTIVATE=1`). I think it would work, but I'm concerned about having multiple '='s in there.
MSBuild: set a specific preprocessor #define in the command line
[ "", "c++", "visual-studio", "msbuild", "" ]
I use `public boolean mouseDown(Event ev, int x, int y)` to detect a click of the mouse. I can distinguish between the right mouse button (ev.metaDown() is true) and the left and middle. How can i differentiate the left from the middle button? Or if it is impossible with mouseDown, what should i use?
Try using [ALT\_MASK](http://java.sun.com/javase/6/docs/api/java/awt/Event.html#ALT_MASK): > This flag indicates that the Alt key was down when the event occurred. For mouse events, this flag indicates that the middle mouse button was pressed or released. So your code might be: ``` if (ev.modifiers & Event.ALT_MASK != 0) { // middle button was pressed } ``` Of course, all this is assuming you have a *very* good reason to use mouseDown in the first place, since it is deprecated. You should (probably) be using [processMouseEvent](http://java.sun.com/javase/6/docs/api/java/awt/Component.html#processMouseEvent(java.awt.event.MouseEvent)) instead, which gives you a MouseEvent to play with.
[mouseDown](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#mouseDown%28java.awt.Event,%20int,%20int%29) is deprecated. All you need is accessible by the MouseEvent.[getButton](http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html#getButton()). Track BUTTON3.
How to fetch the middle mouse button in java?
[ "", "java", "events", "mouse", "" ]
I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use ([details](http://issues.apache.org/bugzilla/show_bug.cgi?id=42411)). I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties: * No external dependencies * Simple and reliable * Support for [`If-Modified-Since`](http://www.freesoft.org/CIE/RFC/1945/58.htm) header (i.e. custom [`getLastModified`](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html#getLastModified(javax.servlet.http.HttpServletRequest)) method) * (Optional) support for gzip encoding, etags,... Is such a servlet available somewhere? The closest I can find is [example 4-10](http://www.unix.org.ua/orelly/java-ent/servlet/ch04_04.htm#ch04-35758) from the servlet book. **Update:** The URL structure I want to use - in case you are wondering - is simply: ``` <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping> ``` So all requests should be passed to the main servlet, unless they are for the `static` path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the `static` folder).
I ended up rolling my own `StaticServlet`. It supports `If-Modified-Since`, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either. The code is available: [StaticServlet.java](http://bruno.defraine.net/StaticServlet.java). Feel free to comment. **Update:** Khurram asks about the `ServletUtils` class which is referenced in `StaticServlet`. It is simply a class with auxiliary methods that I used for my project. The only method you need is `coalesce` (which is identical to the SQL function [`COALESCE`](http://en.wikipedia.org/wiki/Null_(SQL)#COALESCE)). This is the code: ``` public static <T> T coalesce(T...ts) { for(T t: ts) if(t != null) return t; return null; } ```
I came up with a slightly different solution. It's a bit hack-ish, but here is the mapping: ``` <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>myAppServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` This basically just maps all content files by extension to the default servlet, and everything else to "myAppServlet". It works in both Jetty and Tomcat.
Servlet for serving static content
[ "", "java", "jsp", "servlets", "jakarta-ee", "" ]
Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example: ``` int[] terms; for(int runs = 0; runs < 400; runs++) { terms[] = runs; } ``` For those who have used PHP, here's what I'm trying to do in C#: ``` $arr = array(); for ($i = 0; $i < 10; $i++) { $arr[] = $i; } ```
You can do this way - ``` int[] terms = new int[400]; for (int runs = 0; runs < 400; runs++) { terms[runs] = value; } ``` Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list. ``` List<int> termsList = new List<int>(); for (int runs = 0; runs < 400; runs++) { termsList.Add(value); } // You can convert it back to an array if you would like to int[] terms = termsList.ToArray(); ``` **Edit:** [a) **for** loops on List<T> are a bit more than 2 times cheaper than **foreach** loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using **for** is 5 times cheaper than looping on List<T> using **foreach** (which most of us do).](https://stackoverflow.com/a/365658/495455)
Using [Linq](https://learn.microsoft.com/en-us/dotnet/api/system.linq)'s method [Concat](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.concat) makes this simple ``` int[] array = new int[] { 3, 4 }; array = array.Concat(new int[] { 2 }).ToArray(); ``` result 3,4,2
Adding values to a C# array
[ "", "c#", "arrays", "" ]
What is an example of a fast SQL to get duplicates in datasets with hundreds of thousands of records. I typically use something like: ``` SELECT afield1, afield2 FROM afile a WHERE 1 < (SELECT count(afield1) FROM afile b WHERE a.afield1 = b.afield1); ``` But this is quite slow.
This is the more direct way: ``` select afield1,count(afield1) from atable group by afield1 having count(afield1) > 1 ```
You could try: ``` select afield1, afield2 from afile a where afield1 in ( select afield1 from afile group by afield1 having count(*) > 1 ); ```
Fastest "Get Duplicates" SQL script
[ "", "sql", "scripting", "duplicates", "performance", "" ]
I'm trying to do the following without too much special case code to deal with invalidated POSITIONs etc: What's the best way to fill in the blanks? ``` void DeleteUnreferencedRecords(CAtlMap<Record>& records) { for(____;____;____) { if( NotReferencedElsewhere(record) ) { // Delete record _______; } } } ```
According to this: <http://msdn.microsoft.com/en-us/library/0h4c3zkw(VS.80).aspx> RemoveAtPos has these semantics > Removes the key/value pair stored at the specified position. The memory used to store the element is freed. The POSITION referenced by pos becomes invalid, and while the POSITION of any other elements in the map remains valid, they do not necessarily retain the same order. The problem is that the order can change -- which means that GetNext() won't really continue the iteration. It looks like you need to collect the POSITIONs you want to delete in one pass and delete them in the next. Removing a POSITION does not invalidate the other POSITION objects
I'm not too familiar with `CAtlMap`, but if it's similar to the STL's `map` type, then [Rob's "first thought"](https://stackoverflow.com/questions/197121/how-do-i-write-a-for-loop-that-iterates-over-a-catlmap-selectively-deleting-ele#197209) is safe -- deleting an item does not affect any iterators except the one(s) pointing to the item being deleted.
How do I write a for loop that iterates over a CAtlMap selectively deleting elements as it goes?
[ "", "c++", "atl", "" ]
How do I make my application always use English when displaying win32/.net exceptions messages? I got this message, it looks like someone used babelfish to translate it (it's Swedish): "System.ComponentModel.Win32Exception: Programmet kunde inte starta eftersom programmets sida-vid-sidakonfiguration är felaktig." Extremely unhelpful, and Google had a whopping 4 hits for it, none of them helpful. So I have to guess what the original message was and google that. (It's was: "The application has failed to start because its side-by-side configuration is incorrect.") This time it was fairly simple to find out what the original error message was, having the message in English from the start would of course save me time. So how do I do that?
You can try setting `Thread.CurrentThread.CurrentUICulture` and/or `.CurrentCulture` to `CultureInfo("en-US")`.
If it's an ASP.NET application, you can set the UI language in web.config (\*): ``` <system.web> <globalization ... uiCulture="en-US" ... /> </system.web> ``` For other applications, the current user's regional settings are used by default, and you have to explicitly override it - e.g. Thread.CurrentUICulture = new CultureInfo("en-US"). (\*) caveat - if an error in the config file results in an exception being thrown before the element is processed, you'll get the default uiCulture.
Prevent exception messages from being translated into the user's language?
[ "", "c#", ".net", "exception", "globalization", "" ]
I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header. ``` <rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/> <rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}" var="fieldValues" rowKeyVar="rowKey"> <rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx"> <f:facet name="header"> <h:outputText value="#{column}"/> </f:facet> <h:outputText value="#{classFieldValues[idx]}" /> </rich:columns> </rich:dataTable> ``` I already have a method on the bean for executing the sort. ``` public void sort(int column) ```
I ended up doing it manually. I adding a support tag to the header text tag, like so. ``` <h:outputText value="#{column}"> <a4j:support event="onclick" action="#{pageDataModel.sort(idx)}" eventsQueue="instancesQueue" reRender="instanceList,instanceListScroller"/> </h:outputText> ``` To get the ascending/descending arrows, I added a css class. ``` <h:outputText value="#{column}" styleClass="#{pageDataModel.getOrderClass(idx)}" > <a4j:support event="onclick" action="#{pageDataModel.sort(idx)}" eventsQueue="instancesQueue" reRender="instanceList,instanceListScroller"/> </h:outputText> ```
There is a fairly elegant solution to this solution here: <http://livedemo.exadel.com/richfaces-demo/richfaces/sortingFeature.jsf?tab=ex-usage> This demo avoids using the tag.
Server-side DataTable Sorting in RichFaces
[ "", "java", "ajax", "jsf", "richfaces", "" ]
I'm building small web site in Java (Spring MVC with JSP views) and am trying to find best solution for making and including few reusable modules (like "latest news" "upcoming events"...). So the question is: Portlets, tiles or some other technology?
If you are using Spring MVC, then I would recommend using Portlets. In Spring, portlets are just lightweight controllers since they are only responsible for a fragment of the whole page, and are very easy to write. If you are using Spring 2.5, then you can enjoy all the benefits of the new annotation support, and they fit nicely in the whole Spring application with dependency injection and the other benefits of using Spring. A portlet controller is pretty much the same as a servlet controller, here is a simple example: ``` @RequestMapping("VIEW") @Controller public class NewsPortlet { private NewsService newsService; @Autowired public NewsPortlet(NewsService newsService) { this.newsService = newsService; } @RequestMapping(method = RequestMethod.GET) public String view(Model model) { model.addAttribute(newsService.getLatests(10)); return "news"; } } ``` Here, a NewsService will be automatically injected into the controller. The view method adds a List object to the model, which will be available as ${newsList} in the JSP. Spring will look for a view named news.jsp based on the return value of the method. The RequestMapping tells Spring that this contoller is for the VIEW mode of the portlet. The XML configuration only needs to specify where the view and controllers are located: ``` <!-- look for controllers and services here --> <context:component-scan base-package="com.example.news"/> <!-- look for views here --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/news/"/> <property name="suffix" value=".jsp"/> </bean> ``` If you want to simply embed the portlets in your existing application, the you can bundle a portlet container, such as [eXo](http://www.exoplatform.com), [Sun](https://portlet-container.dev.java.net/), or [Apache](http://portals.apache.org/pluto/). If you want to build your application as a set of portlets, the you might want to consider a full blown portlal solution, such as [Liferay Portal](http://liferay.com).
Tiles can be a pain. Vast improvement over what came before (i.e. nothing), but rather limiting. [Wicket](http://wicket.apache.org/) might be more what you're looking for, unless you've settled on JSP.
What's the best way to make a modular java web application
[ "", "java", "spring-mvc", "module", "" ]
I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints. What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either? Also, how would I go about packaging everything up in binaries of *reasonable* size for each target OS? (my main targets are Windows and Mac OS X) *Addition:* I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx\_freeze and getting 30mb+ binaries, and no real advice on how to *actually* do the packaging and how trust-worthy it is.
<http://wiki.wxpython.org/CreatingStandaloneExecutables> It shouldn't be that large unless you have managed to include the debug build of wx. I seem to rememebr about 4Mb for the python.dll and similair for wx.
This may help: [How can I make an EXE file from a Python program?](https://stackoverflow.com/questions/49146/what-is-the-best-way-to-make-an-exe-file-from-a-python-program)
Python GUI Application redistribution
[ "", "python", "user-interface", "wxpython", "distribution", "freeze", "" ]
I have a website which uses the custom 404 error handling in PHP/Apache to display specific pages. e.g. <http://metachat.org/recent> I've a feeling this is a bad way of doing this, but it's code I inherited... Although the page displays correctly on most browsers, I'm getting a situation where AVG Anti-Virus is hijacking the page and redirecting it to an offsite 404 page. I've tried to force a header (Status: 200 OK) using the header command in PHP, but if I do a curl -I of the page, I get the following... ``` HTTP/1.1 404 Not Found Date: Fri, 03 Oct 2008 11:43:01 GMT Server: Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 PHP/4.3.10-16 mod_ssl/2 .0.54 OpenSSL/0.9.7e X-Powered-By: PHP/4.3.10-16 Status: 200 OK Content-Type: text/html ``` I guess that first line is the line AVG traps for its forced redirect. Without rewriting the software to use Mod\_rewrite (which I don't really understand), how can I (in PHP) stop the "HTTP:/1/1 404 Not Found" line being sent in the headers when displaying this page? Thanks.
There's no way other than using URL rewriting (mod\_rewrite) or creating the missing pages. What's happening is that the client requests a page which doesn't exist. Apache is configured to serve a special page upon 404 errors, but it still sends the 404 status code, then AVG traps that. So, you could do something like: ``` RewriteEngine On RewriteCond %{REQUEST_URI} !-f RewriteCond %{REQUEST_URI} !-d RewriteRule (.*) index.php?missing_content=$1 ``` That will rewrite everything that doesn't exist (and would thus give a 404) to your index.php with the URL path in the missing\_content query string parameter
If what you get is a *Page Not Found* error, **don't** make it send Status 200 OK. Please. It's one of most annoying "tricks" people do for whatever reason. If the page user requests does not exist, tell this to him, as well as to his browser. And to search engines, that otherwise will crawl/cache your custom error-page thinking it's the actual response. If someone has some software installed that displays something else instead of your 404, it's his own problem and don't try to fight it making your service lie to the browser :)
PHP - Custom error handling. Redirected 404 is being hijacked by AVG Anti-Virus. How to stop?
[ "", "php", "http-headers", "http-status-code-404", "antivirus", "" ]
I'm learning DirectX as part of a hobby project. I've been looking for some good online resources for DirectX9 (using C++, if that distinction matters), but haven't found anything that's a) great for a beginner and b) up to date. Any recommendations?
When I started using DirectX I found this to be the best resource around for basic stuff: <http://www.directxtutorial.com/> When you start reaching an intermediate level they want you to pay a subscription but all the good basic stuff is free. Tutorials are clear and literally step-by-step. This is website is not bad at all either: <http://www.toymaker.info/> - with some good project downloads. If you have problems the best place to go in my experience is <http://www.gamedev.net/> , they have great articles and forums with plenty of so-called gurus.
* [Toymaker](http://www.toymaker.info/Games/index.html) * [Triple Buffer](http://triplebuffer.devmaster.net/list.php?display=s&page=0) * [DirectX4VB](http://directx4vb.vbgamer.com/DirectX4VB/TUT_DX9Start.asp) * [32Bits](http://www.32bits.co.uk/) [Introduction to 3D Game Programming with DirectX 9](https://rads.stackoverflow.com/amzn/click/com/1556229135): Not an online resource, but that book was very helpful to me. There's also the DirecX SDK documentation, which should be your definitive resource.
What are some good DirectX resources for a beginner?
[ "", "c++", "resources", "directx", "" ]
What is the difference between `bool` and `Boolean` types in C#?
`bool` is an alias for `System.Boolean` just as `int` is an alias for `System.Int32`. See a full list of aliases here: [Built-In Types Table (C# Reference)](https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx).
I don't believe there is one. `bool` is just an alias for `System.Boolean`
What is the difference between bool and Boolean types in C#
[ "", "c#", "types", "boolean", "" ]
I personally use [`var_dump`](http://php.net/var_dump), but lots of people like [`print_r`](http://php.net/print_r). What does everyone use? Pros and Cons? Does someone have a special home brew function of their own?
I always use the Xdebug extended var\_dump. It gives out a lot of verbose output. See: <http://xdebug.org/docs/display> for more details.
I use `print_r()` because I like the pretty array structure... but `var_dump` does give you a bit more information (like types) ``` $obj = (object) array(1, 2, 3); // output of var_dump: object(stdClass)#1 (3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } // output of print_r stdClass Object ( [0] => 1 [1] => 2 [2] => 3 ) ```
Which php variable debugging function do you use? var_dump, print_r, var_export, other?
[ "", "php", "debugging", "" ]
I have this Python application that gets stuck from time to time and I can't find out where. Is there any way to signal Python interpreter to show you the exact code that's running? Some kind of on-the-fly stacktrace? ***Related questions:*** * [Print current call stack from a method in Python code](https://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code) * [Check what a running process is doing: print stack trace of an uninstrumented Python program](https://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py)
I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals): ``` import code, traceback, signal def debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message) def listen(): signal.signal(signal.SIGUSR1, debug) # Register handler ``` To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python: ``` os.kill(pid, signal.SIGUSR1) ``` This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive. I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a [python cookbook recipe](http://code.activestate.com/recipes/576515/).
The suggestion to install a signal handler is a good one, and I use it a lot. For example, [bzr](http://bazaar-vcs.org/) by default installs a SIGQUIT handler that invokes `pdb.set_trace()` to immediately drop you into a [pdb](http://docs.python.org/lib/module-pdb.html) prompt. (See the [bzrlib.breakin](https://bazaar.launchpad.net/%7Ebzr-pqm/bzr/bzr.dev/view/head:/bzrlib/breakin.py) module's source for the exact details.) With pdb you can not only get the current stack trace (with the `(w)here` command) but also inspect variables, etc. However, sometimes I need to debug a process that I didn't have the foresight to install the signal handler in. On linux, you can attach gdb to the process and get a python stack trace with some gdb macros. Put <http://svn.python.org/projects/python/trunk/Misc/gdbinit> in `~/.gdbinit`, then: * Attach gdb: `gdb -p` *`PID`* * Get the python stack trace: `pystack` It's not totally reliable unfortunately, but it works most of the time. See also <https://wiki.python.org/moin/DebuggingWithGdb> Finally, attaching `strace` can often give you a good idea what a process is doing.
Showing the stack trace from a running Python application
[ "", "python", "debugging", "stack-trace", "traceback", "" ]
Basically, I have a class with 2 methods: one to serialize an object into an XML file and another to read an object from XML. Here is an example of synchronized part from the method that restores an object: ``` public T restore(String from) throws Exception { // variables declaration synchronized (from) { try { decoder = new XMLDecoder(new BufferedInputStream( new FileInputStream(from))); restoredItem = decoder.readObject(); decoder.close(); } catch (Exception e) { logger.warning("file not found or smth: " + from); throw new Exception(e); } } // try to cast it } ``` A similar approach is taken when serializing an object. Now, when I create a unit test which in turn creates 10 threads with each thread trying to serialize and instantly read either a Boolean or a String it would fail showing that ClassCastExceptions occur. This makes me think that I get serialization wrong (everything's ok in a single-threaded environment). If you've stayed with me down to this point :), here are the 2 issues I need your help on: 1. does it make sense to synchronize on a string argument passed to method (considering there's a string pool in java)? BTW, I've tried synchronizing on the XMLSerializer class itself with result staying the same. 2. how do i correctly synchronize io operations on a single file?
1. Yes, it's OK to synchronize on a String, however you'd need to synchronize on the string.[intern()](http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()) in order to always get the same Object ``` StringBuffer sb = new StringBuffer(); sb.append("a").append("b"); String a = new String(sb.toString()); String b = new String(sb.toString()); a == b; //false a.equals(b); //true a.intern() == b.intern(); //true ``` Since you want to synchronize on the same monitor, you'd want the intern(). 2. You'd probably not want to synchronize on a String since it may synchronized on somewhere else, inside your code, in 3rd party or in the JRE. What I'd do, if I wanted to stay with synchronize, is create an ID class (which may hold only String), override equals() and hashcode() to match, put it in a WeakHashMap with both as key and value (see IdentityHashMap for idea why) and use only what I .get() from the map (sync map{ syncKey = map.get(new ID(from)); if syncKey==null create and put new key} sync{syncKey}). 3. Then again, I'd ditch synchronize all together and use the java.util.concurrent.locks.Lock instead, in the same setup as above only with the lock attached to the ID.
Given that the some parts of your code are missing, my bet is that the problem lies with synchronizing on a string. You cannot freely assume that strings are pooled (which would break your synchronization scheme). The best approach would be to add a map that will associate a key (string) with its actual synchronization object. Other than that, I would suggest to play with the multi-threaded test to see what make it fail. For example, if you make all threads only store string values (rather than strings or beooleans), does the test still fail?
synchronizing io operation in java on a string method argument?
[ "", "java", "multithreading", "synchronization", "io", "" ]
I'm currently using default implementation of STL for VS2005 and I'm [not really satisfied](https://stackoverflow.com/questions/186494/ifstr1str2-versus-ifstr1lengthstr2length-str1str2) with it. Perhaps there is something better?
The Dinkumware STL implementation (supplied with VS2005) is actually quite good. The STL is a general purpose library and so it is almost always possible to write something better for very specific use cases. I'm aware of the following alternative implementations, but I've never used them with VS2005: SGI Standard Template Library 3.3: <http://www.sgi.com/tech/stl/> STLport 5.1.6 (derived from SGI implementation): <http://www.stlport.org/> Both SGI and STLport implement the size/length check as the first test in operator== and so you might like it. They are also both free to download and use. Changing from one STL implementation to another, in theory, should be easy. However, I've heard from some colleagues that it is not always so. They've tripped over compiler bugs, found that they've inadvertently used non-standard features, or unknowingly relied on some behaviour specific to a particular STL implementation. One good thing about the Dinkumware STL implementation is that it has been well tested with the VS2005 C++ compiler. If you decide to try out these alternatives, good luck! And let us know how it goes.
How about STLPort? <http://www.stlport.org/>
What is the best implementation of STL for VS2005?
[ "", "c++", "visual-studio-2005", "stl", "" ]
In my webapplication (C#, .Net 3.5), made up of a *core* class library (containing the business logic, data layer and a couple of utility classes), a windows service project, a webservice project and the website project, I have a couple of static classes in the *core* library used by all other projects. These classes (for example the **Log** class) require some initialization (They have an **Initialize** method) in order to set them up for usage. As an example, the **Initialize** method of the **Log** class has a directory path parameter which tells the **Log**, where to save the logfiles to. Alternativly I was thinking of loading the "settings" for the **Log** class from a configuration file in the static constructor. The drawback is, that I need different settings for unit-testing then in production code. Is there a better way to design this? The drawback of this approach is, that all consumers of the static class will attempt to call Initialize. This is not really a problem because once initialized, the method will return immediately instead of executing the Initialize code again, but the design seems a bit weird to me. I hope my english is sufficient to explain what I'm after. Do not hesitate to ask if the question is not clear enough.
I would try to avoid static classes for things which will require initialization. Make your Log class a normal class, and perhaps have a separate factory class to create instances or a single instance. You might want to use dependency injection to avoid having any statics, although this could get painful for something like logging which is pretty universal though. For logging in particular, both log4net and log4j (any reason you've rolled your own, btw?) use the idiom of asking some factory class for log instances based on names (commonly based on the name of the type using it). This is often stored in a static variable in each class which needs to perform logging. If the logging objects which are returned can still be affected by initialization of the logging subsystem afterwards, you don't end up with ordering concerns where the DI container has to initialize the logging framework before the logging clients are initialized etc. Using separate logging objects instead of a static class improves testability - you can replace the logging object during a test with one which records the logs to ensure that (say) auditing information is captured. One downside of the logging objects being known statically is that this reduces the possibilities of running tests in parallel. Apologies for the somewhat random musings - I haven't had my first coffee yet. Hopefully it's helpful though.
I would suggest, if the initialisation is expensive, to use a Singleton (if you're not familiar with design patterns, google Singleton Design pattern). As part of the construction of the instance, you then read in a config file, which can be specific to the environment. This way you would get the best of both worlds.
Initializing static objects - Code design question
[ "", "c#", "design-patterns", "architecture", "static", "" ]
Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.
That's very nice, however in order to simulate some time passing we need to run a command that takes some time and that's very clear in second example. However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that. We can see this modification in the code from the same book CLR Via C# Third Ed. ``` using System; using System.Threading; public static class Program { private Timer _timer = null; public static void Main() { // Create a Timer object that knows to call our TimerCallback // method once every 2000 milliseconds. _timer = new Timer(TimerCallback, null, 0, 2000); // Wait for the user to hit <Enter> Console.ReadLine(); } private static void TimerCallback(Object o) { // Display the date/time when this method got called. Console.WriteLine("In TimerCallback: " + DateTime.Now); } } ```
Use the System.Threading.Timer class. System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread. There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway. It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object. Here's an example of a timer in a console application: ``` using System; using System.Threading; public static class Program { public static void Main() { Console.WriteLine("Main thread: starting a timer"); Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); Console.WriteLine("Main thread: Doing other work here..."); Thread.Sleep(10000); // Simulating other work (10 seconds) t.Dispose(); // Cancel the timer now } // This method's signature must match the TimerCallback delegate private static void ComputeBoundOp(Object state) { // This method is executed by a thread pool thread Console.WriteLine("In ComputeBoundOp: state={0}", state); Thread.Sleep(1000); // Simulates other work (1 second) // When this method returns, the thread goes back // to the pool and waits for another task } } ``` From the book [CLR Via C#](https://rads.stackoverflow.com/amzn/click/com/0735667454) by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 27. Compute-Bound Asynchronous Operations, highly recommended.
How do you add a timer to a C# console application
[ "", "c#", "console", "timer", "" ]
Consider the class below that represents a Broker: ``` public class Broker { public string Name = string.Empty; public int Weight = 0; public Broker(string n, int w) { this.Name = n; this.Weight = w; } } ``` I'd like to randomly select a Broker from an array, taking into account their weights. What do you think of the code below? ``` class Program { private static Random _rnd = new Random(); public static Broker GetBroker(List<Broker> brokers, int totalWeight) { // totalWeight is the sum of all brokers' weight int randomNumber = _rnd.Next(0, totalWeight); Broker selectedBroker = null; foreach (Broker broker in brokers) { if (randomNumber <= broker.Weight) { selectedBroker = broker; break; } randomNumber = randomNumber - broker.Weight; } return selectedBroker; } static void Main(string[] args) { List<Broker> brokers = new List<Broker>(); brokers.Add(new Broker("A", 10)); brokers.Add(new Broker("B", 20)); brokers.Add(new Broker("C", 20)); brokers.Add(new Broker("D", 10)); // total the weigth int totalWeight = 0; foreach (Broker broker in brokers) { totalWeight += broker.Weight; } while (true) { Dictionary<string, int> result = new Dictionary<string, int>(); Broker selectedBroker = null; for (int i = 0; i < 1000; i++) { selectedBroker = GetBroker(brokers, totalWeight); if (selectedBroker != null) { if (result.ContainsKey(selectedBroker.Name)) { result[selectedBroker.Name] = result[selectedBroker.Name] + 1; } else { result.Add(selectedBroker.Name, 1); } } } Console.WriteLine("A\t\t" + result["A"]); Console.WriteLine("B\t\t" + result["B"]); Console.WriteLine("C\t\t" + result["C"]); Console.WriteLine("D\t\t" + result["D"]); result.Clear(); Console.WriteLine(); Console.ReadLine(); } } } ``` I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight. Is there a more accurate algorithm? Thanks!
Your algorithm is nearly correct. However, the test should be `<` instead of `<=`: ``` if (randomNumber < broker.Weight) ``` This is because 0 is inclusive in the random number while `totalWeight` is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what you want. This accounts for broker A having more hits than broker D. Other than that, your algorithm is fine and in fact the canonical way of solving this problem.
How about something a little more generic, that can be used for any data type? ``` using System; using System.Linq; using System.Collections; using System.Collections.Generic; public static class IEnumerableExtensions { public static T RandomElementByWeight<T>(this IEnumerable<T> sequence, Func<T, float> weightSelector) { float totalWeight = sequence.Sum(weightSelector); // The weight we are after... float itemWeightIndex = (float)new Random().NextDouble() * totalWeight; float currentWeightIndex = 0; foreach(var item in from weightedItem in sequence select new { Value = weightedItem, Weight = weightSelector(weightedItem) }) { currentWeightIndex += item.Weight; // If we've hit or passed the weight we are after for this item then it's the one we want.... if(currentWeightIndex >= itemWeightIndex) return item.Value; } return default(T); } } ``` Simply call by ``` Dictionary<string, float> foo = new Dictionary<string, float>(); foo.Add("Item 25% 1", 0.5f); foo.Add("Item 25% 2", 0.5f); foo.Add("Item 50%", 1f); for(int i = 0; i < 10; i++) Console.WriteLine(this, "Item Chosen {0}", foo.RandomElementByWeight(e => e.Value)); ```
Random weighted choice
[ "", "c#", "algorithm", "random", "" ]
In PHP5, is the \_\_destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening?
The destructor will be called when the all references are freed, or when the script terminates. I assume this means when the script terminates properly. I would say that critical exceptions would not guarantee the destructor to be called. The [PHP documentation](https://www.php.net/__construct) is a little bit thin, but it does say that Exceptions in the destructor will cause issues.
It's also worth mentioning that, in the case of a subclass that has its own destructor, the parent destructor is **not** called automatically. You have to explicitly call **parent::\_\_destruct()** from the subclass **\_\_destruct()** method if the parent class does any required cleanup.
Can I trust PHP __destruct() method to be called?
[ "", "php", "garbage-collection", "" ]
I need a short code snippet to get a directory listing from an HTTP server. Thanks
A few important considerations before the code: 1. The HTTP Server has to be configured to allow directories listing for the directories you want; 2. Because directory listings are normal HTML pages there is no standard that defines the format of a directory listing; 3. Due to consideration **2** you are in the land where you have to put specific code for each server. My choice is to use regular expressions. This allows for rapid parsing and customization. You can get specific regular expressions pattern per site and that way you have a very modular approach. Use an external source for mapping URL to regular expression patterns if you plan to enhance the parsing module with new sites support without changing the source code. Example to print directory listing from <http://www.ibiblio.org/pub/> ``` namespace Example { using System; using System.Net; using System.IO; using System.Text.RegularExpressions; public class MyExample { public static string GetDirectoryListingRegexForUrl(string url) { if (url.Equals("http://www.ibiblio.org/pub/")) { return "<a href=\".*\">(?<name>.*)</a>"; } throw new NotSupportedException(); } public static void Main(String[] args) { string url = "http://www.ibiblio.org/pub/"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string html = reader.ReadToEnd(); Regex regex = new Regex(GetDirectoryListingRegexForUrl(url)); MatchCollection matches = regex.Matches(html); if (matches.Count > 0) { foreach (Match match in matches) { if (match.Success) { Console.WriteLine(match.Groups["name"]); } } } } } Console.ReadLine(); } } } ```
**Basic understanding:** Directory listings are just HTML pages generated by a web server. Each web server generates these HTML pages in its own way because there is no standard way for a web server to list these directories. The best way to get a directory listing, is to simply do an HTTP request to the URL you'd like the directory listing for and to try to parse and extract all of the links from the HTML returned to you. To parse the HTML links please try to use the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack). **Directory Browsing:** The web server you'd like to list directories from must have directory browsing turned on to get this HTML representation of the files in its directories. So you can only get the directory listing if the HTTP server wants you to be able to. **A quick example of the HTML Agility Pack:** ``` HtmlDocument doc = new HtmlDocument(); doc.Load(strURL); foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a@href") { HtmlAttribute att = link"href"; //do something with att.Value; } ``` **Cleaner alternative:** If it is possible in your situation, a cleaner method is to use an intended protocol for directory listings, like the File Transfer Protocol (FTP), SFTP (FTP like over SSH) or FTPS (FTP over SSL). **What if directory browsing is not turned on:** If the web server does not have directory browsing turned on, then there is no easy way to get the directory listing. The best you could do in this case is to start at a given URL, follow all HTML links on the same page, and try to build a virtual listing of directories yourself based on the relative paths of the resources on these HTML pages. This will not give you a complete listing of what files are actually on the web server though.
C# HttpWebRequest command to get directory listing
[ "", "c#", "http", "" ]
I have some hierarchical data - each entry has an id and a (nullable) parent entry id. I want to retrieve all entries in the tree under a given entry. This is in a SQL Server 2005 database. I am querying it with LINQ to SQL in C# 3.5. LINQ to SQL does not support [Common Table Expressions](http://msdn.microsoft.com/en-us/library/ms190766.aspx) directly. My choices are to assemble the data in code with several LINQ queries, or to make a view on the database that surfaces a CTE. Which option (or another option) do you think will perform better when data volumes get large? Is SQL Server 2008's [HierarchyId type](http://msdn.microsoft.com/en-us/library/bb677173.aspx) supported in Linq to SQL?
I would set up a view and an associated table-based function based on the CTE. My reasoning for this is that, while you could implement the logic on the application side, this would involve sending the intermediate data over the wire for computation in the application. Using the DBML designer, the view translates into a Table entity. You can then associate the function with the Table entity and invoke the method created on the DataContext to derive objects of the type defined by the view. Using the table-based function allows the query engine to take your parameters into account while constructing the result set rather than applying a condition on the result set defined by the view after the fact. ``` CREATE TABLE [dbo].[hierarchical_table]( [id] [int] IDENTITY(1,1) NOT NULL, [parent_id] [int] NULL, [data] [varchar](255) NOT NULL, CONSTRAINT [PK_hierarchical_table] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] CREATE VIEW [dbo].[vw_recursive_view] AS WITH hierarchy_cte(id, parent_id, data, lvl) AS (SELECT id, parent_id, data, 0 AS lvl FROM dbo.hierarchical_table WHERE (parent_id IS NULL) UNION ALL SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl FROM dbo.hierarchical_table AS t1 INNER JOIN hierarchy_cte AS h ON t1.parent_id = h.id) SELECT id, parent_id, data, lvl FROM hierarchy_cte AS result CREATE FUNCTION [dbo].[fn_tree_for_parent] ( @parent int ) RETURNS @result TABLE ( id int not null, parent_id int, data varchar(255) not null, lvl int not null ) AS BEGIN WITH hierarchy_cte(id, parent_id, data, lvl) AS (SELECT id, parent_id, data, 0 AS lvl FROM dbo.hierarchical_table WHERE (id = @parent OR (parent_id IS NULL AND @parent IS NULL)) UNION ALL SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl FROM dbo.hierarchical_table AS t1 INNER JOIN hierarchy_cte AS h ON t1.parent_id = h.id) INSERT INTO @result SELECT id, parent_id, data, lvl FROM hierarchy_cte AS result RETURN END ALTER TABLE [dbo].[hierarchical_table] WITH CHECK ADD CONSTRAINT [FK_hierarchical_table_hierarchical_table] FOREIGN KEY([parent_id]) REFERENCES [dbo].[hierarchical_table] ([id]) ALTER TABLE [dbo].[hierarchical_table] CHECK CONSTRAINT [FK_hierarchical_table_hierarchical_table] ``` To use it you would do something like -- assuming some reasonable naming scheme: ``` using (DataContext dc = new HierarchicalDataContext()) { HierarchicalTableEntity h = (from e in dc.HierarchicalTableEntities select e).First(); var query = dc.FnTreeForParent( h.ID ); foreach (HierarchicalTableViewEntity entity in query) { ...process the tree node... } } ```
This [option](http://www.scip.be/index.php?Page=ArticlesNET18) might also prove useful: **LINQ AsHierarchy() extension method** <http://www.scip.be/index.php?Page=ArticlesNET18>
Hierarchical data in Linq - options and performance
[ "", "sql", "linq", "sql-server-2005", "c#-3.0", "common-table-expression", "" ]
Well... simple question, right? But with no so simple answers. In firefox i use firebug console (profile) but... what to do in other browsers? Like Internet Explorer / Opera / Safari (on windows)
You may use JavaScript optimizers * <http://js-optimizer.sourceforge.net/> * <http://www.xtreeme.com/javascript-optimizer/>
This particular problem solves itself over time. ;-) Version 8 of the Internet Explorer (currently in beta 2) ships with a built-in JavaScript profiler. The next Safari version will probably also include one since its rendering engine, WebKit, now has one as part of its [Web Inspector](http://webkit.org/blog/148/web-inspector-update/).
How do you optimise your Javascript?
[ "", "javascript", "performance", "" ]
One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer?
I would start by reading this article: <http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/> Here is a speed test between the two: <http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx>
Round 1 - You can start a profiler trace and compare the execution times.
Why is parameterized SQL generated by NHibernate just as fast as a stored procedure?
[ "", "sql", "stored-procedures", "orm", "" ]
Is there an easy way of programmatically checking if a serial COM port is already open/being used? Normally I would use: ``` try { // open port } catch (Exception ex) { // handle the exception } ``` However, I would like to programatically check so I can attempt to use another COM port or some such.
I needed something similar some time ago, to search for a device. I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working. ``` var portNames = SerialPort.GetPortNames(); foreach(var port in portNames) { //Try for every portName and break on the first working } ```
This is how I did it: ``` [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); ``` then later on ``` int dwFlagsAndAttributes = 0x40000000; var portName = "COM5"; var isValid = SerialPort.GetPortNames().Any(x => string.Compare(x, portName, true) == 0); if (!isValid) throw new System.IO.IOException(string.Format("{0} port was not found", portName)); //Borrowed from Microsoft's Serial Port Open Method :) SafeFileHandle hFile = CreateFile(@"\\.\" + portName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero); if (hFile.IsInvalid) throw new System.IO.IOException(string.Format("{0} port is already open", portName)); hFile.Close(); using (var serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One)) { serialPort.Open(); } ```
C# check if a COM (Serial) port is already open
[ "", "c#", ".net", "serial-port", "" ]
I've been working on porting some of my Processing code over to regular Java in NetBeans. So far so well, most everything works great, except for when I go to use non-grayscale colors. I have a script that draws a spiral pattern, and should vary the colors in the spiral based on a modulus check. The script seems to hang, however, and I can't really explain why. If anyone has some experience with Processing and Java, and you could tell me where my mistake is, I'd really love to know. For the sake of peer-review, here's my little program: ``` package spirals; import processing.core.*; public class Main extends PApplet { float x, y; int i = 1, dia = 1; float angle = 0.0f, orbit = 0f; float speed = 0.05f; //color palette int gray = 0x0444444; int blue = 0x07cb5f7; int pink = 0x0f77cb5; int green = 0x0b5f77c; public Main(){} public static void main( String[] args ) { PApplet.main( new String[] { "spirals.Main" } ); } public void setup() { background( gray ); size( 400, 400 ); noStroke(); smooth(); } public void draw() { if( i % 11 == 0 ) fill( green ); else if( i % 13 == 0 ) fill( blue ); else if( i % 17 == 0 ) fill( pink ); else fill( gray ); orbit += 0.1f; //ever so slightly increase the orbit angle += speed % ( width * height ); float sinval = sin( angle ); float cosval = cos( angle ); //calculate the (x, y) to produce an orbit x = ( width / 2 ) + ( cosval * orbit ); y = ( height / 2 ) + ( sinval * orbit ); dia %= 11; //keep the diameter within bounds. ellipse( x, y, dia, dia ); dia++; i++; } } ```
Have you considered adding debugging statements (System.out.println) and looking at the Java Console? There may be a massive amount of output and definitive slowdown, but you can at least see what happens when nothing seems to happen. What I do think is a logic error is the filling if statement; every iteratation you decide the color of that iteration and fill with that color. Only iterations with i == 11, 13, or 17 get filled with a color. And the next iteration that color is overwritten by gray. I would think it tends to flicker, possibly to fast to see. Didn't you want something like ``` public class Main extends PApplet { ... int currentColor = gray; public Main(){} ... public void draw() { if( i % 11 == 0 ) currentColor = green; else if( i % 13 == 0 ) currentColor = blue; else if( i % 17 == 0 ) currentColor = pink; else { // Use current color } fill(currentColor); ... } ``` In that way you start with gray, go to green, blue, pink, green, blue, pink etc. If you also want to see gray at some point you'd have to add something like ``` else if ( i % 19 ) { currentColor = gray; } ``` Hope this helps.
Not sure if you have still an issue. You mention hanging. It is a shot in the dark, but I remember fry repeating that size() call must be the first instruction in setup(). So perhaps moving down the background() call might help. Couldn't hurt anyway.
Varying Colors in Processing
[ "", "java", "colors", "processing", "spiral", "" ]
Is there any way to use C# to build a container application where each tab is actually its own process like with Google chrome?
You can use the [SetParent](http://pinvoke.net/default.aspx/user32/SetParent.html) Win32 call to do this, but it's really fraught with problems. I had enough troubles getting it all to work nicely using windows from different AppDomains - there'd be even more difficulties with whole extra processes. Basically there's potentially a lot of communication required between the two processes - things like resizing can become quite painful, as well as what happens if the child app wants to quit etc. It's all doable, but I'd think very carefully before doing it. For a browser it makes a lot of sense (disclaimer: I work for Google) but for most other apps it's really not worth the effort. (Are the "tabs" you want to create actual .NET apps? If so, as I say this becomes significantly easier - and I can give you a big hint which is that each UI should run its own UI thread from within its own AppDomain. You get really weird effects if you don't do this!)
For those of you interested in the actual implementation of multi-process apps, I wrote an article about it on my website: **[Multi-process C# app like Google Chrome](http://wyday.com/blog/2010/multi-process-c-sharp-application-like-google-chrome-using-named-pipes/)**. I've included working C# code. It's been tested to work with .NET 2.0, .NET 3.0, and .NET 3.5. ## Named pipes: How processes talk to eachother Since your question specifically asked about Google Chrome you should know that [Chrome uses named pipes](http://dev.chromium.org/developers/design-documents/inter-process-communication) to communicate between processes. In the C# source code I mentioned above there are 2 files: PipeServer.cs & PipeClient.cs. These 2 files are thin wrappers of the Named Pipes Windows API. It's well tested because hundreds of thousands of people use our products. So stability & robustness were a requirement. ## How we use the multi-process design Now that you have all the pieces to the puzzle, let me tell you how we use Multi-process design in our app. Our product is a complete updater solution. That is, there's a program [that builds update patches](http://wyday.com/wybuild/) (not relevant to the discussion), a standalone updater program ([wyUpdate - also open source](http://wyday.com/wyupdate/)), and an [Automatic Updater control](http://wyday.com/wybuild/help/automatic-updates/) that our users put on their C# or VB.NET forms. We use named pipes to communicate between the standalone updater (wyUpdate) and the Automatic Updater control sitting on your program's form. wyUpdate reports progress to the Automatic Updater, and the Automatic Updater can tell wyUpdate to cancel progress, to start downloading, start extracting, etc. In fact, the exact named pipes code we use is included in the article I mentioned above: **[Multi-process C# app like Google Chrome](http://wyday.com/blog/2010/multi-process-c-sharp-application-like-google-chrome-using-named-pipes/)**. ## Why you shouldn't use the multi-process design As Jon Skeet mentioned above, you should have a specific need for the multi-process model. In our case we wanted to keep the updater completely separate from your program. That way if the updater somehow crashed, your program would remain unscathed. We also didn't want to duplicate our code in 2 places. That being said, even with our well-tested Named Pipes wrapper, inter-process communication is hard. So tread carefully.
Windows Forms application like Google Chrome with multiple processes
[ "", "c#", "winforms", "process", "" ]
I am building an application as a library, but to make sure I can get the output that I'd like, I switched it over to produce an exe. As soon as I did, I got several errors about unresolved external symbols. At first I thought that I didn't have a path set to the 3rd party library that I was referencing, so I added the folder to my path variable and even added it to my include, references, and source files, just to make sure I had all the paths. I still get the error: > error LNK2019: unresolved external > symbol "\_\_declspec(dllimport) public: > static void > \_\_cdecl xercesc\_2\_8::XMLPlatformUtils::Initialize(char > const \* const,char const \* > const,class xercesc\_2\_8::PanicHandler > \* const,class xercesc\_2\_8::MemoryManager \* > const,bool)" > (\_\_imp\_?Initialize@XMLPlatformUtils@xercesc\_2\_8@@SAXQBD0QAVPanicHandler@2@QAVMemoryManager@2@\_N@Z) > referenced in function "void \_\_cdecl > xsd::cxx::xml::initialize(void)" > (?initialize@xml@cxx@xsd@@YAXXZ) The reason that I'm asking it here is because in Visual Studio, when I built it as a library, I didn't get these errors, but as a dll and exe, I do. Anybody have any thoughts?
Building a library, the linker doesn't need to resolve imported symbols. That happens only when it starts linking object files and libraries together. That's why you only started seeing the error when building an executable. Indeed, in VC2008 (and 2005, if I remember well), use the project properties -> Linker -> Input -> Additional dependencies. The libraries you need are to be separated by spaces (odd, hey?) Good Luck!
You also need to specify that you wish to link against that library in particular. The link paths merely tell the linker where the data you need to find is, not what to look for. You will also need to specify that you are linking against the library in question (xerces?). Unfortunately, I don't know how to specify this in MSVC, but it's probably somewhere under 'Linker Options'.
Unresolved External Symbol Errors switching from build library to exe or dll
[ "", "c++", "visual-studio-2005", "linker", "" ]
So, I understand *that* the following doesn't work, but *why* doesn't it work? ``` interface Adapter<E> {} class Adaptulator<I> { <E, A extends I & Adapter<E>> void add(Class<E> extl, Class<A> intl) { addAdapterFactory(new AdapterFactory<E, A>(extl, intl)); } } ``` The `add()` method gives me a compile error, "Cannot specify any additional bound Adapter<E> when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick. Clearly you're just Not Allowed to use the type parameter `I` there, before the `&`, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that `I` isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer. Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one `add()` method, so it's not like there's any ambiguity... Can someone demonstrate the problem for me?
I'm also not sure why the restriction is there. You could try sending a friendly e-mail to the designers of Java 5 Generics (chiefly Gilad Bracha and Neal Gafter). My guess is that they wanted to support only an absolute minimum of [intersection types](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9) (which is what multiple bounds essentially are), to make the language no more complex than needed. An intersection cannot be used as a type annotation; a programmer can only express an intersection when it appears as the upper bound of a type variable. And why was this case even supported? The answer is that multiple bounds allow you to control the erasure, which allows to maintain binary compatibility when generifying existing classes. As explained in section 17.4 of the [book](http://java-generics-book.dev.java.net/) by Naftalin and Wadler, a `max` method would logically have the following signature: ``` public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll) ``` However, this erases to: ``` public static Comparable max(Collection coll) ``` Which does not match the historical signature of `max`, and causes old clients to break. With multiple bounds, only the left-most bound is considered for the erasure, so if `max` is given the following signature: ``` public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) ``` Then the erasure of its signature becomes: ``` public static Object max(Collection coll) ``` Which is equal to the signature of `max` before Generics. It seems plausible that the Java designers only cared about this simple case and restricted other (more advanced) uses of intersection types because they were just unsure of the complexity that it might bring. So the reason for this design decision does not need to be a possible safety problem (as the question suggests). More discussion on intersection types and restrictions of generics in an [upcoming OOPSLA paper](http://www.cs.rice.edu/~javaplt/papers/oopsla2008.pdf).
Two possible reasons for outlawing this: 1. Complexity. [JDK-4899305](https://bugs.openjdk.java.net/browse/JDK-4899305) suggests that a bound containing a type parameter plus additional parameterized types would allow for even more complicated mutually recursive types than already exist. In short, [Bruno's answer](https://stackoverflow.com/questions/197190/why-cant-i-use-a-type-argument-in-a-type-parameter-with-multiple-bounds#197391). 2. The possibility of specifying illegal types. Specifically, [extending a generic interface twice with different parameters](http://forums.sun.com/thread.jspa?messageID=2731375#2731541). I can't come up with a non-contrived example, but: ``` /** Contains a Comparator<String> that also implements the given type T. */ class StringComparatorHolder<T, C extends T & Comparator<String>> {   private final C comparator;   // ... }   void foo(StringComparatorHolder<Comparator<Integer>, ?> holder) { ... } ``` Now `holder.comparator` is a `Comparator<Integer>` and a `Comparator<String>`. It's not clear to me exactly how much trouble this would cause for the compiler, but it's clearly not good. Suppose in particular that `Comparator` had a method like this: ``` void sort(List<? extends T> list); ``` Our `Comparator<Integer>` / `Comparator<String>` hybrid now has two methods with the same erasure: ``` void sort(List<? extends Integer> list); void sort(List<? extends String> list); ``` It's for these kinds of reasons that you can't specify such a type directly: ``` <T extends Comparator<Integer> & Comparator<String>> void bar() { ... } ``` ``` java.util.Comparator cannot be inherited with different arguments: <java.lang.Integer> and <java.lang.String> ``` Since `<A extends I & Adapter<E>>` allows you to do the same thing indirectly, it's out, too.
Why can't I use a type argument in a type parameter with multiple bounds?
[ "", "java", "generics", "constraints", "" ]
I have one text input and one button (see below). How can I use JavaScript to **trigger the button's click event** when the `Enter` key is pressed inside the text box? There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I *only* want the `Enter` key to click this specific button if it is pressed from within this one text box, nothing else. ``` <input type="text" id="txtSearch" /> <input type="button" id="btnSearch" value="Search" onclick="doSomething();" /> ```
In jQuery, the following would work: ``` $("#id_of_textbox").keyup(function(event) { if (event.keyCode === 13) { $("#id_of_button").click(); } }); ``` ``` $("#pw").keyup(function(event) { if (event.keyCode === 13) { $("#myButton").click(); } }); $("#myButton").click(function() { alert("Button code executed."); }); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password:&nbsp;<input id="pw" type="password"><br> <button id="myButton">Submit</button> ``` Or in plain JavaScript, the following would work: ``` document.getElementById("id_of_textbox") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("id_of_button").click(); } }); ``` ``` document.getElementById("pw") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("myButton").click(); } }); function buttonCode() { alert("Button code executed."); } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password:&nbsp;<input id="pw" type="password"><br> <button id="myButton" onclick="buttonCode()">Submit</button> ```
Then just code it in! ``` <input type = "text" id = "txtSearch" onkeydown = "if (event.keyCode == 13) document.getElementById('btnSearch').click()" /> <input type = "button" id = "btnSearch" value = "Search" onclick = "doSomething();" /> ```
Trigger a button click with JavaScript on the Enter key in a text box
[ "", "javascript", "button", "onclick", "onkeydown", "onkeypress", "" ]
I want to have a class which implements an interface, which specifies the specific subclass as a parameter. ``` public abstract Task implements TaskStatus<Task> { TaskStatus<T> listener; protected complete() { // ugly, unsafe cast callback.complete((T) this); } } public interface TaskStatus<T> { public void complete(T task); } ``` But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one. So the best I've come up with is: ``` public abstract Task<T extends Task> implements TaskStatus<T> { } ``` You'd extend that by writing: ``` public class MyTask extends Task<MyTask> { } ``` But this would also be valid: ``` public class MyTask extends Task<SomeOtherTask> { } ``` And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I've somehow missed?
It is not clear what you are trying to do inside of `Task`. However, if you define the generic class `Task<T>` as follows: ``` class Task<T extends Task<T>> { ... } ``` The following two are possible: ``` class MyTask extends Task<MyTask> { ... } class YourTask extends Task<MyTask> { ... } ``` But the following is prohibited: ``` class MyTask extends Task<String> { ... } ``` The above definition of `Task` uses F-bounded polymorphism, a rather advanced feature. You can check the research paper "[F-bounded polymorphism for object-oriented programming](http://www.cs.utexas.edu/~wcook/papers/FBound89/CookFBound89.pdf)" for more information.
I suggest adding a getThis which should return this appropriately typed. Sure a subclas could misbehave, but that's always true. What you avoid is the cast and the possibility of a ClassCastException. ``` public abstract class Task<THIS extends Task<THIS>> { private TaskStatus<THIS> callback; public void setCallback(TaskStatus<THIS> callback) { this.callback = callback==null ? NullCallback.INSTANCE : callback; } protected void complete() { // ugly, unsafe cast callback.complete(getThis()); } protected abstract THIS getThis(); } public interface TaskStatus<T/* extends Task<T>*/> { void complete(T task); } public class MyTask extends Task<MyTask> { @Override protected MyTask getThis() { return this; } } ``` This problem often comes up with builders.
Generic type args which specificy the extending class?
[ "", "java", "generics", "design-patterns", "" ]
If you want a cryptographically strong random numbers in Java, you use `SecureRandom`. Unfortunately, `SecureRandom` can be very slow. If it uses `/dev/random` on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty? Has anyone used [Uncommon Maths](https://uncommons-maths.dev.java.net/) as a solution to this problem? Can anybody confirm that this performance problem has been solved in JDK 6?
If you want true random data, then unfortunately you have to wait for it. This includes the seed for a `SecureRandom` PRNG. Uncommon Maths can't gather true random data any faster than `SecureRandom`, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than `/dev/random` where that's available. If you want a PRNG, do something like this: ``` SecureRandom.getInstance("SHA1PRNG"); ``` What strings are supported depends on the `SecureRandom` SPI provider, but you can enumerate them using `Security.getProviders()` and `Provider.getService()`. Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy. The exception is that if you don't call `setSeed()` before getting data, then the PRNG will seed itself once the first time you call `next()` or `nextBytes()`. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.
You should be able to select the faster-but-slightly-less-secure /dev/urandom on Linux using: ``` -Djava.security.egd=file:/dev/urandom ``` However, this doesn't work with Java 5 and later ([Java Bug 6202721](https://bugs.openjdk.java.net/browse/JDK-6202721)). The suggested work-around is to use: ``` -Djava.security.egd=file:/dev/./urandom ``` (note the extra `/./`)
How to deal with a slow SecureRandom generator?
[ "", "java", "performance", "security", "random", "entropy", "" ]
Is it possible to connect PHP to a SQL Server Compact Edition database? What would be the best driver? --- I need it for a desktop application where SQL Server Express is too heavy.
Short Answer : **No.** Long Answer : To my knowledge, unlike PostgreSQL / MySQL / MS-SQL, there is no native driver to connect PHP to SQL Server Compact Edition. If you want to connect to it, your best bet is to use PHP ODBC connections to talk to a ODBC Driver connected to the SQL Compact server. But its pretty much a hack, and you'd be crazy to use this kind of thing for anything remotely important. If you are worried about SQL Server Express being too heavy, use MySQL with MyISAM tables. It's pretty fast and lightweight. [Emergent has a good checklist of things to configure / disable](http://emergent.urbanpug.com/?p=61) to make MySQL even faster and use less resources. Relevant links : [MSDN Post asking the same question](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2775563&SiteID=1) [Erik EJ's blog - SQL Compact with OLE DB](http://erikej.blogspot.com/2008/04/import-sql-compact-data-to-excel.html)
You could also consider SQLite: <http://www.devshed.com/c/a/PHP/Introduction-to-Using-SQLite-with-PHP-5/>
Is it possible to connect PHP to SQL Server Compact Edition?
[ "", "php", "sql-server", "sql-server-ce", "" ]
Let's say I have a multithreaded C++ program that handles requests in the form of a function call to `handleRequest(string key)`. Each call to `handleRequest` occurs in a separate thread, and there are an arbitrarily large number of possible values for `key`. I want the following behavior: * Simultaneous calls to `handleRequest(key)` are serialized when they have the same value for `key`. * Global serialization is minimized. The body of `handleRequest` might look like this: ``` void handleRequest(string key) { KeyLock lock(key); // Handle the request. } ``` **Question:** How would I implement `KeyLock` to get the required behavior? A naive implementation might start off like this: ``` KeyLock::KeyLock(string key) { global_lock->Lock(); internal_lock_ = global_key_map[key]; if (internal_lock_ == NULL) { internal_lock_ = new Lock(); global_key_map[key] = internal_lock_; } global_lock->Unlock(); internal_lock_->Lock(); } KeyLock::~KeyLock() { internal_lock_->Unlock(); // Remove internal_lock_ from global_key_map iff no other threads are waiting for it. } ``` ...but that requires a global lock at the beginning and end of each request, and the creation of a separate `Lock` object for each request. If contention is high between calls to `handleRequest`, that might not be a problem, but it could impose a lot of overhead if contention is low.
You could do something similar to what you have in your question, but instead of a single global\_key\_map have several (probably in an array or vector) - which one is used is determined by some simple hash function on the string. That way instead of a single global lock, you spread that out over several independent ones. This is a pattern that is often used in memory allocators (I don't know if the pattern has a name - it should). When a request comes in, something determines which pool the allocation will come from (usually the size of the request, but other parameters can factor in as well), then only that pool needs to be locked. If an allocation request comes in from another thread that will use a different pool, there's no lock contention.
**Raise granularity and lock entire key-ranges** This is a variation on Mike B's answer, where instead of having several fluid lock maps you have a single fixed array of locks that apply to key-ranges instead of single keys. Simplified example: create array of 256 locks at startup, then use first byte of key to determine index of lock to be acquired (i.e. all keys starting with 'k' will be guarded by `locks[107]`). To sustain optimal throughput you should analyze distribution of keys and contention rate. The benefits of this approach are zero dynamic allocations and simple cleanup; you also avoid two-step locking. The downside is potential contention peaks if key distribution becomes skewed over time.
How do I use an arbitrary string as a lock in C++?
[ "", "c++", "multithreading", "concurrency", "locking", "" ]
what is the best way to put a container class or a some other class inside a class as private or a public member? Requirements: 1.Vector< someclass> inside my class 2.Add and count of vector is needed interface
If the container's state is part of the class's invariant, then it should, if possible, be private. For example, if the container represents a three dimensional vector then part of the invariant might be that it always contains exactly 3 numbers. Exposing it as a public member would allow code external to the class to change the containers size, which in turn could cause problems for any routine which requires the container's size to be constant. Keeping the container private limits the places in your software where the container's size can be modified to the class's member functions.
Whether a member is declared Private or Public depends entirely on your application. Could you give some more detail? One important point to remember when declaring your member is that if you provide a "getter" to retrieve it, then you are no longer encapsulating that object. Instead, it can be good to write wrapper methods exposing only the functionality you wish to expose. For example, with a Vector member, you might write an AddItem and Clear method, if that's all the functionality you wish to expose.
Class design with vector as a private/public member?
[ "", "c++", "class-design", "encapsulation", "" ]
I have a link that I dynamically create which looks something like the following: ``` <a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a> ``` with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like: ``` <a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a> ``` Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether). Note: I am using ASP as my server side language.
Convert quote charaters to their HTML equivalents, `&quot;` etc. before you insert them into the HTML. There's a [long list](http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references) of HTML/XML character codes on wikipedia. There may well be a function to do this for you, depending on how you're dynamically generating the code: PHP has [htmlspecialchars](http://uk.php.net/htmlspecialchars), and though I'm not familiar with ASP etc, I'm sure there are similar routines.
You could just replace the ' with \'
Passing in a text to a javascript function that may have a single quote
[ "", "javascript", "" ]
I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way. Edit: My current solution, as suggested, is to use an anonymous Comparator: ``` File[] files = directory.listFiles(); Arrays.sort(files, new Comparator<File>(){ public int compare(File f1, File f2) { return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } }); ```
I think your solution is the only sensible way. The only way to get the list of files is to use [File.listFiles()](http://java.sun.com/javase/6/docs/api/java/io/File.html#listFiles()) and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a [Comparator](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) that uses [File.lastModified()](http://java.sun.com/javase/6/docs/api/java/io/File.html#lastModified()) and pass this, along with the array of files, to [Arrays.sort()](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#sort(T[],%20java.util.Comparator)).
**Elegant solution since Java 8:** ``` File[] files = directory.listFiles(); Arrays.sort(files, Comparator.comparingLong(File::lastModified)); ``` --- **Or, if you want it in descending order, just reverse it:** ``` File[] files = directory.listFiles(); Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed()); ```
Best way to list files in Java, sorted by Date Modified?
[ "", "java", "file", "sorting", "" ]
When using JDBC, I often come across constructs like ``` ResultSet rs = ps.executeQuery(); while (rs.next()) { int id = rs.getInt(1); // Some other actions } ``` I asked myself (and authors of code too) why not to use labels for retrieving column values: ``` int id = rs.getInt("CUSTOMER_ID"); ``` The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion. So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)?
You should use **string labels by default.** **Pros:** * Independence of column order * Better readability/maintainability **Cons:** * You have no control over the column names (access via stored procedures) **Which would you prefer?** ints? ``` int i = 1; customerId = resultSet.getInt(i++); customerName = resultSet.getString(i++); customerAddress = resultSet.getString(i++); ``` or Strings? ``` customerId = resultSet.getInt("customer_id"); customerName = resultSet.getString("customer_name"); customerAddress = resultSet.getString("customer_address"); ``` And what if there is a new column inserted at position 1? Which code would you prefer? Or if the order of the columns is changed, which code version would you need to change at all? That's why you should use **string labels by default.**
Warning: I'm going to get bombastic here, because this drives me crazy. 99%\* of the time, it's a ridiculous micro-optimization that people have some vague idea makes things 'better'. This completely ignores the fact that, unless you're in an extremely tight and busy loop over millions of SQL results *all the time*, which is hopefully rare, you'll never notice it. For everyone who's not doing that, the developer time cost of maintaing, updating, and fixing bugs in the column indexing are far greater than the incremental cost of hardware for your infinitesimally-worse-performing application. Don't code optimizations like this in. Code for the person maintaining it. Then observe, measure, analyse, and optimize. Observe again, measure again, analyse again, and optimize again. Optimization is pretty much the last step in development, not the first. \* Figure is made up.
ResultSet: Retrieving column values by index versus retrieving by label
[ "", "java", "optimization", "jdbc", "resultset", "" ]
I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration: ``` <defaultProxy useDefaultCredentials="false"> <proxy usesystemdefault="true" proxyaddress="<proxy address>" bypassonlocal="true" /> </defaultProxy> ``` I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this. Is there any way to do this? MSDN isn't helping me much..
Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though. Create an assembly called *SomeAssembly.dll* with this class : ``` namespace SomeNameSpace { public class MyProxy : IWebProxy { public ICredentials Credentials { get { return new NetworkCredential("user", "password"); } //or get { return new NetworkCredential("user", "password","domain"); } set { } } public Uri GetProxy(Uri destination) { return new Uri("http://my.proxy:8080"); } public bool IsBypassed(Uri host) { return false; } } } ``` Add this to your config file : ``` <defaultProxy enabled="true" useDefaultCredentials="false"> <module type = "SomeNameSpace.MyProxy, SomeAssembly" /> </defaultProxy> ``` This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application. This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own [ConfigurationSection](http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx), or add some information in the [AppSettings](http://msdn.microsoft.com/en-us/library/ms228154.aspx), which is far more easier.
While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config: ``` <system.net> <defaultProxy useDefaultCredentials="true"> <proxy proxyaddress="proxyAddress" usesystemdefault="True"/> </defaultProxy> </system.net> ``` The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server. If your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.
Is it possible to specify proxy credentials in your web.config?
[ "", "c#", "web-services", "proxy", "" ]
I'm using `Console.WriteLine()` from a very simple WPF test application, but when I execute the application from the command line, I'm seeing nothing being written to the console. Does anyone know what might be going on here? I can reproduce it by creating a WPF application in VS 2008, and simply adding `Console.WriteLine("text")` anywhere where it gets executed. Any ideas? All I need for right now is something as simple as `Console.WriteLine()`. I realize I could use log4net or somet other logging solution, but I really don't need that much functionality for this application. **Edit:** I should have remembered that `Console.WriteLine()` is for console applications. Oh well, no stupid questions, right? :-) I'll just use `System.Diagnostics.Trace.WriteLine()` and DebugView for now.
You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work). Here's a complete source code example, of how a ConsoleManager class might look like, and how it can be used to enable/disable the Console, independently of the project type. With the following class, you just need to write `ConsoleManager.Show()` somewhere before any call to `Console.Write`... ``` [SuppressUnmanagedCodeSecurity] public static class ConsoleManager { private const string Kernel32_DllName = "kernel32.dll"; [DllImport(Kernel32_DllName)] private static extern bool AllocConsole(); [DllImport(Kernel32_DllName)] private static extern bool FreeConsole(); [DllImport(Kernel32_DllName)] private static extern IntPtr GetConsoleWindow(); [DllImport(Kernel32_DllName)] private static extern int GetConsoleOutputCP(); public static bool HasConsole { get { return GetConsoleWindow() != IntPtr.Zero; } } /// <summary> /// Creates a new console instance if the process is not attached to a console already. /// </summary> public static void Show() { //#if DEBUG if (!HasConsole) { AllocConsole(); InvalidateOutAndError(); } //#endif } /// <summary> /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown. /// </summary> public static void Hide() { //#if DEBUG if (HasConsole) { SetOutAndErrorNull(); FreeConsole(); } //#endif } public static void Toggle() { if (HasConsole) { Hide(); } else { Show(); } } static void InvalidateOutAndError() { Type type = typeof(System.Console); System.Reflection.FieldInfo _out = type.GetField("_out", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.FieldInfo _error = type.GetField("_error", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); Debug.Assert(_out != null); Debug.Assert(_error != null); Debug.Assert(_InitializeStdOutError != null); _out.SetValue(null, null); _error.SetValue(null, null); _InitializeStdOutError.Invoke(null, new object[] { true }); } static void SetOutAndErrorNull() { Console.SetOut(TextWriter.Null); Console.SetError(TextWriter.Null); } } ```
You can use ``` Trace.WriteLine("text"); ``` This will output to the "Output" window in Visual Studio (when debugging). make sure to have the Diagnostics assembly included: ``` using System.Diagnostics; ```
No output to console from a WPF application?
[ "", "c#", ".net", "wpf", "console", "" ]
How can I make my compilation optimized for Windows 64 bit?
A managed project is automatically built according to the architecture selected => default C# project created on AMD64 will be AMD64, X86 on X86. The native one is always 32-bit by default. To explicitly set a platform: 1 open the solution explorer, select solution, right click->Configuration Manager. 2 go to 'Active Solution Platform', click New. 3 in the 'New Solution Platform' dialog that comes up select the new platform say Itanium. Set 'Copy Settings From' to 'Any CPU' which was the default setting in the 'Active Solution Platform'. 4 click OK. This is from [WebLog](http://blogs.msdn.com/deeptanshuv/archive/2006/04/11/573795.aspx)
You might also want to do a check at runtime, just to be sure: ``` using System; using System.Runtime.InteropServices; class SystemChecker { static bool Is64Bit { get { return Marshal.SizeOf(typeof(IntPtr)) == 8; } } } ```
C# for 64bit OS?
[ "", "c#", ".net", "64-bit", "" ]
Does BeautifulSoup work with Python 3? If not, how soon will there be a port? Will there be a port at all? Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)
About two months after I asked this question, a port has been released: <http://groups.google.com/group/beautifulsoup/browse_thread/thread/f24882cc17a0625e> It'll bet BS working, but that's about it. Not yet tried it though.
Beautiful Soup **4.x** [officially supports Python 3.](https://groups.google.com/forum/#!msg/beautifulsoup/VpNNflJ1rPI/sum07jmEwvgJ) ``` pip install beautifulsoup4 ```
BeautifulSoup's Python 3 compatibility
[ "", "python", "python-3.x", "beautifulsoup", "porting", "" ]
I have written something that uses the following includes: ``` #include <math.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <commctrl.h> ``` This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean installs of windows (VMs of course). It dies with the quite familiar: ``` --------------------------- C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe --------------------------- C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. --------------------------- OK --------------------------- ``` How can I make it run on clean installs? Which dll is it using which it can't find? My bet is on commctrl, but can someone enlighten me on why it's isn't with every windows? Further more, if anyone has tips on how to debug such a thing, as my CPP is already rusty, as it seems :) Edit - What worked for me is downloading the Redistributable for Visual Studio 2008. I don't think it's a good solution - downloading a 2MB file and an install to run a simple 11K tool. I think I'll change the code to use LoadLibrary to get the 2 or 3 functions I need from comctl32.dll. Thanks everyone :)
Use Dependency Walker. Download and install from <http://www.dependencywalker.com/> (just unzip to install). Then load up your executable. The tool will highlight which DLL is missing. Then you can find the redistributable pack which you need to ship with your executable. If you use VS2005, most cases will be covered by <http://www.microsoft.com/downloads/details.aspx?FamilyId=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en> which includes everything needed to run EXEs created with VS2005. Using depends.exe you may find a more lightweight solution, though.
**Common controls is a red herring**. Your problem is that the Visual C++ 8.0 runtime - I assume you're using Visual Studio 2005 - isn't installed. Either statically link to the C/C++ runtime library, or distribute the runtime DLL. You will have this problem with any C or C++ program that uses the DLL. You could get away with it in VS 6.0 as `msvcrt.dll` came with the OS from Windows 2000 up, and in VS.NET 2003 as `msvcr71.dll` came with .NET Framework 1.1. No more. Visual Studio 2005 and later use side-by-side assemblies to prevent DLL Hell, but that means you can't rely even on .NET 2.0 installing the exact version of C runtime that your program's built-in manifest uses. .NET 2.0's `mscorwks.dll` binds to version 8.0.50608.0 in its manifest; a VS-generated application binds to 8.0.50727.762 as of VS2005 SP1. My recollection is it used some pre-release version in the original (RTM) release of VS2005, which meant you had to deploy a Publisher Policy merge module if you were using the merge modules, to redirect the binding to the version actually in the released C run-time merge module. See also [Redistributing Visual C++ Files](http://msdn.microsoft.com/en-us/library/ms235299(VS.80).aspx) on MSDN.
Windows API commctrl.h using application doesn't work on machines without the Platform SDK
[ "", "c++", "windows", "dll", "" ]
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results: ``` >>> 6/3 2 >>> 6//3 2 ```
In Python 3.x, `5 / 2` will return `2.5` and `5 // 2` will return `2`. The former is floating point division, and the latter is ***floor division***, sometimes also called ***integer division***. In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a `from __future__ import division`, which causes Python 2.x to adopt the 3.x behavior. Regardless of the future import, `5.0 // 2` will return `2.0` since that's the floor division result of the operation. You can find a detailed description at *[PEP 238: Changing the Division Operator](https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator)*.
### Python 2.x Clarification: To clarify for the Python 2.x line, `/` is neither floor division nor true division. `/` is floor division when **both** args are `int`, but is true division when ***either*** of the args are `float`.
What is the difference between '/' and '//' when used for division?
[ "", "python", "math", "syntax", "operators", "floor-division", "" ]
How do I invoke a console application from my .NET application and capture all the output generated in the console? (Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)
This can be quite easily achieved using the [ProcessStartInfo.RedirectStandardOutput](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx) property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application. ``` Process compiler = new Process(); compiler.StartInfo.FileName = "csc.exe"; compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs"; compiler.StartInfo.UseShellExecute = false; compiler.StartInfo.RedirectStandardOutput = true; compiler.Start(); Console.WriteLine(compiler.StandardOutput.ReadToEnd()); compiler.WaitForExit(); ```
This is bit improvement over accepted answer from **@mdb**. Specifically, we also capture error output of the process. Additionally, we capture these outputs through events because `ReadToEnd()` doesn't work if you want to capture *both* error and regular output. It took me while to make this work because it actually also requires `BeginxxxReadLine()` calls after `Start()`. Asynchronous way: ``` using System.Diagnostics; Process process = new Process(); void LaunchProcess() { process.EnableRaisingEvents = true; process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived); process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived); process.Exited += new System.EventHandler(process_Exited); process.StartInfo.FileName = "some.exe"; process.StartInfo.Arguments = "param1 param2"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); //below line is optional if we want a blocking call //process.WaitForExit(); } void process_Exited(object sender, EventArgs e) { Console.WriteLine(string.Format("process exited with code {0}\n", process.ExitCode.ToString())); } void process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data + "\n"); } void process_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data + "\n"); } ```
Capturing console output from a .NET application (C#)
[ "", "c#", ".net", "debugging", "console", "" ]
He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings `{'id': id, 'url': url}`. Some `id`s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function: ``` def unique_mapping(map): d = {} for res in map: d[res['id']] = res['url'] return [{'id': id, 'url': d[id]} for id in d] ``` I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?
Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones: ``` def unique_mapping(mappings): return dict((m['id'], m) for m in mappings).values() ``` Although this came out as a one-liner, I still think it's quite readable. There are two things you have to keep in mind when using your original solution and mine: * the items will not always be returned in the same order they were originally * the later entry will overwrite previous entries with the same id If you don't mind, then I suggest the solution above. In other case, this function preserves order and treats first-encountered ids with priority: ``` def unique_mapping(mappings): addedIds = set() for m in mappings: mId = m['id'] if mId not in addedIds: addedIds.add(mId) yield m ``` You might need to call it with `list(unique_mappings(mappings))` if you need a list and not a generator.
There are a couple of things you could improve. * You're performing two loops, one over the original dict, and then again over the result dict. You could build up your results in one step instead. * You could change to use a generator, to avoid constructing the whole list up-front. (Use list(unique\_mapping(items)) to convert to a full list if you need it) * There's no need to store the value when just checking for duplicates, you can use a set instead. * You're recreating a dictionary for each element, rather than returning the original. This may actually be needed (eg. you're modifying them, and don't want to touch the original), but if not, its more efficient to use the dictionaries already created. Here's an implementation: ``` def unique_mapping(items): s = set() for res in items: if res['id'] not in s: yield res s.add(res['id']) ```
Extracting unique items from a list of mappings
[ "", "python", "unique", "duplicate-data", "" ]
How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?
``` import socket socket.gethostbyname(socket.gethostname()) ``` This won't work always (returns `127.0.0.1` on machines having the hostname in `/etc/hosts` as `127.0.0.1`), a paliative would be what gimel shows, use `socket.getfqdn()` instead. Of course your machine needs a resolvable hostname.
I just found this but it seems a bit hackish, however they say tried it on \*nix and I did on windows and it worked. ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(s.getsockname()[0]) s.close() ``` This assumes you have an internet access, and that there is no local proxy.
Finding local IP addresses using Python's stdlib
[ "", "python", "networking", "ip-address", "" ]
I am using sql server 2005. I just want to know is there something we can get the week number for the particular month. Example `Date = '2008-10-16'` Is there something we can have `SELECT WEEK(Date)`. Or any better suggestion.
``` select (datepart(dd,'2008-10-08')-1) / 7 + 1 ```
``` SELECT DATEPART( week, '2008-10-16') ```
Week() function in sql script
[ "", "sql", "sql-server", "sql-server-2005", "" ]
1. What are the patterns you use to determine the frequent queries? 2. How do you select the optimization factors? 3. What are the types of changes one can make?
This is a nice question, if rather broad (and none the worse for that). If I understand you, then you're asking how to attack the problem of optimisation starting from scratch. The first question to ask is: "*is there a performance problem?*" If there is no problem, then you're done. This is often the case. Nice. On the other hand... ### Determine Frequent Queries **Logging** will get you your frequent queries. If you're using some kind of data access layer, then it might be simple to add code to log all queries. It is also a good idea to log when the query was executed and how long each query takes. This can give you an idea of where the problems are. Also, **ask the users** which bits annoy them. If a slow response doesn't annoy the user, then it doesn't matter. ### Select the optimization factors? (I may be misunderstanding this part of the question) You're looking for any patterns in the queries / response times. These will typically be queries over large tables or queries which join many tables in a single query. ... but if you log response times, you can be guided by those. ### Types of changes one can make? You're specifically asking about optimising tables. Here are some of the things you can look for: * **Denormalisation**. This brings several tables together into one wider table, so in stead of your query joining several tables together, you can just read one table. This is a very common and powerful technique. NB. I advise keeping the original normalised tables and building the denormalised table in addition - this way, you're not throwing anything away. How you keep it up to date is another question. You might use triggers on the underlying tables, or run a refresh process periodically. * **Normalisation**. This is not often considered to be an optimisation process, but it is in 2 cases: + updates. Normalisation makes updates much faster because each update is the smallest it can be (you are updating the smallest - in terms of columns and rows - possible table. This is almost the very definition of normalisation. + Querying a denormalised table to get information which exists on a much smaller (fewer rows) table may be causing a problem. In this case, store the normalised table as well as the denormalised one (see above). * **Horizontal partitionning**. This means making tables smaller by putting some rows in another, identical table. A common use case is to have all of this month's rows in table *ThisMonthSales*, and all older rows in table *OldSales*, where both tables have an identical schema. If most queries are for recent data, this strategy can mean that 99% of all queries are only looking at 1% of the data - a huge performance win. * **Vertical partitionning**. This is Chopping fields off a table and putting them in a new table which is joinned back to the main table by the primary key. This can be useful for very wide tables (e.g. with dozens of fields), and may possibly help if tables are sparsely populated. * **Indeces**. I'm not sure if your quesion covers these, but there are plenty of other answers on SO concerning the use of indeces. A good way to find a case for an index is: find a slow query. look at the query plan and find a table scan. Index fields on that table so as to remove the table scan. I can write more on this if required - leave a comment. You might also like [my post on this](https://stackoverflow.com/questions/18783/sql-what-are-your-favorite-performance-tricks#103176).
Your question is a bit vague. Which DB platform? If we are talking about SQL Server: 1. Use the Dynamic Management Views. Use SQL Profiler. Install the SP2 and the performance dashboard reports. 2. After determining the most costly queries (i.e. number of times run x cost one one query), examine their execution plans, and look at the sizes of the tables involved, and whether they are predominately Read or Write, or a mixture of both. 3. If the system is under your full control (apps. and DB) you can often re-write queries that are badly formed (quite a common occurrance), such as deep correlated sub-queries which can often be re-written as derived table joins with a little thought. Otherwise, you options are to create covering non-clustered indexes and ensure that statistics are kept up to date.
How do you optimize tables for specific queries?
[ "", "sql", "database-design", "" ]
``` Pattern pattern = Pattern.compile("^[a-z]+$"); String string = "abc-def"; assertTrue( pattern.matcher(string).matches() ); // obviously fails ``` Is it possible to have the character class match a "-" ?
Don't put the minus sign between characters. ``` "[a-z-]" ```
Escape the minus sign ``` [a-z\\-] ```
In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign?
[ "", "java", "regex", "" ]
Here is an example of polymorphism from <http://www.cplusplus.com/doc/tutorial/polymorphism.html> (edited for readability): ``` // abstract base class #include <iostream> using namespace std; class Polygon { protected: int width; int height; public: void set_values(int a, int b) { width = a; height = b; } virtual int area(void) =0; }; class Rectangle: public Polygon { public: int area(void) { return width * height; } }; class Triangle: public Polygon { public: int area(void) { return width * height / 2; } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << endl; // outputs 20 cout << ppoly2->area() << endl; // outputs 10 return 0; } ``` My question is how does the compiler know that ppoly1 is a Rectangle and that ppoly2 is a Triangle, so that it can call the correct area() function? It could find that out by looking at the "Polygon \* ppoly1 = ▭" line and knowing that rect is a Rectangle, but that wouldn't work in all cases, would it? What if you did something like this? ``` cout << ((Polygon *)0x12345678)->area() << endl; ``` Assuming that you're allowed to access that random area of memory. I would test this out but I can't on the computer I'm on at the moment. (I hope I'm not missing something obvious...)
Each object (that belongs to a class with at least one virtual function) has a pointer, called a `vptr`. It points to the `vtbl` of its actual class (which each class with virtual functions has at least one of; possibly more than one for some multiple-inheritance scenarios). The `vtbl` contains a bunch of pointers, one for each virtual function. So at runtime, the code just uses the object's `vptr` to locate the `vtbl`, and from there the address of the actual overridden function. In your specific case, `Polygon`, `Rectangle`, and `Triangle` each has a `vtbl`, each with one entry pointing to its relevant `area` method. Your `ppoly1` will have a `vptr` pointing to `Rectangle`'s `vtbl`, and `ppoly2` similarly with `Triangle`'s `vtbl`. Hope this helps!
[Chris Jester-Young](https://stackoverflow.com/questions/203126/how-does-the-c-compiler-know-which-implementation-of-a-virtual-function-to-call#203136) gives the basic answer to this question. [Wikipedia](http://en.wikipedia.org/wiki/Virtual_table) has a more in depth treatment. If you want to know the full details for how this type of thing works (and for all type of inheritance, including multiple and virtual inheritance), one of the best resources is Stan Lippman's "[Inside the C++ Object Model](https://rads.stackoverflow.com/amzn/click/com/0201834545)".
How does the C++ compiler know which implementation of a virtual function to call?
[ "", "c++", "oop", "polymorphism", "" ]
I need to send email through an (external) SMTP server from Java however this server will only accept CRAM-MD5 authentication, which is not supported by JavaMail. What would be a good way to get these emails to send? (It must be in Java.)
Here is [thread](http://lists.gnu.org/archive/html/classpathx-javamail/2010-10/msg00004.html) which says that you need to add the following property: ``` props.put("mail.smtp.auth.mechanisms", "CRAM-MD5") ``` Also in Geronimo implementation there is [CramMD5Authenticator](http://geronimo.apache.org/maven/javamail/1.7/geronimo-javamail_1.4_provider/apidocs/org/apache/geronimo/javamail/authentication/CramMD5Authenticator.html) Hope it helps to resolve this old question.
Since Java Mail 1.4.4, CRAM-MD5 is supported for use with smtp. Just set this parameter to your properties and it will work: `props.put("mail.smtp.sasl.enable", "true");`
SMTP with CRAM-MD5 in Java
[ "", "java", "smtp", "sasl", "" ]
I have a new app I'll be working on where I have to generate a Word document that contains tables, graphs, a table of contents and text. What's a good API to use for this? How sure are you that it supports graphs, ToCs, and tables? What are some hidden gotcha's in using them? Some clarifications: * I can't output a PDF, they want a Word doc. * They're using MS Word 2003 (or 2007), not OpenOffice * Application is running on \*nix app-server It'd be nice if I could start with a template doc and just fill in some spaces with tables, graphs, etc. Edit: Several good answers below, each with their own faults as far as my current situation. Hard to pick a "final answer" from them. Think I'll leave it open, and hope for better solutions to be created. Edit: The OpenOffice UNO project does seem to be closest to what I asked for. While POI is certainly more mainstream, it's too immature for what I want.
In 2007 my project successfully used OpenOffice.org's [Universal Network Objects](https://www.openoffice.org/udk/common/man/uno.html) (UNO) interface to programmatically generate MS-Word compatible documents (\*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework). OpenOffice UNO also lets you build MS-Office-compatible charts, spreadsheets, presentations, etc. We were able to dynamically build sophisticated Word documents, including charts and tables. We simplified the process by using template MS-Word documents with bookmark inserts into which the software inserted content, however, you can build documents completely from scratch. The goal was to have the software generate report documents that could be shared and further tweaked by end-users before converting them to PDF for final delivery and archival. You can optionally produce documents in OpenOffice formats if you want users to use OpenOffice instead of MS-Office. In our case the users want to use MS-Office tools. UNO is included within the OpenOffice suite. We simply linked our Java app to UNO-related libraries within the suite. An [OpenOffice Software Development Kit](http://www.openoffice.org/download/sdk/) (SDK) is available containing example applications and the UNO Developer's Guide. I have not investigated whether the latest OpenOffice UNO can generate MS-Office 2007 Open XML document formats. The important things about OpenOffice UNO are: 1. It is freeware 2. It supports multiple languages (e.g. Visual Basic, Java, C++, and others). 3. It is platform-independent (Windows, Linux, Unix, etc.). Here are some useful web sites: * [Open Office home](http://www.openoffice.org) * [Open Office UNO Developer's Guide](http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide) * [OpenOffice Developer's Forum](http://www.staroffice.org/developers.html) (especially the "Macros and API" and "Code Snippets" forums).
I think [Apache POI](http://poi.apache.org/) can do the job. A possible problem depending on the usage your aiming to may be caused by the fact that HWPF is still in early development. > [HWPF](http://poi.apache.org/hwpf/index.html) > is the set of APIs for reading and > writing Microsoft Word 97(-XP) > documents using (only) Java.
Is there a Java API that can create rich Word documents?
[ "", "java", "ms-word", "docx", "doc", "" ]
Is there a better way to debug JavaScript than MS Script Editor? I am searching for something like Firebug. Firebug Lite doesn't offer this functionality, though. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Use Visual Studio 2008. The Web Development Helper from Nikhilk is useful as is the Internet Explorer Developer Toolbar (<http://www.microsoft.com/en-us/download/details.aspx?id=18359>). They are not as good as FireBug though :-(
Though not strictly debuggers, these are useful tools for your arsenal * <http://www.debugbar.com/> * <http://projects.nikhilk.net/WebDevHelper/>
How to debug JavaScript in IE?
[ "", "javascript", "internet-explorer", "" ]
I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the [docs](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx), 'd' should produce the day (1-31). ``` string.Format("{0:d }", DateTime.Today); string.Format("{0:d}", DateTime.Today); ``` UPDATE:Adding % is indeed the trick. Appropriate docs [here](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers).
See [here](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx) > d, %d > > The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns. Otherwise d is interpreted as: > d - 'ShortDatePattern' PS. For messing around with format strings, using [LinqPad](http://www.linqpad.net/) is invaluable.
From the MSDN documentation for "Custom Date and Time Format Strings": > Any string that is not a standard date > and time format string is interpreted > as a custom date and time format > string. {0:d} is interpreted as a standard data and time format string. From "Standard Date and Time Format Strings", the "d" format specifier: > Represents a custom date and time > format string defined by the current > ShortDatePattern property. With the space, {0:d } doesn't match any standard date and time format string, and is interpreted as a custom data and time format string. From "Custom Date and Time Format Strings", the "d" format specifier: > Represents the day of the month as a > number from 1 through 31.
Why do these two date formats differ?
[ "", "c#", ".net", "datetime", "formatting", "" ]
Say I have my sources in my src/ tree (and possibly in my test/ tree). Say I would like to compile only *part* of that tree. The reasons why I might want to do that are various. Just as an example, I might want to create the smallest possible jar (without including certain classes), or I might want the fastest compile time for what I am compiling. I absolutely want to compile all the dependencies, though! This can be easily achieved from the command line with: ``` javac -d build/ -cp whatever -sourcepath src src/path/to/MyClass.java ``` Now, how can you do that with ant? The javac ant [task compiles everything](http://ant.apache.org/manual/Tasks/javac.html): > The source and destination directory > will be recursively scanned for Java > source files to compile. One can use the `excludes` and `includes` parameters, but they are problematic for this purpose. In fact, it seems that one has to explicitly setup all the `includes` (not automatic dependency lookup), and **even worst** that [excludes has priority on includes](http://ant.apache.org/manual/dirtasks.html#patternset): > When both inclusion and exclusion are > used, only files/directories that > match at least one of the include > patterns and don't match *any* of the > exclude patterns are used. Thus, you cannot use ``` <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" excludes="**/*.java" includes="src/path/to/MyClass.java" /> ``` Because it will not compile anything :-( Is there any way of achieving that simple command line `javac` with ant? --- EDITED: Thank you for your answer, Sadie, I'm accepting it, because it does work in the way I was wondering in this question. But I have a couple of comments (too long to be in the comment field of your answer): 1) I did read the documentation (see links above), but it's unclear that with just `includes` you are actually also excluding everything else 2) When you just `includes` ant logs something like ``` [javac] Compiling 1 source file to /my/path/to/build ``` even if the dependencies make it compiling (much) more than just one source file.
Why are you excluding as well as including? If you have at least one include, then files are only compiled if they're explicitly included. So this should work: ``` <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includes="src/path/to/MyClass.java" /> ``` Or more flexibly: ``` <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"> <include name="src/path/to/MyClass.java"/> <include name="src/path/to/AnotherClass.java"/> </javac> ``` To include only certain packages or classes in a jar, use a fileset attribute ``` <jar jarfile="${outlib}/something.jar"> <fileset dir="${build.dir}"> <include name='src/path/to/classes' /> </fileset> </jar> ``` Again, you can use multiple includes to combine separate packages. Experiment with includes and [read the documentation](http://ant.apache.org/manual/) and you're sure to find the answer you need.
Old question, but I was struggling with the same problem and found a a more elegant solution. So here it is, for future reference: According to the ant docs the `<javac>` element is an implicit `<fileset>` and as such can take [Selectors](https://ant.apache.org/manual/Types/selectors.html "Selectors") like `<filename name="**/MyClass.java"/>`, so this would only compile MyClass.java: ``` <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"> <filename name="**/path/to/MyClass.java"/> </javac> ```
compiling only part of the source tree with ant
[ "", "java", "ant", "jar", "javac", "" ]
I'm trying to access the Facebook API Admin.getMetrics method via jQuery. I'm correctly composing the request url on the server side (in order to keep my app secret secret). I'm then sending the url over to the browser to be request using `jQuery.getJSON()`. Facebook requires that I send a copy of all of my request params hashed with my application secret along with the request in order to verify my authenticity. The problem is that jQuery wants to generate the name of the callback function itself in order to match the name it gives to the anonymous function you pass in to be called when the data returns. Therefore, the name of the function is not available until `jQuery.getJSON()` executes and Facebook considers my request to be inauthentic due to a mismatched signature (the signature I send along does not include the correct callback param because that was not generated until `jQuery.getJSON()` ran). The only way I can think of out of this problem is to somehow specify the name of my function to `jQuery.getJSON()` instead of allowing it to remain anonymous. But I cannot find any option for doing so in the jQuery AP.
The use of `jQuery.getScript` turned out to be close to -- but not quite -- the answer. Using getScript eliminates jQuery's need to add the dynamically named anonymous function to the request params (though it will still do that if you go ahead and pass it an anonymous function as in the above code). However, the default in `jQuery.getScript`, as in all the other calls in jQuery's Ajax library, is to append a further additional argument `_=12344567` (where 1234567 is really a time stamp). jQuery does this to prevent the browser from caching the response. However, this additional breaks my signing of the request just like the auto-named callback function. With some help on #jquery, I learned that the only way to get jQuery not to mess at all with your params is to make the request using the base `jQuery.Ajax` method with the following arguments: ``` jQuery.ajax({ url: fbookUrl, dataType: "script", type: "GET", cache: true, callback: null, data: null }); ``` (where `fbookUrl` is the Facebook API url I'm trying to request with its full params including the signature and the `callback=myFunction`). The `dataType: "script"` arg specifies that the resulting JSONP should be stuffed into a script tag on the page for execution, `cache: true` tells jQuery to allow the browser to cache the response, i.e. to skip the addition of the time stamp parameter.
The only thing that did the work for me were the following settings `jQuery.ajax({ url: fbookUrl, dataType: "jsonp", type: "GET", cache: true, jsonp: false, jsonpCallback: "MyFunctionName" //insert here your function name });`
using a named function as the callback for $.getJSON in jQuery to satisfy Facebook request signing demands
[ "", "javascript", "jquery", "json", "facebook", "jsonp", "" ]
I have a bit of code where I am looping through all the select boxes on a page and binding a `.hover` event to them to do a bit of twiddling with their width on `mouse on/off`. This happens on page ready and works just fine. The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound. I have found this plugin ([jQuery Live Query Plugin](http://brandonaaron.net/docs/livequery/#getting-started)), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
**As of jQuery 1.7** you should use [`jQuery.fn.on`](https://api.jquery.com/on/#on-events-selector-data-handler) with the selector parameter filled: ``` $(staticAncestors).on(eventName, dynamicChild, function() {}); ``` *Explanation:* This is called event delegation and works as followed. The event is attached to a static parent (`staticAncestors`) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (`dynamicChild`). When there is a match then your custom handler function is executed. --- **Prior to this**, the recommended approach was to use [`live()`](http://api.jquery.com/live): ``` $(selector).live( eventName, function(){} ); ``` However, `live()` was deprecated in 1.7 in favour of `on()`, and completely removed in 1.9. The `live()` signature: ``` $(selector).live( eventName, function(){} ); ``` ... can be replaced with the following [`on()`](http://api.jquery.com/on/) signature: ``` $(document).on( eventName, selector, function(){} ); ``` --- For example, if your page was dynamically creating elements with the class name `dosomething` you would bind the event to **a parent which already exists** (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is `document`. Though bear in mind [`document` may not be the most efficient option](https://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document). ``` $(document).on('mouseover mouseout', '.dosomething', function(){ // what you want to happen when mouseover and mouseout // occurs on elements that match '.dosomething' }); ``` Any parent that exists at the time the event is bound is fine. For example ``` $('.buttons').on('click', 'button', function(){ // do something here }); ``` would apply to ``` <div class="buttons"> <!-- <button>s that are generated dynamically and added here --> </div> ```
There is a good explanation in the documentation of [`jQuery.fn.on`](http://api.jquery.com/on/). In short: > Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to `.on()`. Thus in the following example `#dataTable tbody tr` must exist before the code is generated. ``` $("#dataTable tbody tr").on("click", function(event){ console.log($(this).text()); }); ``` If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next. **Delegated events** have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it: ``` $("#dataTable tbody").on("click", "tr", function(event){ console.log($(this).text()); }); ``` In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its `tbody`, the first code example attaches a handler to 1,000 elements. A delegated-events approach (the second code example) attaches an event handler to only one element, the `tbody`, and the event only needs to bubble up one level (from the clicked `tr` to `tbody`). **Note:** Delegated events do not work for [SVG](http://en.wikipedia.org/wiki/Scalable_Vector_Graphics).
Event binding on dynamically created elements?
[ "", "javascript", "jquery", "events", "unobtrusive-javascript", "" ]
I tried but I guess Message Box only works with win forms. What is the best alternative to use in web forms?
You can use `confirm` for yes/no questions and `alert` for "OK" messages in JavaScript. The other alternative is to use JavaScript to pop up a new window that looks and acts like a message box. Modality in this case varied by browser. In Internet Explorer, the method ``` window.showModalDialog(url,name,params) ``` will display a modal dialog. The Mozilla approach is to still use ``` window.open(url,name,params) ``` but add `modal=yes` to the `params` list.
``` result = confirm('Yes or no question here.') ```
Is it possible to get Message Box in web forms?
[ "", "javascript", "user-interface", "dialog", "" ]
I've ran some "ALTER" scripts on the database [SQL Server Server 2005], and overwrote some sprocs. Is there any way to undo changes and get my old sprocs back? Is there a way to get the scripts that were executed out of the .LDf file? That way i can re-run my initial "create" script for my sprocs. I don't have a backup file with old sprocs. p.s. i backed the DB up as per [@Gulzar's](https://stackoverflow.com/users/4337/gulzar) deleted answer, and looks like I'm "hosed". @Pittsburgh DBA: thanx for the solution, but it doesn't seem to work after the backup. **MORAL: Wait for 10 minutes before trying the suggested answers out** --- **Update from Gulzar**: What I meant was a file backup before trying anything (to be safe). Not a SQL Server backup.
FIRST: DO NOT TAKE ANY BACKUPS JUST YET. There are several tools on the market to do this sort of thing. You might try this one: [ApexSQL Log](http://www.apexsql.com/sql_tools_log.asp)
In case anybody else has the same problem - Were you doing transaction log backups every X minutes? If so, you can use Quest LiteSpeed's log reader or Quest Toad for SQL Server's log reader to read the log file backups. It gives undo/redo scripts too for any transaction in the log backups or the ldf.
Undo changes to SQL Server 2005 database
[ "", "sql", "sql-server", "sql-server-2005", "recovery", "" ]
How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net?
There are two possible solutions. 1. Call the Win32 function GetDiskFreeSpaceEx. Here is a sample program: ``` internal static class Win32 { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes); } class Program { static void Main(string[] args) { long freeBytesForUser; long totalBytes; long freeBytes; if (Win32.GetDiskFreeSpaceEx(@"\\prime\cargohold", out freeBytesForUser, out totalBytes, out freeBytes)) { Console.WriteLine(freeBytesForUser); Console.WriteLine(totalBytes); Console.WriteLine(freeBytes); } } } ``` 2. Use the system management interface. There is another answer in this post which describes this. This method is really designed for use in scripting languages such as PowerShell. It performs a lot of fluff just to get the right object. Ultimately, I suspect, this method boils down to calling GetDiskFreeSpaceEx. Anybody doing any serious Windows development in C# will probably end up calling many Win32 functions. The .NET framework just doesn't cover 100% of the Win32 API. Any large program will quickly uncover gaps in the .NET libraries that are only available through the Win32 API. I would get hold of one of the Win32 wrappers for .NET and include this in your project. This will give you instant access to just about every Win32 API.
Use WMI ``` using System.Management; // Get all the network drives (drivetype=4) SelectQuery query = new SelectQuery("select Name, VolumeName, FreeSpace from win32_logicaldisk where drivetype=4"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject drive in searcher.Get()) { string Name = (string)drive["Name"]; string VolumeName = (string)drive["VolumeName"]; UInt64 freeSpace = (UInt64)drive["FreeSpace"]; } ``` based on (stolen from) <http://www.dreamincode.net/code/snippet1576.htm>
How can I determine if a remote drive has enough space to write a file using C#?
[ "", "c#", ".net", "networking", "filesystems", "" ]
Here's a common code pattern I have to work with: ``` class foo { public: void InitMap(); void InvokeMethodsInMap(); static void abcMethod(); static void defMethod(); private: typedef std::map<const char*, pMethod> TMyMap; TMyMap m_MyMap; } void foo::InitMap() { m_MyMap["abc"] = &foo::abcMethod; m_MyMap["def"] = &foo::defMethod; } void foo::InvokeMethodsInMap() { for (TMyMap::const_iterator it = m_MyMap.begin(); it != m_MyMap.end(); it++) { (*it->second)(it->first); } } ``` However, I have found that the *order* that the map is processed in (within the for loop) can differ based upon whether the build configuration is Release or Debug. It seems that the compiler optimisation that occurs in Release builds affects this order. I thought that by using `begin()` in the loop above, and incrementing the iterator after each method call, it would process the map in order of initialisation. However, I also remember reading that a map is implemented as a hash table, and order cannot be guaranteed. This is particularly annoying, as most of the unit tests are run on a Debug build, and often strange order dependency bugs aren't found until the external QA team start testing (because they use a Release build). Can anyone explain this strange behaviour?
Don't use `const char*` as the key for maps. That means the map is ordered by the addresses of the strings, not the contents of the strings. Use a `std::string` as the key type, instead. `std::map` is not a hash table, it's usually implemented as a red-black tree, and elements are guaranteed to be ordered by some criteria (by default, `<` comparison between keys).
The definition of map is: **map<Key, Data, Compare, Alloc>** Where the last two template parameters default too: Compare: less<Key> Alloc:        allocator<value\_type> When inserting new values into a map. The new value (valueToInsert) is compared against the old values in order (**N.B.** This is not sequential search, the standard guarantees a max insert complexity of O(log(N)) ) until Compare(value,ValueToInsert) returns true. Because you are using ***'const char\*'*** as the key. The Compare Object is using ***less<const char\*>*** this class just does a < on the two values. So in effect you are comparing the pointer values (not the string) therefore the order is random (as you don't know where the compiler will put strings. There are two possible solutions: * Change the type of the key so that it compares the string values. * Define another Compare Type that does what you need. Personally I (like Chris) would just use a std::string because < operator used on strings returns a comparison based on the string content. But for arguments sake we can just define a Compare type. ``` struct StringLess { bool operator()(const char* const& left,const char* const& right) const { return strcmp(left,right) < 0; } }; /// typedef std::map<const char*, int,StringLess> TMyMap; ```
std::map iteration - order differences between Debug and Release builds
[ "", "c++", "stl", "" ]
I noticed a good while back that Wikipedia links to a [Javascript implementation](http://pajhome.org.uk/crypt/md5/) of different hash functions. Also found [Clipperz Crypto](http://www.clipperz.com/open_source/javascript_crypto_library). Even Mozilla implements a [crypto object](http://developer.mozilla.org/en/JavaScript_crypto) in Firefox. So, *Is Javascript a proper platform for cryptography? Or, can it be?* Or, I suppose.. Are there any purposes or benefits for hashing data before POST?
There are uses for hashing functions in Javascript, for example validating captchas client side (by comparing hash in session to computed hash from input). Obviously, the uses are limited since it runs almost exclusively client side (and you can't trust client input), but the potential is there.
You can encrypt data using JavaScript; however I'm not sure about the benefits. Because if you are using, let's say bas64, you need to send the encryption key to the client, and if someone can intercept the encrypted information he/ she would probably be able to intercept the encryption key too. You should never use this for replacing SSL certificates.
Is Javascript a proper platform for cryptography? Or, can it be?
[ "", "javascript", "security", "language-agnostic", "cryptography", "" ]
Is there any way to clean up this type of loop using LINQ? ``` List<Car> result; List<string> makes; List<string> models; for (int i = 0; i < makes.Count() && i < models.Count(); i++) { result.Add(new Car() { Make = makes[i], Model = models[i] }); } ``` Basically I'm looking for some way to collate multiple arrays of individual fields into a single array of objects made up of those fields.
You could use `Enumerable.Range`, like so: ``` List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count)) .Select(i => new Car { Make = makes[i], Model = models[i] }).ToList(); ``` If `makes` and `models` always contain the same number of items, you can use more compact syntax: ``` List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList(); ```
It sounds like you really need a new LINQ operator - one which wasn't included in LINQ, somewhat accidentally: Zip. It would basically take two enumerables and return a single enumerable which paired entries, until one or other of the original sequences finished. I don't have anything like that up my sleeve, but it shouldn't take too long to write if you're interested. The resulting code would be something like: ``` List<Car> cars = makes.Zip(models) .Select(pair => new Car(pair.First, pair.Second)) .ToList(); ``` Let me know if you'd be interested in this and I'll code it up in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil).
How do I LINQify this?
[ "", "c#", ".net", "linq", "" ]
Our base Masterpage has something like the following ``` <head runat="server"> <title></title> <script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/actions.js")%>"></script> <script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></script> <asp:contentplaceholder id="cph_htmlhead" runat="server"> </asp:contentplaceholder> </head> ``` If this Masterpage is the Masterpage for an ASPX page things work fine. If this Masterpage is the Masterpage for a child Masterpage and then a new ASPX page uses the child Masterpage as it's MasterPage we see: Server Error in '' Application. The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>). **What is the preferred way to include global resources (Javascript/CSS) in a base Masterpage preserving tilde(~) style relative pathing?**
Use the ScriptManager server control: ``` <asp:ScriptManager ID="myScriptManager" runat="server"> <Scripts> <asp:ScriptReference Path = "~/javascript/actions.js" /> <asp:ScriptReference Path = "~/javascript/jquery/jquery-1.2.6.min.js" /> </Scripts> </asp:ScriptManager> ```
Have you tried: ``` <script type="text/javascript" src='<%= Page.ResolveClientUrl("~/javascript/actions.js") %>'></script> ```
Preferred way to include relative reference to JavaScript in VS 2008 nested Masterpage
[ "", "asp.net", "javascript", "master-pages", "relative-path", "nested", "" ]
Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too.
[PHP Code Beautifier](http://www.waterproof.fr/products/phpCodeBeautifier/) is a useful free tool that should do what you're after, although their [download page](http://www.waterproof.fr/products/phpCodeBeautifier/download.php) does require an account to be created. > The tool has been declined into 3 versions: > > * A GUI version which allow to process file visually. > * A command line version which allow to be batched or integrated with other tools (CVS, SubVersion, IDE ...). > * As an integrated tool of PHPEdit. Basically, it'll turn: ``` if($code == BAD){$action = REWRITE;}else{$action = KEEP;} for($i=0; $i<10;$i++){while($j>0){$j++;doCall($i+$j);if($k){$k/=10;}}} ``` into ``` if ($code == BAD) { $action = REWRITE; } else { $action = KEEP; } for($i = 0; $i < 10;$i++) { while ($j > 0) { $j++; doCall($i + $j); if ($k) { $k /= 10; } } } ```
Well here is my very basic and rough script: ``` #!/usr/bin/php <?php class Token { public $type; public $contents; public function __construct($rawToken) { if (is_array($rawToken)) { $this->type = $rawToken[0]; $this->contents = $rawToken[1]; } else { $this->type = -1; $this->contents = $rawToken; } } } $file = $argv[1]; $code = file_get_contents($file); $rawTokens = token_get_all($code); $tokens = array(); foreach ($rawTokens as $rawToken) { $tokens[] = new Token($rawToken); } function skipWhitespace(&$tokens, &$i) { global $lineNo; $i++; $token = $tokens[$i]; while ($token->type == T_WHITESPACE) { $lineNo += substr($token->contents, "\n"); $i++; $token = $tokens[$i]; } } function nextToken(&$j) { global $tokens, $i; $j = $i; do { $j++; $token = $tokens[$j]; } while ($token->type == T_WHITESPACE); return $token; } $OPERATORS = array('=', '.', '+', '-', '*', '/', '%', '||', '&&', '+=', '-=', '*=', '/=', '.=', '%=', '==', '!=', '<=', '>=', '<', '>', '===', '!=='); $IMPORT_STATEMENTS = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE); $CONTROL_STRUCTURES = array(T_IF, T_ELSEIF, T_FOREACH, T_FOR, T_WHILE, T_SWITCH, T_ELSE); $WHITESPACE_BEFORE = array('?', '{', '=>'); $WHITESPACE_AFTER = array(',', '?', '=>'); foreach ($OPERATORS as $op) { $WHITESPACE_BEFORE[] = $op; $WHITESPACE_AFTER[] = $op; } $matchingTernary = false; // First pass - filter out unwanted tokens $filteredTokens = array(); for ($i = 0, $n = count($tokens); $i < $n; $i++) { $token = $tokens[$i]; if ($token->contents == '?') { $matchingTernary = true; } if (in_array($token->type, $IMPORT_STATEMENTS) && nextToken($j)->contents == '(') { $filteredTokens[] = $token; if ($tokens[$i + 1]->type != T_WHITESPACE) { $filteredTokens[] = new Token(array(T_WHITESPACE, ' ')); } $i = $j; do { $i++; $token = $tokens[$i]; if ($token->contents != ')') { $filteredTokens[] = $token; } } while ($token->contents != ')'); } elseif ($token->type == T_ELSE && nextToken($j)->type == T_IF) { $i = $j; $filteredTokens[] = new Token(array(T_ELSEIF, 'elseif')); } elseif ($token->contents == ':') { if ($matchingTernary) { $matchingTernary = false; } elseif ($tokens[$i - 1]->type == T_WHITESPACE) { array_pop($filteredTokens); // Remove whitespace before } $filteredTokens[] = $token; } else { $filteredTokens[] = $token; } } $tokens = $filteredTokens; function isAssocArrayVariable($offset = 0) { global $tokens, $i; $j = $i + $offset; return $tokens[$j]->type == T_VARIABLE && $tokens[$j + 1]->contents == '[' && $tokens[$j + 2]->type == T_STRING && preg_match('/[a-z_]+/', $tokens[$j + 2]->contents) && $tokens[$j + 3]->contents == ']'; } // Second pass - add whitespace $matchingTernary = false; $doubleQuote = false; for ($i = 0, $n = count($tokens); $i < $n; $i++) { $token = $tokens[$i]; if ($token->contents == '?') { $matchingTernary = true; } if ($token->contents == '"' && isAssocArrayVariable(1) && $tokens[$i + 5]->contents == '"') { /* * Handle case where the only thing quoted is the assoc array variable. * Eg. "$value[key]" */ $quote = $tokens[$i++]->contents; $var = $tokens[$i++]->contents; $openSquareBracket = $tokens[$i++]->contents; $str = $tokens[$i++]->contents; $closeSquareBracket = $tokens[$i++]->contents; $quote = $tokens[$i]->contents; echo $var . "['" . $str . "']"; $doubleQuote = false; continue; } if ($token->contents == '"') { $doubleQuote = !$doubleQuote; } if ($doubleQuote && $token->contents == '"' && isAssocArrayVariable(1)) { // don't echo " } elseif ($doubleQuote && isAssocArrayVariable()) { if ($tokens[$i - 1]->contents != '"') { echo '" . '; } $var = $token->contents; $openSquareBracket = $tokens[++$i]->contents; $str = $tokens[++$i]->contents; $closeSquareBracket = $tokens[++$i]->contents; echo $var . "['" . $str . "']"; if ($tokens[$i + 1]->contents != '"') { echo ' . "'; } else { $i++; // process " $doubleQuote = false; } } elseif ($token->type == T_STRING && $tokens[$i - 1]->contents == '[' && $tokens[$i + 1]->contents == ']') { if (preg_match('/[a-z_]+/', $token->contents)) { echo "'" . $token->contents . "'"; } else { echo $token->contents; } } elseif ($token->type == T_ENCAPSED_AND_WHITESPACE || $token->type == T_STRING) { echo $token->contents; } elseif ($token->contents == '-' && in_array($tokens[$i + 1]->type, array(T_LNUMBER, T_DNUMBER))) { echo '-'; } elseif (in_array($token->type, $CONTROL_STRUCTURES)) { echo $token->contents; if ($tokens[$i + 1]->type != T_WHITESPACE) { echo ' '; } } elseif ($token->contents == '}' && in_array($tokens[$i + 1]->type, $CONTROL_STRUCTURES)) { echo '} '; } elseif ($token->contents == '=' && $tokens[$i + 1]->contents == '&') { if ($tokens[$i - 1]->type != T_WHITESPACE) { echo ' '; } $i++; // match & echo '=&'; if ($tokens[$i + 1]->type != T_WHITESPACE) { echo ' '; } } elseif ($token->contents == ':' && $matchingTernary) { $matchingTernary = false; if ($tokens[$i - 1]->type != T_WHITESPACE) { echo ' '; } echo ':'; if ($tokens[$i + 1]->type != T_WHITESPACE) { echo ' '; } } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE && in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) { echo ' ' . $token->contents . ' '; } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE) { echo ' ' . $token->contents; } elseif (in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) { echo $token->contents . ' '; } else { echo $token->contents; } } ```
Php code formatter / beautifier and php beautification in general
[ "", "php", "editor", "" ]
Does the using catch the exception or throw it? i.e. ``` using (StreamReader rdr = File.OpenText("file.txt")) { //do stuff } ``` If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?
using statements do not eat exceptions. All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block. There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called.
When you see a using statement, think of this code: ``` StreadReader rdr = null; try { rdr = File.OpenText("file.txt"); //do stuff } finally { if (rdr != null) rdr.Dispose(); } ``` So the real answer is that it doesn't do anything with the exception thrown in the body of the using block. It doesn't handle it or rethrow it.
C# "Using" Syntax
[ "", "c#", "exception", "using", "using-statement", "" ]
What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired? I would prefer to not use Console.Read or Console.ReadLine as I do not want to accept input. I just want to enable the underlying application to print to the console event details as they are fired. Then once the CancelKeyPress event is fired I want to gracefully shut down the application.
I'm assuming that "gracefully shut down the application" is the part you are struggling with here. Otherwise your application will automatically exit on ctrl-c. You should change the title. Here's a quick demo of what I think you need. It could be refined a bit more with use of locking and Monitors for notification. I'm not sure exactly what you need though, so I'll just pose this... ``` class Program { private static volatile bool _s_stop = false; public static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); while (!_s_stop) { /* put real logic here */ Console.WriteLine("still running at {0}", DateTime.Now); Thread.Sleep(3000); } Console.WriteLine("Graceful shut down code here..."); //don't leave this... demonstration purposes only... Console.ReadLine(); } static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { //you have 2 options here, leave e.Cancel set to false and just handle any //graceful shutdown that you can while in here, or set a flag to notify the other //thread at the next check that it's to shut down. I'll do the 2nd option e.Cancel = true; _s_stop = true; Console.WriteLine("CancelKeyPress fired..."); } } ``` The \_s\_stop boolean should be declared volatile or an overly-ambitious optimizer might cause the program to loop infinitely.
The `_s_stop` boolean should be declared volatile in the example code, or an overly-ambitious optimizer might cause the program to loop infinitely.
How can I keep a console open until CancelKeyPress event is fired?
[ "", "c#", ".net", "console", "" ]
I'm writing code that looks similar to this: ``` public IEnumerable<T> Unfold<T>(this T seed) { while (true) { yield return [next (T)object in custom sequence]; } } ``` Obviously, this method is never going to return. (The C# compiler silently allows this, while R# gives me the warning *"Function never returns"*.) Generally speaking, is it *bad* design to provide an enumerator that returns an infinite number of items, without supplying a way to stop enumerating? Are there any special considerations for this scenario? Mem? Perf? Other gotchas? If we always supply an exit condition, which are the options? E.g: * an object of type T that represents the inclusive or exclusive boundary * a `Predicate<T> continue` (as `TakeWhile` does) * a count (as `Take` does) * ... Should we rely on users calling `Take(...)` / `TakeWhile(...)` after `Unfold(...)`? (Maybe the preferred option, since it leverages existing Linq knowledge.) Would you answer this question differently if the code was going to be published in a public API, either as-is (generic) or as a specific implementation of this pattern?
So long as you document very clearly that the method will never finish iterating (the method itself returns very quickly, of course) then I think it's fine. Indeed, it can make some algorithms much neater. I don't believe there are any significant memory/perf implications - although if you refer to an "expensive" object within your iterator, that reference will be captured. There are always ways of abusing APIs: so long as your docs are clear, I think it's fine.
> "Generally speaking, is it bad desing > to provide an enumerator that returns > an infinite amount of items, without > supplying a way to stop enumerating?" The consumer of the code, can **always** stop enumerating (using break for example or other means). If your enumerator returns and infinite sequence, that doesn't mean the client of the enumerator is somehow forced to never break enumeration, actually you can't make an enumerator which is guaranteed to be fully enumerated by a client. > Should we rely on users calling > Take(...) / TakeWhile(...) after > Unfold(...)? (Maybe the preferred > option, since it leverages existing > Linq knowledge.) Yes, as long as you clearly specify in your documentation that the enumerator returns and infinite sequence and breaking of enumeration is the caller's responsibility, everything should be fine. Returning infinite sequences isn't a bad idea, functional programing languages have done it for a long time now.
How do you design an enumerator that returns (theoretically) an infinite amount of items?
[ "", "c#", "enumerator", "" ]
I'm looking for a good audio compression library for .NET. Anything using MP3 is out (because of the licensing issue). Basically I just need to be able to compress regular WAV audio data into some format, and decompress back to WAV. Preferably the code would be all .NET (C# or VB.NET), but I don't think this is likely. It should either be lossless or relatively lossless (as good as 192 MP3s, preferably), with a compression ratio at least as good as 4:1. I'd prefer a buffer-based API, but a file-based API is OK too. Does anyone know of anything like this?
Have you thought about using WMA? If you use managed C++ or C++/CLI it's very easy to write a managed wrapper around the Windows Media Format SDK. This assembly can then be easily used by a higher level VB.Net or C# assembly. As long as you have WMP installed it even has the advantage of not requiring any additional dependencies.
You've thought about the **.OGG** format yet? I don't know if a .net library is available, but the libogg and libvorbis C libs aren't rocket-science and well tested. For a simple compress/decompress job you may get away with a two function wrapper that handles all the details. It should be easy to write a .net wrapper around them. Benefits: * patent free * usable licence even for closed source projects * *very* good compression ratio * cross platform (maybe not that important since you aim .net, but nevertheless nice to have). * last but not least: a very mature library without known bugs and good support.
What's the best audio compression library for .NET?
[ "", "c#", ".net", "vb.net", "audio", "compression", "" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? ***Note***: I didn't use any Python Web Framework, I just wrote the whole thing from scratch. ***Note'***: Other suggestions are also welcome.
For nginx/mod\_wsgi, ensure you read: <http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html> Because of how nginx is an event driven system underneath, it has behavioural characteristics which are detrimental to blocking applications such as is the case with WSGI based applications. Worse case scenario is that with multiprocess nginx configuration, you can see user requests be blocked even though some nginx worker processes may be idle. Apache/mod\_wsgi doesn't have this issue as Apache processes will only accept requests when it has the resources to actually handle the request. Apache/mod\_wsgi will thus give more predictable and reliable behaviour.
The author of nginx mod\_wsgi explains some differences to Apache mod\_wsgi [in this mailing list message](http://osdir.com/ml/web.nginx.english/2008-05/msg00451.html).
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
[ "", "python", "apache", "nginx", "mod-wsgi", "" ]
The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.
I don't endorse this solution in any way, shape or form. But if you add a variable to the `__builtin__` module, it will be accessible as if a global from any other module that includes `__builtin__` -- which is all of them, by default. a.py contains ``` print foo ``` b.py contains ``` import __builtin__ __builtin__.foo = 1 import a ``` The result is that "1" is printed. **Edit:** The `__builtin__` module is available as the local symbol `__builtins__` -- that's the reason for the discrepancy between two of these answers. Also note that `__builtin__` has been renamed to `builtins` in python3.
If you need a global cross-module variable maybe just simple global module-level variable will suffice. a.py: ``` var = 1 ``` b.py: ``` import a print a.var import c print a.var ``` c.py: ``` import a a.var = 2 ``` Test: ``` $ python b.py # -> 1 2 ``` Real-world example: [Django's global\_settings.py](https://github.com/django/django/blob/master/django/conf/global_settings.py) (though in Django apps settings are used by importing the *object* [`django.conf.settings`](http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code)).
How to make a cross-module variable?
[ "", "python", "module", "global", "" ]
Is there a way to deploy a given war file on Tomcat server? I want to do this without using the web interface.
Just copy the war file into the $TOMCAT\_HOME/webapps/ directory. Tomcat will deploy the war file by automatically exploding it. FYI - If you want you can make updates directly to the exploded directory, which is useful for development.
There are several ways to deploy a Tomcat webapp: * Dropping into $CATALINA\_HOME/webapps, as was already mentioned. * Using your build scripts to deploy automatically via the manager interface (that comes with Tomcat). Here are the two ways + for *Maven*: use the tomcat plugin. You don't need to include it in `pom.xml`, just issue the goal `mvn tomcat:deploy`, the plugin is included in Maven 2. This assumes several defaults explained in the [documentation](http://mojo.codehaus.org/tomcat-maven-plugin/), you can [configure](http://mojo.codehaus.org/tomcat-maven-plugin/usage.html) the behaviour in the `pom.xml`. There are other goals that let you deploy as an exploded archive *etc*. + for *Ant*: something like this: ``` <property name="manager.url" value="http://localhost:8080/manager"/> <property name="manager.username" value="manager"/> <property name="manager.password" value="foobar"/> <!-- Task definitions --> <taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask"/> <taskdef name="list" classname="org.apache.catalina.ant.ListTask"/> <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"/> <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/> <!-- goals --> <target name="install" depends="compile" description="Install application to servlet container"> <deploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" localWar="file://${build.home}"/> </target> <target name="list" description="List installed applications on servlet container"> <list url="${manager.url}" username="${manager.username}" password="${manager.password}"/> </target> <target name="reload" depends="compile" description="Reload application on servlet container"> <reload url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target> <target name="remove" description="Remove application on servlet container"> <undeploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target> ``` All of those will require you to have a Tomcat user configuration. It lives `$CATALINA_BASE/conf/tomcat-users.xml`, but since you know already how to use the web interface, I assume you know how to configure the users and passwords.
Deployment of war file on Tomcat
[ "", "java", "linux", "tomcat", "deployment", "release-management", "" ]
Our company runs a web site (oursite.com) with affiliate partners who send us traffic. In some cases, we set up our affiliates with their own subdomain (affiliate.oursite.com), and they display selected content from our site on their site (affiliate.com) using an iframe. Example of a page on their site: ``` <html> <head></head> <body> <iframe src="affiliate.example.com/example_page.html"> ...content... [google analytics code for affiliate.oursite.com] </iframe> [google analytics code for affiliate.com] </body> </html> ``` We would like to have Google Analytics tracking for affiliate.oursite.com. At present, it does not seem that Google is receiving any data from the affiliate when the page is loaded from the iframe. Now, there are security implications in that Javascript doesn't like accessing information about a page in a different domain, and IE doesn't like setting cookies for a different domain. Does anyone have a solution to this? Will we need to CNAME the affiliate.oursite.com to cname.oursite.com, or is there a cleaner solution?
1. You have to append the Google Analytics tracking code to the end of `example_page.html`. The content between the `<iframe>` - `</iframe>` tag only displays for browsers, which do not support that specific tag. 2. Should you need to merge the results from the subdomains, there's an excellent article on Google's help site: [How do I track all of the subdomains for my site in one profile?](http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55524)
In the specific case of iframes, Google doesn't say much. I've been in the same situation but I'm glad I figured it out. I posted a [walkthrough here](http://www.emarketeur.fr/gestion-de-projet/developper/mesurer-son-trafic-sur-plusieurs-domaines-au-travers-dun-iframe-avec-google-analytics). It's in French but you won't need to speak the language to copy / paste the code. Plus there's a demo file you can download.
Running Google Analytics in iframe?
[ "", "javascript", "iframe", "google-analytics", "cross-domain", "tracking", "" ]
How can I unset variable? For example, PHP has an `unset($var)` function.
There is not really an equivalent to "unset". The closest match I know is the use of the [default](http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx) keyword. For example: ``` MyType myvar = default(MyType); string a = default(string); ``` The variable will still be "set", but it will have its default value.
You can't. There's no notion of "unsetting" a variable. You can set it to a different value - 0, null, whatever's appropriate. Instance/static variables don't even have a concept of whether the variable is set/unset, and local variables only have "definitely assigned" or "not definitely assigned". What is it you're trying to achieve?
How to unset variable in C#?
[ "", "c#", "" ]
I've been unable to build [P4Python](http://www.perforce.com/perforce/loadsupp.html#api) for an Intel Mac OS X 10.5.5. These are my steps: 1. I downloaded p4python.tgz (from <http://filehost.perforce.com/perforce/r07.3/tools/>) and expanded it into "P4Python-2007.3". 2. I downloaded p4api.tar (from <http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/>) and expanded it into "p4api-2007.3.143793". 3. I placed "p4api-2007.3.143793" into "P4Python-2007.3" and edited setup.cfg to set "p4\_api=./p4api-2007.3.143793". 4. I added the line 'extra\_link\_args = ["-framework", "Carbon"]' to setup.py after: ``` elif unameOut[0] == "Darwin": unix = "MACOSX" release = "104" platform = self.architecture(unameOut[4]) ``` 5. I ran `python setup.py build` and got: $ python setup.py build ``` API Release 2007.3 running build running build_py running build_ext building 'P4API' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DID_OS="MACOSX104X86" -DID_REL="2007.3" -DID_PATCH="151416" -DID_API="2007.3" -DID_Y="2008" -DID_M="04" -DID_D="09" -I./p4api-2007.3.143793 -I./p4api-2007.3.143793/include/p4 -I/build/toolchain/mac32/python-2.4.3/include/python2.4 -c P4API.cpp -o build/temp.darwin-9.5.0-i386-2.4/P4API.o -DOS_MACOSX -DOS_MACOSX104 -DOS_MACOSXX86 -DOS_MACOSX104X86 cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++ P4API.cpp: In function âint P4Adapter_init(P4Adapter*, PyObject*, PyObject*)â: P4API.cpp:105: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:105: error: expected `;' before âposâ P4API.cpp:107: error: âposâ was not declared in this scope P4API.cpp: In function âPyObject* P4Adapter_run(P4Adapter*, PyObject*)â: P4API.cpp:177: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:177: error: expected `;' before âiâ P4API.cpp:177: error: âiâ was not declared in this scope error: command 'gcc' failed with exit status 1 ``` `which gcc` returns /usr/bin/gcc and `gcc -v` returns: ``` Using built-in specs. Target: i686-apple-darwin9 Configured with: /var/tmp/gcc/gcc-5465~16/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib --build=i686-apple-darwin9 --with-arch=apple --with-tune=generic --host=i686-apple-darwin9 --target=i686-apple-darwin9 Thread model: posix gcc version 4.0.1 (Apple Inc. build 5465) ``` `python -V` returns Python 2.4.3.
The newer version 2008.1 will build with Python 2.4. I had posted the minor changes required to do that on my P4Python page, but they were rolled in to the official version. Robert
From <http://bugs.mymediasystem.org/?do=details&task_id=676> suggests that Py\_ssize\_t was added in python 2.5, so it won't work (without some modifications) with python 2.4. Either install/compile your own copy of python 2.5/2.6, or work out how to change P4Python, or look for an alternative python-perforce library.
How do I build and install P4Python for Mac OS X?
[ "", "python", "macos", "perforce", "p4python", "" ]
I have a table of items, each of which has a date associated with it. If I have the date associated with one item, how do I query the database with SQL to get the 'previous' and 'subsequent' items in the table? It is not possible to simply add (or subtract) a value, as the dates do not have a regular gap between them. One possible application would be 'previous/next' links in a photo album or blog web application, where the underlying data is in a SQL table. I think there are two possible cases: **Firstly** where each date is unique: Sample data: ``` 1,3,8,19,67,45 ``` What query (or queries) would give 3 and 19 when supplied 8 as the parameter? (or the rows 3,8,19). Note that there are not always three rows to be returned - at the ends of the sequence one would be missing. **Secondly**, if there is a separate unique key to order the elements by, what is the query to return the set 'surrounding' a date? The order expected is by date then key. Sample data: ``` (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8 ``` What query for '8' returns the set: ``` 2:3,3:8,4:8,16:8,5:19 ``` or what query generates the table: ``` key date prev-key next-key 1 1 null 2 2 3 1 3 3 8 2 4 4 8 3 16 5 19 16 10 10 19 5 11 11 67 10 15 15 45 11 null 16 8 4 5 ``` The table order is not important - just the next-key and prev-key fields. --- Both TheSoftwareJedi and Cade Roux have solutions that work for the data sets I posted last night. For the second question, both seem to fail for this dataset: ``` (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8 ``` The order expected is by date then key, so one expected result might be: ``` 2:3,3:8,4:8,16:8,5:19 ``` and another: ``` key date prev-key next-key 1 1 null 2 2 3 1 3 3 8 2 4 4 8 3 16 5 19 16 10 10 19 5 11 11 67 10 15 15 45 11 null 16 8 4 5 ``` The table order is not important - just the next-key and prev-key fields.
My own attempt at the set solution, based on TheSoftwareJedi. First question: ``` select date from test where date = 8 union all select max(date) from test where date < 8 union all select min(date) from test where date > 8 order by date; ``` Second question: While debugging this, I used the data set: ``` (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8,17:3,18:1 ``` to give this result: ``` select * from test2 where date = 8 union all select * from (select * from test2 where date = (select max(date) from test2 where date < 8)) where key = (select max(key) from test2 where date = (select max(date) from test2 where date < 8)) union all select * from (select * from test2 where date = (select min(date) from test2 where date > 8)) where key = (select min(key) from test2 where date = (select min(date) from test2 where date > 8)) order by date,key; ``` In both cases the final order by clause is strictly speaking optional.
Select max(element) From Data Where Element < 8 Union Select min(element) From Data Where Element > 8 But generally it is more usefull to think of sql for set oriented operations rather than iterative operation.
What is the SQL for 'next' and 'previous' in a table?
[ "", "sql", "" ]
I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly. I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - [this old discussion list link](http://mail.python.org/pipermail/python-list/2000-March/028122.html) has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions. Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :)
There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example: ``` class Whois(object): _whois_by_query_cache = {} def __init__(self, query): """Initializes the instance variables to defaults. See :meth:`lookup` for details on how to submit the query.""" self.query = query self.domain = None # ... other fields. def lookup(self): """Submits the `whois` query and stores results internally.""" # ... implementation ``` Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like [you're saying](https://stackoverflow.com/questions/50394#50423)), this interface stays the same. This approach is generally not considered ugly at all -- **sometimes command utilities do what you want and you should be able to leverage them**. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code. [Practicality beats purity](http://www.python.org/dev/peps/pep-0020/) -- that's what's Pythonic. :)
Found this question in the process of my own search for a python whois library. Don't know that I agree with cdleary's answer that using a library that wraps a command is always the best way to go - but I can see his reasons why he said this. Pro: cmd-line whois handles all the hard work (socket calls, parsing, etc) Con: not portable; module may not work depending on underlying whois command. Slower, since running a command and most likely shell in addition to whois command. Affected if not UNIX (Windows), different UNIX, older UNIX, or older whois command I am looking for a whois module that can handle whois IP lookups and I am not interested in coding my own whois client. Here are the modules that I (lightly) tried out and more information about it: **UPDATE from 2022: I would search pypi for newer whois libraries.** NOTE - some APIs are specific to online paid services pywhoisapi: * Home: <http://code.google.com/p/pywhoisapi/> * Last Updated: 2011 * Design: REST client accessing ARIN whois REST service * Pros: Able to handle IP address lookups * Cons: Able to pull information from whois servers of other RIRs? BulkWhois * Home: <http://pypi.python.org/pypi/BulkWhois/0.2.1> * Last Updated: fork <https://github.com/deontpearson/BulkWhois> in 2020 * Design: telnet client accessing whois telnet query interface from RIR(?) * Pros: Able to handle IP address lookups * Cons: Able to pull information from whois servers of other RIRs? pywhois: * Home: <http://code.google.com/p/pywhois/> * Last Updated: 2010 (no forks found) * Design: REST client accessing RRID whois services * Pros: Accessses many RRIDs; has python 3.x branch * Cons: does not seem to handle IP address lookups python-whois (wraps whois command): * Home: <http://code.google.com/p/python-whois/> * Last Updated: 2022-11 <https://github.com/DannyCork/python-whois> * Design: wraps "whois" command * Cons: does not seem to handle IP address lookups whois: * Home: <https://github.com/richardpenman/whois> (<https://pypi.org/project/python-whois/>) * Last Updated: 2022-12 * Design: port of whois.c from Apple * Cons: TODO whoisclient - fork of python-whois * Home: <http://gitorious.org/python-whois> * Last Updated: (home website no longer valid) * Design: wraps "whois" command * Depends on: IPy.py * Cons: does not seem to handle IP address lookups Update: I ended up using pywhoisapi for the reverse IP lookups that I was doing
What Python way would you suggest to check whois database records?
[ "", "python", "system-administration", "whois", "" ]
Let's say I have a class that has a member called data which is a list. I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list. What's your technique for doing this? Do you just check the type by looking at `__class__`? Is there some trick I might be missing? I'm used to C++ where overloading by argument type is easy.
A much neater way to get 'alternate constructors' is to use classmethods. For instance: ``` >>> class MyData: ... def __init__(self, data): ... "Initialize MyData from a sequence" ... self.data = data ... ... @classmethod ... def fromfilename(cls, filename): ... "Initialize MyData from a file" ... data = open(filename).readlines() ... return cls(data) ... ... @classmethod ... def fromdict(cls, datadict): ... "Initialize MyData from a dict's items" ... return cls(datadict.items()) ... >>> MyData([1, 2, 3]).data [1, 2, 3] >>> MyData.fromfilename("/tmp/foobar").data ['foo\n', 'bar\n', 'baz\n'] >>> MyData.fromdict({"spam": "ham"}).data [('spam', 'ham')] ``` The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with `isinstance(x, basestring)` is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.
with python3, you can use [Implementing Multiple Dispatch with Function Annotations](https://github.com/dabeaz/python-cookbook/blob/master/src/9/multiple_dispatch_with_function_annotations/example1.py) as Python Cookbook wrote: ``` import time class Date(metaclass=MultipleMeta): def __init__(self, year:int, month:int, day:int): self.year = year self.month = month self.day = day def __init__(self): t = time.localtime() self.__init__(t.tm_year, t.tm_mon, t.tm_mday) ``` and it works like: ``` >>> d = Date(2012, 12, 21) >>> d.year 2012 >>> e = Date() >>> e.year 2018 ```
How to overload __init__ method based on argument type?
[ "", "python", "constructor", "operator-overloading", "" ]
I have a table in my database which stores a tree structure. Here are the relevant fields: ``` mytree (id, parentid, otherfields...) ``` I want to find all the leaf nodes (that is, any record whose `id` is not another record's `parentid`) I've tried this: ``` SELECT * FROM mytree WHERE `id` NOT IN (SELECT DISTINCT `parentid` FROM `mytree`) ``` But that returned an empty set. Strangely, removing the "NOT" returns the set of all the non-leaf nodes. Can anyone see where I'm going wrong? *Update:* Thanks for the answers folks, they all have been correct and worked for me. I've accepted Daniel's since it also explains why my query didn't work (the NULL thing).
Your query didn't work because the sub-query includes `NULL`. The following slight modification works for me: ``` SELECT * FROM `mytree` WHERE `id` NOT IN ( SELECT DISTINCT `parentid` FROM `mytree` WHERE `parentid` IS NOT NULL) ```
No clue why your query didn't work. Here's the identical thing in left outer join syntax - try it this way? ``` select a.* from mytree a left outer join mytree b on a.id = b.parentid where b.parentid is null ```
Find leaf nodes in hierarchical tree
[ "", "sql", "database", "tree", "" ]