Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Hashtables have a syncroot property but generic dictionaries don't. If I have code that does this: ``` lock (hashtable.Syncroot) { .... } ``` How do I replicate this if I am removing the hashtable and changing to generic dictionaries?
If you are going strictly for compatability then Bryan is correct. This is the best way to maintain your current semantics on top of a Dictionary. Expanding on it though. The reason the SyncRoot property was not directly added to the generic dictionary is that it's a dangerous way to do synchronization. It's only slig...
The new thinking behind SyncRoot is that it was a mistake in the original design. If the only thing to lock is the dictionary and it's private, you can lock it or another object that serves as the synchronization object. The latter technique is useful when the state you are protecting is more than just the dictionary. ...
Hashtable to Dictionary<> syncroot .
[ "", "c#", "generics", "dictionary", "hashtable", "" ]
I'm wanting to use google maps and see a million ways to do it on the web. Some are javascript methods and some are asp.net server components with which I have hit and miss luck. What's the easiest and most reliable way using c# and asp.net? I have my location data including geocodes in a database. I want to provide u...
The Google Maps API is accessed via JavaScript (any server controls are just abstracting this away from you). In the case you described, you would need to dynamically output the required JavaScript to tell the maps API what to display. See <http://dotnet.sys-con.com/node/171162>
There are a few server controls to do it, like [this](http://googlemaps.subgurim.net/), but you have to learn how to do things in one way (server control) or another (Javascript Google API). I recommend using the Google API, since it has more samples all over the web, and you can use new features implemented by Google...
Google Maps - Easy way in ASP.Net?
[ "", "c#", "asp.net", "google-maps", "" ]
Is there a way or tool for Vista I can use to search for content in Java files? (I do not have an Eclipse project set up for it) I used to be able to do it easily in the windows search tool when I had Windows 2000. Edit: I have already enabled "search file contents" and added additional file types as recommended by x...
Personally, I just use [BareGrep](http://www.baremetalsoft.com/baregrep/ "BareGrep") (and previously, [Agent Ransack](http://www.mythicsoft.com/agentransack/ "Agent Ransack")), which is fast, supports regexes and show lines that match. [grepWin](http://tools.tortoisesvn.net/grepWin "grepWin") is nice too (can replace...
There are tons of search tools. Simplest and smallest is the GNU grep. I personnally use Far (for many things, not just search).
How do I search in files (for example in Java files) in Vista?
[ "", "java", "search", "windows-vista", "" ]
I have checked the whole site and googled on the net but was unable to find a simple solution to this problem. I have a datatable which has about 20 columns and 10K rows. I need to remove the duplicate rows in this datatable based on 4 key columns. Doesn't .Net have a function which does this? The function closest to ...
You can use Linq to Datasets. Check [this](http://msdn.microsoft.com/en-us/library/bb669119.aspx). Something like this: ``` // Fill the DataSet. DataSet ds = new DataSet(); ds.Locale = CultureInfo.InvariantCulture; FillDataSet(ds); List<DataRow> rows = new List<DataRow>(); DataTable contact = ds.Tables["Contact"]; ...
[How can I remove duplicate rows?](https://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows). (Adjust the query there to join on your 4 key columns) EDIT: with your new information I believe the easiest way would be to implement IEqualityComparer<T> and use Distinct on your data rows. Otherwise if...
What is the best way to remove duplicates from a datatable?
[ "", "c#", "datatable", "duplicates", "" ]
This is my first time using joomla. I don't know if I'm using the concept of a Contact in the wrong way, but I have a Contact Us menu that I've created and I've added the contact details in. I'm looking to add a sentence or two of text above the contact details & the e-mail contact form. There doesn't seem to be a way ...
If you really want it above the contact details you have to work with a layout-override. There is no way to do this through the admin backend. In Joomla 1.0 it was only possible with a hack, now in Joomla 1.5 there is the possibility of layout override. [This article](http://docs.joomla.org/How_to_override_the_output_...
Not exactly above the contact information but above the e-mail form you can use the "Miscellaneous Info" field to put any extra Data.
How do i add additional text to a joomla contact page
[ "", "php", "joomla", "" ]
I bet I've got elementary question, but I couldn't solve it for two nights. I've got 1 "ul" element and I just want it to move any amount of pixels every e.g. 2 sec to the left. I want him to move like this step by step and then come back to the original position and start moving again. I've been stucked, my script onl...
Do you mean something like this? ``` window.onload = function moveUl() { var eUl = document.getElementById('change'); var eLi = eUl.getElementsByTagName('li'); var delta = 0; function move() { for(i=0;i< eLi.length;i++) eUl.style.marginLeft = (-300*i+delta)+'px'; delta...
If you want it to slide, you have to timeout per iteration. Try writing a function that does a single shift, then calling this function every 10 ms. You can also look into a Javascript library like [jQuery](http://www.jquery.com) that provides a nice API for doing the moving.
I would like to move an element to the left using loop
[ "", "javascript", "" ]
What is classpath hell and is/was it really a problem for Java?
Classpath hell is an unfortunate consequence of dynamic linking of the kind carried out by Java. Your program is not a fixed entity but rather the exact set of classes loaded by a JVM in a particular instance. It is very possible to be in situations where the same command line on different platforms or even on the sa...
Classpath/jar-hell has a couple of escape hatches if they make sense for your project: * [OSGi](http://en.wikipedia.org/wiki/OSGi) * [JarJarLinks](http://code.google.com/p/jarjar/) * [NetBeans Module System](http://www.antonioshome.net/kitchen/netbeans/nbms-theplatform.php) - Not sure if this is usable outside of NetB...
What is classpath hell and is/was it really a problem for Java?
[ "", "java", "history", "" ]
I've come up with: ``` re.findall("([a-fA-F\d]*)", data) ``` but it's not very fool proof, is there a better way to grab all MD5-hash codes?
Well, since md5 is just a string of 32 hex digits, about all you could add to your expression is a check for "32 digits", perhaps something like this? ``` re.findall(r"([a-fA-F\d]{32})", data) ```
When using regular expressions in Python, you should almost always use the raw string syntax `r"..."`: ``` re.findall(r"([a-fA-F\d]{32})", data) ``` This will ensure that the backslash in the string is not interpreted by the normal Python escaping, but is instead passed through to the `re.findall` function so it can ...
Python regex for MD5 hash
[ "", "python", "regex", "md5", "" ]
I very rarely meet any other programmers! My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense. So how do I say or read "=>" as in:- ``` IEnumerable<Person> Adults = people.Where(p => p.Age > 16) ``` Or is there even ...
I usually say 'such that' when reading that operator. In your example, p => p.Age > 16 reads as "P, such that p.Age is greater than 16." In fact, I asked this very question on the official linq pre-release forums, and Anders Hejlsberg responded by saying > I usually read the => operator as "becomes" or "for which". ...
From [MSDN](http://msdn.microsoft.com/en-us/library/bb397687.aspx): > All lambda expressions use the lambda > operator =>, which is read as "goes > to".
How do I pronounce "=>" as used in lambda expressions in .Net
[ "", "c#", ".net", "lambda", "conventions", "" ]
I've created a *very* simple app, which presents an easygui entrybox() and continues to loop this indefinitely as it receives user input. I can quit the program using the Cancel button as this returns None, but I would also like to be able to use the standard 'close' button to quit the program. (ie. top right of a Win...
It would require altering the easygui module, yes. I will get it modified! \*\* I have sent in a e-mail to the EasyGUI creator explaning this [12:12 PM, January 23/09] \*\* I just want to say that the possibility of this change happening - if at all, which I doubt - is very tiny. You see, EasyGUI is intended to be a ...
I don't know right now, but have you tried something like this?: ``` root.protocol('WM_DELETE_WINDOW', self.quit) ``` or ``` root.protocol('WM_DELETE_WINDOW', self.destroy) ``` I haven't tried, but google something like `"Tkinter protocol WM_DELETE_WINDOW"`
Close an easygui Python script with the standard 'close' button
[ "", "python", "user-interface", "tkinter", "easygui", "" ]
Hi I'm using `System.Net.Mail` to send some HTML formatted emails. What is the correct method for inserting css into the email message? I know I can apply formatting to each item, but I'ld rather use style sheets.. **EDIT** I should have mentioned that this is for an internal application, and I expect 99% of users t...
I've always found that strictly using **HTML 3.0 compatible tags and formatting** works best for all email readers and providers. nevertheless here is a [**CSS in Email** article](http://www.alistapart.com/articles/cssemail) that may answer your question, you will find solutions to your css problems.
The email clients don't use CSS in a uniform way so it's difficult to use CSS. This article can help - <http://www.alistapart.com/articles/cssemail/>
What is the best method for formatting email when using System.Net.Mail
[ "", "c#", "asp.net", "css", "system.net.mail", "" ]
I'm trying to get started with unit testing in Python and I was wondering if someone could explain the advantages and disadvantages of doctest and unittest. What conditions would you use each for?
Both are valuable. I use both doctest and [nose](https://pypi.python.org/pypi/nose/) taking the place of unittest. I use doctest for cases where the test is giving an example of usage that is actually useful as documentation. Generally I don't make these tests comprehensive, aiming solely for informative. I'm effective...
I use unittest almost exclusively. Once in a while, I'll put some stuff in a docstring that's usable by doctest. 95% of the test cases are unittest. Why? I like keeping docstrings somewhat shorter and more to the point. Sometimes test cases help clarify a docstring. Most of the time, the application's test cases are...
Python - doctest vs. unittest
[ "", "python", "unit-testing", "comparison", "doctest", "" ]
How do I check to see if a column exists in a `SqlDataReader` object? In my data access layer, I have create a method that builds the same object for multiple stored procedures calls. One of the stored procedures has an additional column that is not used by the other stored procedures. I want to modified the method to ...
``` public static class DataRecordExtensions { public static bool HasColumn(this IDataRecord dr, string columnName) { for (int i=0; i < dr.FieldCount; i++) { if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase)) return true; } ...
The correct code is: ``` public static bool HasColumn(DbDataReader Reader, string ColumnName) { foreach (DataRow row in Reader.GetSchemaTable().Rows) { if (row["ColumnName"].ToString() == ColumnName) return true; } //Still here? Column not found. return false; } ```
Check for column name in a SqlDataReader object
[ "", "c#", ".net", "sqldatareader", "" ]
I'm creating a zip file using the class FastZip from SharpZipLib and once I after I close the program, I cannot delete the file because: "Cannot delete zip.zip: It is being used by another person or program. Close any programs that might be using the file and try again." The code that is generating the file is simply...
Perhaps antivirus is busy checking the file? If not, then get a program that can tell you which programs have files open. You can look at: * [Unlocker](http://www.emptyloop.com/unlocker/) * [IARSN TaskInfo](http://www.iarsn.com/)
It looks like it may be a bug with SharpZipLib. The FastZip.CreateZip method has three overloads and two of them create use File.Create such as: ``` CreateZip(File.Create(zipFileName), // ... ``` It seems it does not close the stream, so you may be better off using: ``` string zipFileName = System.IO.Path.Combine(fi...
Cannot Delete Zip file Created by SharpZipLib (FastZip)
[ "", "c#", "file", "sharpziplib", "" ]
Can someone explain to me why this code prints 14? I was just asked by another student and couldn't figure it out. ``` int i = 5; i = ++i + ++i; cout<<i; ```
The order of side effects is undefined in C++. Additionally, modifying a variable twice in a single expression has no defined behavior (See the [C++ standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf), §5.0.4, physical page 87 / logical page 73). Solution: Don't use side effects in complex exp...
That's undefined behaviour, the result will vary depending on the compiler you use. See, for example, [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15).
i = ++i + ++i; in C++
[ "", "c++", "puzzle", "operator-precedence", "" ]
Is it possible to cast an object in Java to a combined generic type? I have a method like: ``` public static <T extends Foo & Bar> void doSomething(T object) { //do stuff } ``` Calling this method is no problem if I have a class that implements both interfaces (Foo & Bar). The problem is when I need to call thi...
Java 8 introduces the possibility of [casting with additional bounds](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.16). You can cast an `Object` as a `class` with multiple `interfaces` (or just as multiple `interfaces`). So this: ``` doSomething((Problematic cast) o); ``` simply becomes to thi...
Unfortunately, there is no legal cast that you can make to satisfy this situation. There must be a single type known to implement all of the interfaces that you need as bounds, so that you can cast to it. The might be a type you create for the purpose, or some existing type. ``` interface Baz extends Foo, Bar { } pub...
How should I cast for Java generic with multiple bounds?
[ "", "java", "generics", "casting", "polymorphism", "" ]
I'm trying to assert that one object is "equal" to another object. The objects are just instances of a class with a bunch of public properties. Is there an easy way to have NUnit assert equality based on the properties? This is my current solution but I think there may be something better: ``` Assert.AreEqual(LeftOb...
Override .Equals for your object and in the unit test you can then simply do this: ``` Assert.AreEqual(LeftObject, RightObject); ``` Of course, this might mean you just move all the individual comparisons to the .Equals method, but it would allow you to reuse that implementation for multiple tests, and probably makes...
Do not override Equals just for testing purposes. It's tedious and affects domain logic. Instead, ### Use JSON to compare the object's data No additional logic on your objects. No extra tasks for testing. Just use this simple method: ``` public static void AreEqualByJson(object expected, object actual) { var se...
Compare equality between two objects in NUnit
[ "", "c#", "unit-testing", "automated-tests", "nunit", "" ]
Anticipating the day when multi-touch interfaces become more pervasive, are there libraries in Java that can be used for developing touch applications? I'm looking for interfaces similar to MouseListener / MouseMotionListener / MouseWheelListener.
The MT4j project has everything you need to develop multitouch applications in java. All the well known multitouch gestures are already built in and can be accessed as simple as listening to mouse events (for example: component.addGestureListener(..)). It also features a hardware accelerated scene graph, similar to Jav...
[Sparsh](http://code.google.com/p/sparsh-ui/) is still in my bookmarks from the last time I was investigating multitouch java solutions. While not as straight forward as the typical mouse listener or click listener, it still provides a reasonable interface. You need your listening class to implement `sparshui.client....
How to develop multi-touch applications in Java?
[ "", "java", "touch", "multi-touch", "" ]
First, let me explain what I am doing. I need to take an order, which is split up into different databases, and print out this very large order. What I need from the orders is about 100 or so columns from different databases. The way I was doing in was querying with a join and assigning all of the column values to a va...
I'm going against the grain here, but I'd say that keeping this object mapped to the result set, and keeping the join in the database, might be a better idea. For the business logic, an "order" is usually a single cohesive concept (at least, that's how you started out framing it). Could the fact that it is mapped into...
I would recommend an object-oriented solution to this. Presumably your database is designed with tables that represent logical groupings of data. Each of these tables can likely be mapped onto a class in your system, although in some cases, it may be more than one table that makes up an object or there might be multipl...
Should I have one class for every database I use?
[ "", "c#", "database", "business-objects", "" ]
I need to update a record in a database with the following fields ``` [ID] int (AutoIncr. PK) [ScorerID] int [Score] int [DateCreated] smalldatetime ``` If a record exists for todays date (only the date portion should be checked, not the time) and a given scorer, I'd like to update the score value for this guy and th...
``` IF EXISTS (SELECT NULL FROM MyTable WHERE ScorerID = @Blah AND CONVERT(VARCHAR, DateCreated, 101) = CONVERT(VARCHAR, GETDATE(), 101)) UPDATE MyTable SET blah blah blah ELSE INSERT INTO MyTable blah blah blah ```
The other guys have covered 2005 (and prior) compatible T-SQL/apprroaches. I just wanted to add that if you are lucky enough to be working with SQL Server 2008, you could take advantage of the new Merge (sometimes referred to as Upsert) statement. I had trouble finding a blog entry or article which explains it further...
SQL Select: Update if exists, Insert if not - With date part comparison?
[ "", "sql", "sql-server", "sql-update", "" ]
I've got a website (currently in development for a third party, I'm sorry I can't show) that requires users to confirm their contact information by, clicking on a link sent to their email address, upon registration for the website. It's a pretty standard practice, not very technical or unique, which is why I was surpr...
Make sure you have [SPF records](http://www.openspf.org/) for your domain, and that they are set correctly. This will go a long way. Email deliverability is a complex topic. At a previous gig, I was a member of the [ESPC](http://www.espcoalition.org/). This [PDF link](http://www.espcoalition.org/ESPC_Authentication_Re...
My friend had a notification system that he has his PHP code send the notifications using a SMTP. So his notiifications were really sent from his Gmail account. He did this to prevent hotmail/etc from auto blocking the emails. I don't know if this helps
Hotmail / Yahoo (Others?) blocking email notifications?
[ "", "php", "email-notifications", "email-bounces", "" ]
``` function a () { return "foo"; } a.b = function () { return "bar"; } function c () { }; c.prototype = a; var d = new c(); d.b(); // returns "bar" d(); // throws exception, d is not a function ``` Is there some way for `d` to be a function, and yet still inherit properties from `a`?
Based on a [discussion on meta](https://meta.stackoverflow.com/questions/356167/why-was-this-edit-rejected-with-a-seeming-unrelated-generic-response/356168?noredirect=1#comment511249_356168) [about a similar question](https://stackoverflow.com/questions/37625164/object-createfunction-prototype-create-function-which-inh...
Actually, it turns out that this **is possible**, albeit in a **non-standard** way. Mozilla, Webkit, Blink/V8, Rhino and ActionScript provide a non-standard **`__proto__`** property, which allow changing the prototype of an object after it has been created. On these platforms, the following code is possible: ``` func...
Can a JavaScript object have a prototype chain, but also be a function?
[ "", "javascript", "inheritance", "" ]
How do I programmatically find out the width and height of the video in an mpeg-2 transport program stream file? Edit: I am using C++, but am happy for examples in any language. Edit: Corrected question - it was probably program streams I was asking about
Check out the source code to [libmpeg2](http://libmpeg2.sourceforge.net/), a F/OSS MPEG2 decoder. It appears that the width and height are set in the `mpeg2_header_sequence()` function in `header.c`. I'm not sure how control flows to that particular function, though. I'd suggest opening up an MPEG2 file in something us...
If you are using DirectX, there is a method in the VMRWindowlessControl interface: ``` piwc->GetNativeVideoSize(&w, &h, NULL, NULL); ``` Or the IBasicVideo interface: ``` pivb->GetVideoSize(&w, &h); ```
How to determine video dimensions of an mpeg-2 program stream file
[ "", "c++", "video", "mpeg-2", "transport-stream", "" ]
Generally, I like to keep an application completely ignorant of the IoC container. However I have ran into problems where I needed to access it. To abstract away the pain I use a basic Singleton. Before you run for the hills or pull out the shotgun, let me go over my solution. Basically, the IoC singleton does absolutl...
I've seen that even Ayende implements this pattern in the Rhino Commons code, but I'd advise against using it wherever possible. There's a reason Castle Windsor doesn't have this code by default. StructureMap does, but Jeremy Miller has been moving away from it. Ideally, you should regard the container itself with as m...
That's not really a singleton class. That's a static class with static members. And yes that seems a good approach. I think JP Boodhoo even has a name for this pattern. [The Static Gateway pattern](http://codebetter.com/jpboodhoo/2007/10/15/the-static-gateway-pattern).
Abstracting IoC Container Behind a Singleton - Doing it wrong?
[ "", "c#", "singleton", "inversion-of-control", "" ]
I would like to do something like this: a rotating cube on a form. I don't want to use any external library or dll, just pure .NET 3.5 (without directx). And a cube build with lines only. Could you please tell me how to do this? I don't want to use external libraries because I don't need > 100 MB library to do this th...
This is how you go about making a Cube in GDI+ C# 3D Drawing with GDI+ Euler Rotation <http://www.vcskicks.com/3d-graphics-improved.html> C# 3D-Drawing Cube with Shading <http://www.vcskicks.com/3d_gdiplus_drawing.html>
Study assignment? This can be done with some simple 3D maths. You just need to understand the basics of matrix algebra, 3D transformations, and 3D->2D view transformation. The [DirectX tutorial](http://msdn.microsoft.com/en-us/library/bb172485.aspx) covers this, but you can google for it and you'll get plenty of other ...
How to animate rotating cube in C#?
[ "", "c#", "animation", "3d", "cube", "" ]
Does anyone know of an accurate source for an (E)BNF for the Java language? Preferably, it would be from an authorative source, e.g. Sun. Thanks.
[First google result :)](http://java.sun.com/docs/books/jls/second_edition/html/syntax.doc.html) Though I can't speak for how up-to-date it might be.
i believe the 3rd edition is the latest: [JLS 3rd edition](http://java.sun.com/docs/books/jls/third_edition/html/syntax.html)
Java EBNF?
[ "", "java", "bnf", "ebnf", "" ]
In what situations should one catch `java.lang.Error` on an application?
Generally, never. However, sometimes you need to catch specific errors. If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch `LinkageError` (no class def found, unsatisfied link, incompatible class change). I've also seen some stupid 3rd-party code throwing subclasses of `Error...
Never. You can never be sure that the application is able to execute the next line of code. If you get an `OutOfMemoryError`, you have [no guarantee that you will be able to do anything reliably](https://stackoverflow.com/a/8729011/545127). Catch RuntimeException and checked Exceptions, but never Errors. <http://pmd.s...
When to catch java.lang.Error?
[ "", "java", "error-handling", "exception", "" ]
How do type casting happen without loss of data inside the compiler? For example: ``` int i = 10; UINT k = (UINT) k; float fl = 10.123; UINT ufl = (UINT) fl; // data loss here? char *p = "Stackoverflow Rocks"; unsigned char *up = (unsigned char *) p; ``` How does the compiler handle this type of typecasting...
Well, first note that a cast is an *explicit request to convert a value of one type to a value of another type*. A cast will also always produce a new object, which is a temporary returned by the cast operator. Casting to a reference type, however, will not create a new object. The object referenced by the value is rei...
The two C-style casts in your example are different kinds of cast. In C++, you'd normally write them ``` unsigned int uf1 = static_cast<unsigned int>(fl); ``` and ``` unsigned char* up = reinterpret_cast<unsigned char*>(p); ``` The first performs an arithmetic cast, which truncates the floating point number, so the...
How do C/C++ compilers handle type casting between types with different value ranges?
[ "", "c++", "c", "types", "casting", "compiler-construction", "" ]
I'm new to regular expressions and would appreciate your help. I'm trying to put together an expression that will split the example string using all spaces that are not surrounded by single or double quotes. My last attempt looks like this: `(?!")` and isn't quite working. It's splitting on the space before the quote. ...
I don't understand why all the others are proposing such complex regular expressions or such long code. Essentially, you want to grab two kinds of things from your string: sequences of characters that aren't spaces or quotes, and sequences of characters that begin and end with a quote, with no quotes in between, for tw...
There are several questions on StackOverflow that cover this same question in various contexts using regular expressions. For instance: * [parsings strings: extracting words and phrases](https://stackoverflow.com/questions/64904/) * [Best way to parse Space Separated Text](https://stackoverflow.com/questions/54866/) ...
Regex for splitting a string using space when not surrounded by single or double quotes
[ "", "java", "regex", "split", "" ]
Here are the specs that I'm trying to implement in a nutshell: 1) Some Alerts have to be sent on certain events in the application. 2) These Alerts have Users subscribe to them. 3) And the Users have set their own Notification preferences (e.g. Email and/or SMS). I have not been able to find an open source solution...
JMX can be a mechanism to solve this problem, but it's not the complete solution. JMX provides facilities and services to your programs to allow clients to access monitoring data as well as allowing clients to make control calls to the application. As you mentioned, one aspect of JMX is the notification system. What ...
There is an article with sample code for using JMX in your app to raise alerts: [Delivering notification with JMX](https://www.zdnet.com/article/delivering-notification-with-jmx/ "delivering-notification-with-jmx"). Once you have that working with local monitoring, you need to set these properties when executing your ...
Can we use JMX for Alerts/Notification
[ "", "java", "notifications", "jmx", "alerts", "" ]
A lot of programs log things into a text file in a format something like this: 11/19/2008 13:29:01 DEBUG Opening connection to localhost. 11/19/2008 13:29:01 DEBUG Sending login message for user 'ADMIN'. 11/19/2008 13:29:03 DEBUG Received login response 'OK' for user 'ADMIN'. ... However, I prefer something more s...
I'm not sure of any products that do that, but you could use [log4net](http://www.ondotnet.com/pub/a/dotnet/2003/06/16/log4net.html) and write your own [appender](http://logging.apache.org/log4net/release/features.html) (output handler).
Enteprise library Logging block provides different loggings formats such as xml but it is a long way to configure and deal with it
Logging component that produces xml logs
[ "", "c#", ".net", "xml", "logging", "" ]
I am writing a set of database-driven applications in PHP. These applications will run on a Linux server as its own user. Other users will likely be on the system at times, but have very controlled access. Other servers they will not have access to at all. I will also expose a limit stored procedure API to developers w...
If the machine really is being administered in the traditional Unix fashion, where J. Random user isn't off su-ing to root all the time, I'd say that filesystem permissions are your best bet. If someone gets unauthorized root access, no amount of encryption silliness is going to "secure" the connection string. I'd mar...
Here's a link to a free Apache module that helps to manage access to a password store: <http://uranus.it.swin.edu.au/~jn/linux/php/passwords.htm> It seems a little elaborate to me, and requires you run PHP under mod\_php. And still it doesn't address the possibility that unauthorized people who have access to the ser...
What's best way to secure a database connection string?
[ "", "php", "database", "linux", "security", "connection-string", "" ]
Ought I to unit test constructors? Say I have a constructor like this: ``` IMapinfoWrapper wrapper; public SystemInfo(IMapinfoWrapper mapinfoWrapper) { this.wrapper = mapinfoWrapper; } ``` Do I need to write a unit test for this construtor? I don't have any getters for the wrapper variable, so I don't need to tes...
Unit testing is about testing the public states, behaviors, and interactions of your objects. If you simply set a private field in your constructor, what is there to test? Don't bother unit-testing your simple accessors and mutators. That's just silly, and it doesn't help anyone.
Yes. If you have logic in your constructor, you should test it. Simply setting properties is not logic IMO. Conditionals, control flow, etc IS logic. **Edit:** You should probably test for when IMapinfoWrapper is null, if that dependency is required. If so, then that is logic and you should have a test that catches yo...
Is it important to unit test a constructor?
[ "", "c#", ".net", "unit-testing", "constructor", "" ]
Is it possible to send messages from a PHP script to the console in Eclipse? Has anyone attempted this already? I'm not very familiar with how the console works, so I'm not sure if there is a standardized method for communicating with it.
If you look at... Main Menu -> Run -> External Tools -> Open External Tools Dialog. In there I have set up PHP Codesniffer with the following... * Name : Code Sniffer * Location : /usr/bin/phpcs * Working Directory : ${workspace\_loc} * Arguments : --standard=${resource\_loc} That runs the codesniffer as an externa...
Any echo or print you do should go to the console automatically. This has been very unreliable for a long time, however. Please vote to have this bug fixed at: <https://bugs.eclipse.org/bugs/show_bug.cgi?id=282997>
PHP: Messaging/Logging to Eclipse Console?
[ "", "php", "eclipse", "logging", "console", "" ]
I need to store of 100-200 data in mysql, the data which would be separated by pipes.. any idea how to store it on mysql? should I use a single column or should I make many multiple columns? I don't know exactly how many data users will input. I made a form, it halted at the part where multiple data needs to be store...
You should implement your table with an ID for the source of the data. This ID will be used to group all those pieces of similar data so you don't need to know how many you have beforehand. Your table columns and data could be set up like this: ``` sourceID data -------- ---- 1 100 ...
If you have a form where this data is coming from, store each input from your form into it's own separate column. Look for relationships in your data: sounds like you have a "has many" relationship which indicates you may want a linking table where you could do a simple join query... Storing multiple data in a single...
PHP MYSQL - Many data in one column
[ "", "php", "mysql", "database-design", "" ]
is it possible to create something like [this](https://web.archive.org/web/20200805044711/http://geekswithblogs.net/AzamSharp/archive/2008/02/24/119946.aspx) i ASP.NET MVC beta 1 i have tried but the ``` override bool OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo) `...
In the blogpost you are referring to, the author states that > One way to solve this problem is by using the attribute based security as shown on this post. But then you will have to decorate your actions with the security attribute which is not a good idea. I think it's a perfectly fine way to go about it and it is ...
[Create a custom attribute](http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/)
ASP.NET MVC Authenticate
[ "", "c#", "asp.net-mvc", ".net-3.5", "c#-3.0", "" ]
I have the following values being returned in a column.. 0.250000 and 13.000000. I'd like to round the 0.250000 up to 1 and leave the 13 as is. Any easy way to do this since they both fall within the same column?
Your DBMS probably has a CEILING function. Try that.
The ceiling function will work well because you want to round to the nearest whole number. For more methods on rounding with SQL Server.... [SQL Server Rounding Methods](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/sql-server-rounding-methods)
SQL Rounding Question
[ "", "sql", "rounding", "" ]
Is is possible to have a local variable in an anonymous c# methods, i.e. in the following code I would like to perform the count only once. ``` IQueryable<Enquiry> linq = db.Enquiries; if(...) linq = linq.Where(...); if(...) linq = linq.Where(e => (x <= (from p in db.Orders where p.EnquiryId == e.Id select p).C...
I've run into a similar problem. The solution is to create a custom expression tree generating method. I asked my question on MSDN-forums. Please see the question and answer here: [Reusing Where expressions](http://social.msdn.microsoft.com/forums/en-US/linqtosql/thread/7256f2a6-71e2-40f5-9235-1bf71032f8b6/ "Reusing W...
Yes, why not?! After all it's a function, just anonymous! Example: ``` x => { int y = x + 1; return x + y; } ``` Or alternatively: ``` delegate(int x) { int y = x + 1; return x + y; } ``` So your code can be written as: ``` ... = linq.Where(e => { var count = (from p in db.Orders where p.E...
C#: Is it possible to declare a local variable in an anonymous method?
[ "", "c#", "linq-to-sql", "lambda", "anonymous-methods", "" ]
I don't need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, where xxx is between 0 and 255.
You probably want the [inet\_pton](http://man7.org/linux/man-pages/man3/inet_pton.3.html), which returns -1 for invalid AF argument, 0 for invalid address, and +1 for valid IP address. It supports both the IPv4 and future IPv6 addresses. If you still need to write your own IP address handling, remember that a standard ...
[Boost.Asio](http://www.boost.org/doc/libs/release/doc/html/boost_asio.html) provides the class [ip::address](http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/ip__address.html). If you just want to verify the string, you can use it like this: ``` std::string ipAddress = "127.0.0.1"; boost::system::e...
How do you validate that a string is a valid IPv4 address in C++?
[ "", "c++", "string", "" ]
Whilst trawling through some old code I came across something similar to the following: ``` class Base { public: virtual int Func(); ... }; class Derived : public Base { public: int Func(); // Missing 'virtual' qualifier ... }; ``` The code compiles fine (MS VS2008) with no warnings (level 4) and it ...
The `virtual` will be carried down to all overriding functions in derived classes. The only real benefit to adding the keyword is to signify your intent a casual observer of the Derived class definition will immediately know that `Func` is virtual. Even classes that extend Derived will have virtual Func methods. Refe...
Here's an interesting consequence of not needing to declare overriding functions virtual: ``` template <typename Base> struct Derived : Base { void f(); }; ``` Whether Derived's f will be virtual depends on whether Derived is instantiated with a Base with a virtual function f of the right signature.
Missing 'virtual' qualifier in function declarations
[ "", "c++", "inheritance", "virtual", "" ]
First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd. I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd. Despite not using th...
For the use of the crypt module: When GENERATING the crypted password, you provide the salt. It might as well be random to increase resistance to brute-forcing, as long as it meets the listed conditions. When CHECKING a password, you should provide the value from getpwname, in case you are on a system that supports la...
Python's crypt() is a wrapper for the system's crypt() function. From the Linux crypt() man page: ``` char *crypt(const char *key, const char *salt); key is a user’s typed password. salt is a two-character string chosen from the set [a–zA–Z0–9./]. This string is used to perturb the algorithm in one of 4096 differen...
Python crypt module -- what's the correct use of salts?
[ "", "python", "linux", "cryptography", "crypt", "" ]
I just ran across the following error: > (.gnu.linkonce.[stuff]): undefined > reference to [method] [object > file]:(.gnu.linkonce.[stuff]): > undefined reference to `typeinfo for > [classname]' Why might one get one of these "undefined reference to typeinfo" linker errors? Can anyone explain what's going on behind...
One possible reason is because you are declaring a virtual function without defining it. When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries). An e...
This can also happen when you mix `-fno-rtti` and `-frtti` code. Then you need to ensure that any class, which `type_info` is accessed in the `-frtti` code, have their key method compiled with `-frtti`. Such access can happen when you create an object of the class, use `dynamic_cast` etc. [[source](http://web.archive....
g++ undefined reference to typeinfo
[ "", "c++", "linker", "g++", "" ]
Our development process is highly automated via a raft of bash and php scripts (including subversion hook scripts.) These scripts do a number of things to integrate with our Bugzilla 3.0 installation. But the current integration approach is a bunch of SQL calls which update the bugzilla database directly - which obvio...
According to the Bugzilla WebServices API, some of the features needed (e.g. changing a bug status) are not yet available, so for the time being, direct SQL calls seem the most appropriate option. The database schema has not changed significantly between version 3.0 and 3.2 so this is a practical way forward.
FYI, in the Bugzilla 3.2 distribution, there is a `contrib/bz_webservice_demo.pl` file whose intent is to "Show how to talk to Bugzilla via XMLRPC".
How can I update Bugzilla bugs from bash and php scripts?
[ "", "php", "web-services", "bash", "integration", "bugzilla", "" ]
I have XML files in a directory that I wish to get over to a webservice on a server that will validate them and return a true/false as to whether they are valid in construct and values etc. Reason for server side processing is that the validation rules may change from time to time and need to adjust in one place as opp...
You might consider using something like a WCF service and streaming the xml up using the GZipStream. I am doing something similar to this and it is working pretty well.
Wouldn't a normal string be enough? It's overkill to serialize / deserialize an entire XDoc instance in my opinion. Of course, you can also zip the entire thing to reduce the size of the requests.
Best approach for passing XML to a webservice?
[ "", "c#", "xml", "web-services", "xml-serialization", "" ]
During development (and for debugging) it is very useful to run a Java class' *public static void main(String[] argv)* method directly from inside Eclipse (using the Run As context menu). Is there a similarily quick way to specify command line parameters for the run? What I do now is go to the "Run Dialog", click thro...
This answer is based on Eclipse 3.4, but should work in older versions of Eclipse. When selecting Run As..., go into the run configurations. On the Arguments tab of your Java run configuration, configure the variable ${string\_prompt} to appear (you can click variables to get it, or copy that to set it directly). Ev...
Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do: 1. Run your class once as is. 2. Go to `Run -> Run configurations...` 3. From the lefthand list, select your class from the...
Invoking Java main method with parameters from Eclipse
[ "", "java", "eclipse", "main-method", "" ]
I have a Customer class. ``` public class Customer { private string _id; private string _name; // some more properties follow ``` I am inheriting the EqualityComparer form MyEqualityComparer(of Customer). This I am intending to use in LINQ queries. MyEqualityComparer is intended for partial check betw...
See [this question on hashcodes](https://stackoverflow.com/questions/263400) for a pretty simple way to return one hashcode based on multiple fields. Having said that, I wouldn't derive from `EqualityComparer<T>` myself - I'd just implement `IEqualityComparer<T>` directly. I'm not sure what value `EqualityComparer<T>`...
You should see it from the perspective of possible "collisions", e.g. when two different objects get the same hash code. This could be the case with such pairs as "1,2any" and "12, any", the values in the pairs being "id" and "name". If this is not possible with your data, you're good to go. Otherwise you can change it...
Inheriting the equality comparer
[ "", "c#", ".net", "linq", "" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
If you're looking for something lightweight checkout [schedule](https://github.com/dbader/schedule): ``` import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) while 1: schedule.run_pending() ...
You could just use normal Python argument passing syntax to specify your crontab. For example, suppose we define an Event class as below: ``` from datetime import datetime, timedelta import time # Some utility classes / functions first class AllMatch(set): """Universal set - match everything""" def __contains...
How do I get a Cron like scheduler in Python?
[ "", "python", "cron", "scheduled-tasks", "" ]
Is it acceptable to add types to the `std` namespace. For example, I want a TCHAR-friendly string, so is the following acceptable? ``` #include <string> namespace std { typedef basic_string<TCHAR> tstring; } ``` Or should I use my own namespace?
No ... part of the point of a namespace is to prevent name collisions on upgrade. If you add things to the std namespace, then your code might break with the next release of the library if they decide to add something with the same name.
Only specializations are allowed. So for example, you are allowed to specialize `std::numeric_limits` for your type. And this of course must happen in namespace `std::`. But your typedef isn't a specialization so that's causing undefined behavior.
Adding types to the std namespace
[ "", "c++", "stl", "namespaces", "" ]
I wrote a program out, which was all in one file, and the methods were forward declared in a header. The program initially worked perfectly when it was in one file. But when I separated the program, I kept getting random occurrences for the destructor of one of the classes which was declared in the header file. I have...
``` class A { public: virtual ~A() { count --; if (count == 0) { // this is the last one, do something } } protected: static int count; }; class B : public A{ public: B(); }; ``` And then, in one and only one of your source files you need to put the following. It should go in the source fi...
You must define the constructor in A (all of them) to increment the count. Note unless you define them the compiler automatically generate the following four methods: * Default Constructor (if no other constructor is defined) * Default Destructor * Copy Constructor * Assignment operator The following code overrides ...
Static Variables, Separate Compilation
[ "", "c++", "file", "variables", "static", "" ]
I am loading JSON data to my page and using `appendTo()` but I am trying to fade in my results, any ideas? ``` $("#posts").fadeIn(); $(content).appendTo("#posts"); ``` I saw that there is a difference between `append` and `appendTo`, on the documents. I tried this as well: ``` $("#posts").append(content).fadeIn(); ...
If you hide the content before you append it and chain the fadeIn method to that, you should get the effect that you're looking for. ``` // Create the DOM elements $(content) // Sets the style of the elements to "display:none" .hide() // Appends the hidden elements to the "posts" element .appendTo('#posts') //...
I don't know if I fully understand the issue you're having, but something like this should work: HTML: ``` <div id="posts"> <span id="post1">Something here</span> </div> ``` Javascript: ``` var counter=0; $.get("http://www.something/dir", function(data){ $('#posts').append('<span style="display:none"...
Using fadein and append
[ "", "javascript", "jquery", "fade", "" ]
I'm trying to learn about Expression trees, and I've created a method that takes an ``` Expression<Func<bool>> ``` and executes it if it satisfies some conditions - see the code below. ``` private static void TryCommand(Expression<Func<bool>> expression) { var methodCallExpression = expre...
The target of the method call is an instance of MyClass, but the delegate itself isn't the method call. It's something which will perform the method call when it's executed. If you look at func.Target, you'll see it's a [System.Runtime.CompilerServices.ExecutionScope](http://msdn.microsoft.com/en-us/library/system.run...
Akash, once you have a MethodCallExpression it's simple to recover the method caller. You must recover the MemberExpression and build an Expression tree that evaluates it. See the code below: ``` MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body; MemberExpression memberExpression = (Me...
Accessing calling object from MethodCallExpression
[ "", "c#", "" ]
If both get and set are compulsory in C# automatic properties, why do I have to bother specifying "get; set;" at all?
**ERROR: A property or indexer may not be passed as an out or ref parameter** If you didn't specify `{get; set;}` then the compiler wouldn't know if it's a field or a property. This is important becasue while they "look" identical the compiler treats them differently. e.g. Calling "InitAnInt" on the property raises an...
Because you might want a read-only property: ``` public int Foo { get; private set; } ``` Or Write-only property: ``` public int Foo { private get; set; } ```
C# Automatic Properties - Why Do I Have To Write "get; set;"?
[ "", "c#", "c#-3.0", "automatic-properties", "" ]
It is advised to use override instead of new key word in C#. Why that rule?
"new" means you've got two completely different methods as far as the CLR is concerned - they happen to have the same name, but they're unrelated in terms of inheritance. That means that if you run: ``` Base b = new Derived(); Derived d = new Derived(); b.MyMethod(); // Calls Base.MyMethod d.MyMethod(); // Calls Deriv...
I'm still trying to work out what the use case is for "new" aside from horrid hackery.
How to chose between new and override in C#?
[ "", "c#", "" ]
I have a number of icons used throughout an application - let's take ok/cancel icons as an example. At the moment they might be a tick and a cross (tick.png, cross.png) but I may want to replace them in future. Also, I would like to keep the resource path in one place. Is this ok: ``` public class Icons { public ...
If you want to keep you icons as static constants, I would extract the instantiation of the ImageIcon objects into a static method; ``` public static final Icon ok = icon("ok.png"); private static Icon icon(String path) { URL resource = Icons.class.getResource("/icons/" + path); if (resource == null) { ...
I see two problems with that, both might be acceptable: 1. It will get hard to debug if your icons are not found or can't be loaded for some reasons. Code that runs in static initializers can be tricky, because it's easy to "loose" the exception. 2. The class will probably never be unloaded and therefore the resource ...
Java icon constants - Are static constants ok?
[ "", "java", "icons", "constants", "" ]
I want to write out a text file. Instead of the default UTF-8, I want to write it encoded as ISO-8859-1 which is code page 28591. I have no idea how to do this... I'm writing out my file with the following very simple code: ``` using (StreamWriter sw = File.CreateText(myfilename)) { sw.WriteLine("my text..."); ...
``` using System.IO; using System.Text; using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant)) { sw.WriteLine("my text..."); } ``` An alternate way of getting your encoding: ``` using System.IO; using System.Text; using (var sw = new StreamWriter(F...
Simple! ``` System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591)); ```
How do I write out a text file in C# with a code page other than UTF-8?
[ "", "c#", "encoding", "utf-8", "iso-8859-1", "" ]
The best I can come up with for now is this monstrosity: ``` >>> datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12,...
I think you can shave off a few method calls if you do it like this: ``` >>> from datetime import datetime >>> datetime.now(pytz.timezone("Australia/Melbourne")) \ .replace(hour=0, minute=0, second=0, microsecond=0) \ .astimezone(pytz.utc) ``` BUT… there is a bigger problem than aesthetics in ...
[@hop's answer](https://stackoverflow.com/a/381788/4279) is wrong on the day of transition from Daylight Saving Time (DST) e.g., Apr 1, 2012. To fix it [`tz.localize()`](http://pytz.sourceforge.net/#localized-times-and-date-arithmetic) could be used: ``` tz = pytz.timezone("Australia/Melbourne") today = datetime.now(t...
How do I get the UTC time of "midnight" for a given timezone?
[ "", "python", "datetime", "timezone", "utc", "pytz", "" ]
If I create a UserControl and add some objects to it, how can I grab the HTML it would render? ex. ``` UserControl myControl = new UserControl(); myControl.Controls.Add(new TextBox()); // ...something happens return strHTMLofControl; ``` I'd like to just convert a newly built UserControl to a string of HTML.
You can render the control using `Control.RenderControl(HtmlTextWriter)`. Feed `StringWriter` to the `HtmlTextWriter`. Feed `StringBuilder` to the `StringWriter`. Your generated string will be inside the `StringBuilder` object. Here's a code example for this solution: ``` string html = String.Empty; using (TextWri...
``` //render control to string StringBuilder b = new StringBuilder(); HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b)); this.LoadControl("~/path_to_control.ascx").RenderControl(h); string controlAsString = b.ToString(); ```
How do I get the HTML output of a UserControl in .NET (C#)?
[ "", "c#", "html", ".net", "user-controls", "" ]
I'm using python and I need to map locations like "Bloomington, IN" to GPS coordinates so I can measure distances between them. What Geocoding libraries/APIs do you recommend? Solutions in other languages are also welcome.
The Google Maps API [supports geocoding](http://code.google.com/apis/maps/documentation/services.html#Geocoding), and the Python Cookbook has a simple [example](http://code.activestate.com/recipes/498128/) of accessing it from Python (although the recipe doesn't use the API directly, just simple maps.google.com URLs).
[Geopy](http://code.google.com/p/geopy/) lets you choose from several geocoders (including Google, Yahoo, Virtual Earth).
Geocoding libraries
[ "", "python", "api", "rest", "geocoding", "" ]
I have a class with two methods defined in it. ``` public class Routines { public static method1() { /* set of statements */ } public static method2() { /* another set of statements.*/ } } ``` Now I need to call method1() from method2() Which one the following approaches is better? ...
While I agree with the existing answers that this is primarily a style issue, it is enough of a style issue that both Eclipse and IntelliJ's code critics will flag "non-static references to static methods" in code that does not use the `Classname.method()` style. I made it a habit to emphasize *intent* by using the cl...
I'd go with the first method. In my eyes, it's the equivalent of: ``` public void method2() { method1(); } ``` and: ``` public void method2() { this.method1(); } ``` I don't know many people who explicitly call **this** when calling another method in a class. So personally my taste is option 1 - no need to ...
calling method Versus class.method
[ "", "java", "coding-style", "" ]
I'd like to split a string using one or more separator characters. E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"]. At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g. ``` def my_split(string, split_chars): if isinstance(string...
``` >>> import re >>> re.split('[ .]', 'a b.c') ['a', 'b', 'c'] ```
This one replaces all of the separators with the first separator in the list, and then "splits" using that character. ``` def split(string, divs): for d in divs[1:]: string = string.replace(d, divs[0]) return string.split(divs[0]) ``` output: ``` >>> split("a b.c", " .") ['a', 'b', 'c'] >>> split("a...
split string on a number of different characters
[ "", "python", "string", "split", "" ]
I'm trying to do a simple erase and keep getting errors. Here is the snippet of code for my erase: ``` std::list<Mine*>::iterator iterMines = mines.begin(); for(int i = oldSizeOfMines; i >0 ; i--, iterMines++) { if(player->distanceFrom(*iterMines) < radiusOfOnScreen) { onScreen.push_back(*iterMines); ...
The problem is you are trying to use the iterator of mines as an iterator in the onScreen list. This will not work. Did you mean to call mines.erase(iterMines) instead of onScreen.erase(iterMines)?
``` std::list<Mine*>::iterator iterMines = mines.begin(); for(int i = oldSizeOfMines; i >0 ; i--, iterMines++) { if(player->distanceFrom(*iterMines) < radiusOfOnScreen) { onScreen.push_back(*iterMines); iterMines = onScreen.erase(iterMines); iterMines--; ...
Help with C++ List erase function
[ "", "c++", "iterator", "" ]
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using? Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the ap...
``` >>> import os >>> os.times() (1.296875, 0.765625, 0.0, 0.0, 0.0) >>> print os.times.__doc__ times() -> (utime, stime, cutime, cstime, elapsed_time) Return a tuple of floating point numbers indicating process times. ``` From the (2.5) manual: > times( ) > > Return a 5-tuple of floating point numbers indicating ac...
By using [psutil](http://code.google.com/p/psutil): ``` >>> import psutil >>> p = psutil.Process() >>> p.cpu_times() cputimes(user=0.06, system=0.03) >>> p.cpu_percent(interval=1) 0.0 >>> ```
CPU Usage Per Process in Python
[ "", "python", "monitoring", "cpu-usage", "" ]
I have an application that has to deal with getting "special" characters in its URL (like &, +, %, etc). When I'm sending a request to the application using these characters (of course I'm sending them escaped) I'm getting "Bad Request" response code with the message "ASP.NET detected invalid characters in the URL". Tr...
I ran into the same problem (creating an IHttpHandler that needed to receive requests with special characters in the URL). I had to do two things to fix it: 1. Create the following DWORD registration entry with a value of 1: `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\VerificationCompatibility` 2. In the web.config...
I had the same problem and got it working by setting validateRequest="false" as well as requestValidationMode="2.0", like below. No registry edits. ``` <system.web> <httpRuntime requestValidationMode="2.0" /> ... <pages ... validateRequest="false" /> </system.web> ```
Canceling request validation using HttpHandler on IIS 7
[ "", "c#", ".net", "asp.net", "iis", "iis-7", "" ]
I'm using the appengine webapp framework ([link](http://code.google.com/appengine/docs/webapp/)). Is it possible to add Django middleware? I can't find any examples. I'm currently trying to get the FirePython middleware to work ([link](http://github.com/woid/firepython/tree/master)).
It's easy: You create the WSGI application as per normal, then wrap that application in your WSGI middleware before executing it. See [this code](http://github.com/Arachnid/bloog/blob/bb777426376d298765d5dee5b88f53964cc6b5f3/main.py#L71) from Bloog to see how firepython is added as middleware.
The GAE webapp framework does not map one to one to the Django framework. It would be hard to do what you want without implementing some kind of adapter yourself, I do not know of any third party handler adapters to do this. That said, I generally use the app-engine-patch so I can use the latest 1.0.2 Django release w...
How to adding middleware to Appengine's webapp framework?
[ "", "python", "django", "google-app-engine", "middleware", "django-middleware", "" ]
I am developing a prototype for a game, and certain gameplay rules are to be defined in an ini file so that the game designers can tweak the game parameters without requiring help from me in addition to a re-compile. This is what I'm doing currently: ``` std::ifstream stream; stream.open("rules.ini"); if (!stream.is_...
You are assuming that the **working directory** is the directory that your executable resides in. That is a bad assumption. Your executable can be run from any working directory, so it's usually a bad idea to hard-code relative paths in your software. If you want to be able to access files relative to the location of...
Is the scope of your open stream correct. "rules.ini" isn't a full path so it has to be relative so what is it relative to. Or do you need to use full path there.
std::ifstream::open() not working
[ "", "c++", "stl", "iostream", "" ]
Is there any good way to unit test destructors? Like say I have a class like this (contrived) example: ``` class X { private: int *x; public: X() { x = new int; } ~X() { delete x; } int *getX() {return x;} const int *getX() const {return x;} }; ``` Is there any...
There may be something to be said for dependency injection. Instead of creating an object (in this case an int, but in a non-contrived case more likely a user-defined type) in its constructor, the object is passed as a parameter to the constructor. If the object is created later, then a factory is passed to the constru...
I think your problem is that your current example isn't testable. Since you want to know if `x` was deleted, you really need to be able to replace `x` with a mock. This is probably a bit OTT for an int but I guess in your real example you have some other class. To make it testable, the `X` constructor needs to ask for ...
Unit testing destructors?
[ "", "c++", "unit-testing", "destructor", "cppunit", "" ]
I have an application which is a relatively old. Through some minor changes, it builds nearly perfectly with Visual C++ 2008. One thing that I've noticed is that my "debug console" isn't quite working right. Basically in the past, I've use `AllocConsole()` to create a console for my debug output to go to. Then I would ...
## Updated Feb 2018: Here is the latest version of a function which fixes this problem: ``` void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr) { // Re-initialize the C runtime "FILE" handles with clean handles bound to "nul". We do this because it has been // observed that the f...
I'm posting a portable solution in answer form so it can be accepted. Basically I replaced `cout`'s `streambuf` with one that is implemented using c file I/O which does end up being redirected. Thanks to everyone for your input. ``` class outbuf : public std::streambuf { public: outbuf() { setp(0, 0); ...
Redirecting cout to a console in windows
[ "", "c++", "winapi", "" ]
How do I set environment variables from Java? I see that I can do this for subprocesses using [`ProcessBuilder`](http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html). I have several subprocesses to start, though, so I'd rather modify the current process's environment and let the subprocesses inherit ...
> (Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?) I think you've hit the nail on the head. A possible way to ease the burden would be to factor out a method ``` void setUpEnvironment(ProcessBuilder builder) { Map<String, String> env =...
For use in scenarios where you need to set specific environment values for unit tests, you might find the following hack useful. It will change the environment variables throughout the JVM (so make sure you reset any changes after your test), but will not alter your system environment. I found that a combination of th...
How do I set environment variables from Java?
[ "", "java", "environment-variables", "" ]
Is there a way to detect if a mouse button is currently down in JavaScript? I know about the "mousedown" event, but that's not what I need. Some time AFTER the mouse button is pressed, I want to be able to detect if it is still pressed down. Is this possible?
Regarding [Pax' solution](https://stackoverflow.com/a/322650/2750743): it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(. The correct code should be like that: ``` var mouseDown = 0; document.body.onmousedown = function() { ++mouseDown; } document.body.o...
This is an old question, and the answers here seem to mostly advocate for using `mousedown` and `mouseup` to keep track of whether a button is pressed. But as others have pointed out, `mouseup` will only fire when performed within the browser, which can lead to losing track of the button state. However, [MouseEvent](h...
JavaScript: Check if mouse button down?
[ "", "javascript", "input", "mouse", "user-input", "input-devices", "" ]
This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated: I have a directory full of files where the filenames are hash values like this: ``` fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee ``` These files have dif...
Here's mimetypes' version: ``` #!/usr/bin/env python """It is a `filename -> filename.ext` filter. `ext` is mime-based. """ import fileinput import mimetypes import os import sys from subprocess import Popen, PIPE if len(sys.argv) > 1 and sys.argv[1] == '--rename': do_rename = True del sys.argv[1] else:...
You can use ``` file -i filename ``` to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find a [list of MIME-types](http://www.iana.org/assignments/media-types/media-types.xhtml) and [example file extensions](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs...
How to add file extensions based on file type on Linux/Unix?
[ "", "python", "linux", "bash", "unix", "shell", "" ]
I need to pick up list items from an list, and then perform operations like adding event handlers on them. I can think of two ways of doing this. HTML: ``` <ul id="list"> <li id="listItem-0"> first item </li> <li id="listItem-1"> second item </li> <li id="listItem-2"> third item </li> <...
You can avoid adding event handlers to each list item by adding a single event handler to the containing element (the unordered list) and leveraging the concept of event bubbling. In this single event handler, you can use properties of the event object to determine what was clicked. It appears that you are wanting to ...
If you opt to use jQuery it comes as simple as: ``` $('ul#list li').click(function () { var i = this.id.split('-').pop(); alert( i ); }); ```
Identifying list item index - which is a better approach?
[ "", "javascript", "html", "dom", "" ]
I am thinking about something like this: ``` public static <T extends Comparable<T>> T minOf(T...ts){ SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts)); return set.first(); } public static <T extends Comparable<T>> T maxOf(T...ts){ SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts)); retur...
What's wrong with [Collections.max](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#max(java.util.Collection))? And why do you care about null safety? Are you sure you want to allow nulls to be in your Collection?
If you really need to exclude "null" from the result, and you can't prevent it from being in your array, then maybe you should just iterate through the array with a simple loop and keep track of the "min" and "max" in separate variables. You can still use the "compare()" method on each object to compare it with your cu...
What is the best way to get min and max value from a list of Comparables that main contain null values?
[ "", "java", "collections", "comparable", "" ]
I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D If you don't know any (I've done my google search...), yacc/bison is the only way? Thx
None of these listed in [TheFreeCountry](http://www.thefreecountry.com/compilers/basic.shtml) are acceptable? None of them are in Python, but I should think that starting from [XBLite](http://www.xblite.com/) might be more helpful than starting from Yacc/Bison/[PLY](http://www.dabeaz.com/ply/). Also, [Vb2py](http://vb...
[PLY](http://www.dabeaz.com/ply/) is a great parser-creation library for Python. It has a simple BASIC interpreter as one of its example scripts. You could start there.
Is there an OpenSource BASIC interpreter in Ruby/Python?
[ "", "python", "ruby", "interpreter", "" ]
I need to do a LINQ2DataSet query that does a join on more than one field (as ``` var result = from x in entity join y in entity2 on x.field1 = y.field1 and x.field2 = y.field2 ``` I have yet found a suitable solution (I can add the extra constraints to a where clause, but this is far from a suita...
The solution with the anonymous type should work fine. LINQ *can* only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query. If you don't like the version with the anonymous type for some specific reason, you should explain that rea...
``` var result = from x in entity join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 } ```
How to do joins in LINQ on multiple fields in single join
[ "", "c#", "linq", "join", "" ]
**For a particular segment of Java code, I'd like to measure:** * **Execution time (most likely *thread execution time*)** * **Memory usage** * **CPU load (specifically attributable to the code segment)** I'm a relative Java novice and am not familiar with how this might be achieved. I've been referred to [JMX](http:...
Profiling may be an easier option since you don't require in-production stats. Profiling also doesn't require code modification. VisualVM (which ships w/ the JDK 1.6.06+) is a simple tool. If you want something more in-depth I'd go with Eclipse TPTP, Netbeans profiler, or JProfiler(pay). If you want to write you own, ...
With the ThreadMXBean you can get CPU usage of individual threads and cpu time consumed rather than elapse time which may be useful. However, its often simpler to use a profiler as this process often generates a lot of data and you need a good visualisation tool to see what is going on. I use Yourkit as I find it eas...
Measuring Java execution time, memory usage and CPU load for a code segment
[ "", "java", "performance", "monitoring", "jmx", "measurement", "" ]
I need to put an LDAP contextSource into my Java EE container's JNDI tree so it can be used by applications inside the container. I'm using Spring-LDAP to perform queries against ORACLE OVD. For development, I simply set up the contextSource in the Spring xml configuration file. For production, however, I need to be a...
Specifically in reference to the actual pooling of LDAP connections, if you are using the built in JNDI LDAP provider, the connections are pooled already using semantics similar to JDBC data sources where separate pools are maintained for different LDAP URLs and security properties. When creating a JNDI `DirContext`, ...
Any chance you can setup a dev version of LDAP and use that? Then you can use a jndi.properties file, which would be environment specific, but agnostic to your system. Edit: the difference here is that when you build your app, your admin can deploy it to the production system, thereby protecting the precious ldap pass...
How can I set up an LDAP connection pool in a Java EE Container?
[ "", "java", "spring", "jakarta-ee", "ldap", "jndi", "" ]
I have a gallery I quickly coded up for a small site, and under Firefox 3 and Safari 3 works fine. But when I test on my old best friend IE7, it seems to not fire the imageVar.onload = function() { // code here }.. which I want to use to stop the load effect and load the image. Please bear in mind... * I know the thu...
For successful use of Image.onload, you must register the event handler method before the src attribute is set. **Related Information in this Question:** **[Javascript callback for Image Loading](https://stackoverflow.com/questions/280049/javascript-callback-for-knowing-when-an-image-is-loading#280087)**
Cross browser event support is not so straightforward due to implementation differences. Since you are using jQuery at your site, you are better off using its events methods to normalize browser support: instead of: ``` window.load = function(){ //actions to be performed on window load } imageViewer.image....
JavaScript & IE7 - Why won't my *.onload = function() { } fire?
[ "", "javascript", "xhtml", "internet-explorer-7", "" ]
I'm trying to attach a PDF attachment to an email being sent with System.Net.Mail. The attachment-adding part looks like this: ``` using (MemoryStream pdfStream = new MemoryStream()) { pdfStream.Write(pdfData, 0, pdfData.Length); Attachment a = new Attachment(pdfStream, string.Format("Receipt_{0}_{1}...
Have you tried doing a `pdfStream.Seek(0,SeekOrigin.Begin)` before creating the attachment to reset the stream to the beginning?
Have you checked to make sure that the PDF document isn't already corrupted in the pdfData array? Try writing that to a file then opening it.
corrupted email attachments in .NET
[ "", "c#", ".net", "smtp", "" ]
Does python have the ability to create dynamic keywords? For example: ``` qset.filter(min_price__usd__range=(min_price, max_price)) ``` I want to be able to change the **usd** part based on a selected currency.
Yes, It does. Use `**kwargs` in a function definition. Example: ``` def f(**kwargs): print kwargs.keys() f(a=2, b="b") # -> ['a', 'b'] f(**{'d'+'e': 1}) # -> ['de'] ``` But why do you need that?
If I understand what you're asking correctly, ``` qset.filter(**{ 'min_price_' + selected_currency + '_range' : (min_price, max_price)}) ``` does what you need.
Dynamic Keyword Arguments in Python?
[ "", "python", "" ]
I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec\_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively? ``` ssh = para...
The full paramiko distribution ships with a lot of good [demos](https://github.com/paramiko/paramiko/tree/master/demos). In the demos subdirectory, `demo.py` and `interactive.py` have full interactive TTY examples which would probably be overkill for your situation. In your example above `ssh_stdin` acts like a stand...
I had the same problem trying to make an interactive ssh session using [ssh](https://github.com/bitprophet/ssh/), a fork of Paramiko. I dug around and found this article: **Updated link** (last version before the link generated a 404): <http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-p...
Running interactive commands in Paramiko
[ "", "python", "ssh", "paramiko", "" ]
I'm have a ADO DataSet that I'm loading from its XML file via ReadXml. The data and the schema are in separate files. Right now, it takes close to 13 seconds to load this DataSet. I can cut this to 700 milliseconds if I don't read the DataSet's schema and just let ReadXml infer the schema, but then the resulting DataS...
It's not an answer, exactly (though it's better than nothing, which is what I've gotten so far), but after a long time struggling with this problem I discovered that it's completely absent when my program's not running inside Visual Studio. Something I didn't mention before, which makes this even more mystifying, is t...
I will try to give you a performance comparison between storing data in text plain files and xml files. The first function creates two files: one file with 1000000 records in plain text and one file with 1000000 (same data) records in xml. First you have to notice the difference in file size: ~64MB(plain text) vs ~102...
How do I improve performance of DataSet.ReadXml if I'm using a schema?
[ "", "c#", "performance", "ado.net", "dataset", "readxml", "" ]
This is a follow-up question to [this one](https://stackoverflow.com/questions/369220/why-should-you-not-use-number-as-a-constructor). Take a look at these two examples: ``` var number1 = new Number(3.123); number1 = number1.toFixed(2); alert(number1); var number2 = 3.123; number2 = number2.toFixed(2); alert(number...
In JavaScript, everything is an object, even functions and integers. It is perfectly OK to think of methods on numbers and strings. For example: ``` >>> (3.123).toString() "3.123" ```
Technically, no. You can treat it like it is a method of the primative value, because number2 is will be converted to a `Number` object, then `toFixed` is gets called on that object. The same thing happens when you call methods on strings. To illustrate what's happening, you can run this code: ``` Object.prototype.t...
Question about object.method in JavaScript
[ "", "javascript", "oop", "methods", "" ]
Let's start with the following snippet: ``` Foreach(Record item in RecordList){ .. item = UpdateRecord(item, 5); .. } ``` The UpdateRecode function changes some field of item and returns the altered object. In this case the compiler throws an exception saying that the item can not be updated in a foreach iterat...
If you need to update a collection, don't use an iterator pattern, like you said, its either error prone, or smells bad. I find that using a for loop with an index a bit clearer in this situation, as its very obvious what you are trying to do that way.
The compiler is complaining that you can't update the *collection*, not the record. By doing item = UpdateRecord, you are reassigning the iterator variable item. I disagree that UpdateRecord(item, 5) is in any way unreadable - but if it makes you feel better, an extension method may make it more clear that you are cha...
Changing item in foreach thru method
[ "", "c#", "methods", "foreach", "" ]
I have a textbox with an onchange event. Why does this event not fire when the user uses the autocomplete feature to populate the textbox? I am working with Internet Explorer. Is there a standard and relatively simple solution to workaround this problem, without me having to disable the autocomplete feature?
Last time I had that issue, I ended up using the `onpropertychange` event for Internet Explorer instead. I read about that [here on MSDN](http://msdn.microsoft.com/en-us/library/ms533032(VS.85).aspx): it is the recommended way to get around it.
I've encountered this annoying feature before and my solution at the time was to use the onfocus event to record the current value of the text box, and then use the onblur event to check whether the current value now matches the value saved during onfocus. For example ``` <input type="text" name="txtTest" value="" onf...
Why does the javascript onchange event not fire if autocomplete is on?
[ "", "asp.net", "javascript", "" ]
I am building a small wpf app in C#. When a button gets clicked a third party dll function constructs a tree like object. This object is bound to a treeview. This works fine but takes a bit of time to load. As the dll function constructs the object it prints progress info to the console. I want to redirect this into a ...
You haven't included the code that is loading the data for the `TreeView`, but I'm guessing it's being done on the UI thread. If so, this will block any UI updates (including changes to the `TextBlock`) until it has completed.
So after doing some reading on the WPF threading model ( <http://msdn.microsoft.com/en-us/library/ms741870.aspx> ) I finally got it to refresh by calling Dispatcher Invoke() with Dispatch priority set to Render. As Kent suggested above UI updates in the dispatcher queue were probably low priority. I ended up doing some...
WPF problems refreshing textblock bound to console.stdout
[ "", "c#", "wpf", "user-interface", "console", "refresh", "" ]
I am using Hibernate 3.x, MySQL 4.1.20 with Java 1.6. I am mapping a Hibernate Timestamp to a MySQL TIMESTAMP. So far so good. The problem is that MySQL stores the TIMESTAMP in seconds and discards the milliseconds and I now need millisecond precision. I figure I can use a BIGINT instead of TIMESTAMP in my table and co...
Also, look at creating a custom Hibernate Type implementation. Something along the lines of (psuedocode as I don't have a handy environment to make it bulletproof): ``` public class CalendarBigIntType extends org.hibernate.type.CalendarType { public Object get(ResultSet rs, String name) { return cal = new ...
For those who are still interested in this issue: MySQL 5.6.4 supports timestamps with precision. Subclassing MySQL5Dialect to override the used MySQL type solves the problem.
How do I map a hibernate Timestamp to a MySQL BIGINT?
[ "", "java", "mysql", "hibernate", "orm", "jdbc", "" ]
**What in C#.NET makes it more suitable** for some projects than VB.NET? Performance?, Capabilities?, Libraries/Components?, Reputation?, Reliability? Maintainability?, Ease? --- Basically anything **C# can do, that is impossible using VB,** or vice versa. Things you just **have to consider** when choosing C#/VB for...
C# and VB are basically the same however there are some minor differences. Aside from the obvious grammar differences you have the following differences: 1. C# can call unsafe code 2. VB has optional parameters (Coming in C#4.0) 3. VB is easier to use when making late bound calls (Coming in C# 4.0) This and number mak...
I think this blog post by Kathleen Dollard provides an excellent overview to the question: [**What a C# Coder Should Know Before They Write VB**](http://msmvps.com/blogs/kathleen/archive/2008/07/25/what-a-c-coder-should-know-before-they-write-vb-updated.aspx) and her first advice is: > 1) Get over the respect thing ...
C#'s edge over VB
[ "", "c#", ".net", "vb.net", "" ]
I want to examine the contents of a std::vector in gdb but I don't have access to \_M\_impl because I'm using icc, not gcc, how do I do it? Let's say it's a std::vector for the sake of simplicity. There is a very nice answer [here](https://stackoverflow.com/questions/253099/how-do-i-print-the-elements-of-a-c-vector-in...
Not sure this will work with your vector, but it worked for me. ``` #include <string> #include <vector> int main() { std::vector<std::string> vec; vec.push_back("Hello"); vec.push_back("world"); vec.push_back("!"); return 0; } ``` gdb: ``` (gdb) break source.cpp:8 (gdb) run (gdb) p vec.begin() $...
Generally when I deal with the container classes in a debugger, I build a reference to the element, as a local variable, so it is easy to see in the debugger, without mucking about in the container implementation. Here is a contrived example. ``` vector<WeirdStructure> myWeird; /* push back a lot of stuff into the ...
How do I examine the contents of an std::vector in gdb, using the icc compiler?
[ "", "c++", "stl", "vector", "gdb", "icc", "" ]
First a little intro: Last year i wrote this <http://dragan.yourtree.org/code/canvas-3d-graph/> Now, i want to make complete rewrite of it, because that old version have some limitations, for example: sometimes it happens that bars are not visible, because they are drawn one behind another. In this old version there...
If this is specifically for a JavaScript related project then I understand but if you are simply doing this to grasp the basics of 3d rendering there might be more mature platforms out there for you. In any case.. Links that might be useful to your learning: * [Prototyping A Simple 3d Renderer In JavaScript](http://...
Just a couple of suggestions, but probably not exactly what you're looking for: I suggest that you take a look at Jacob Seidelin's canvas examples at nihilogic.dk : [<http://blog.nihilogic.dk/search/label/canvas>](http://blog.nihilogic.dk/search/label/canvas) . If you're willing to abandon canvas and go with an exist...
What is the best online resource for 3D rendering in JavaScript?
[ "", "javascript", "3d", "rendering", "" ]
I've been lately trying to learn more and generally test Java's serialization for both work and personal projects and I must say that the more I know about it, the less I like it. This may be caused by misinformation though so that's why I'm asking these two things from you all: **1:** On byte level, how does serializ...
I would personally try to avoid Java's "built-in" serialization: * It's not portable to other platforms * It's not hugely efficient * It's fragile - getting it to cope with multiple versions of a class is somewhat tricky. Even changing compilers can break serialization unless you're careful. For details of what the a...
The main advantage of serialization is that it is extremely easy to use, relatively fast, and preserves actual Java object meshes. But you have to realize that it's not really meant to be used for storing data, but mainly as a way for different JVM instances to communicate over a network using the RMI protocol.
How does Java's serialization work and when it should be used instead of some other persistence technique?
[ "", "java", "serialization", "" ]
I am using sfOpenID plugin for Symfony, which doesn't support OpenID 2.0. That means, for example, that people using Yahoo! OpenID can't login to my site. There is an OpenID 2.0 plugin that works with sfGuard, but I am not using nor planning to use sfGuard. Plus, it requires to install Zend framework, too, which is an...
I think you've covered all your options with sfOpenID and taOpenIDsfGuardPlugin for Symfony's plugins. Without studying OpenID's specs in detail though, you could try one of those PHP libraries (<http://wiki.openid.net/Libraries>) by dropping it in your lib and connecting to a `sfUser`, or whatever you're using for au...
There is an easier way. JanRain offers OpenID (and facebook) as a service <http://rpxnow.com> . Vastly easier/quicker than going native with the libraries.
Is there an OpenID 2.0 plugin for Symfony?
[ "", "php", "symfony1", "openid", "" ]
Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stored in a string class in my application. But I would like to save multiple files in a single self-contained archive. They can all be in the root of t...
Use `ZipEntry` and `PutNextEntry()` for this. The following shows how to do it for a file, but for an in-memory object just use a MemoryStream ``` FileStream fZip = File.Create(compressedOutputFile); ZipOutputStream zipOStream = new ZipOutputStream(fZip); foreach (FileInfo fi in allfiles) { ZipEntry entry = new Zi...
Using SharpZipLib for this seems pretty complicated. This is so much easier in [DotNetZip](http://www.codeplex.com/DotNetZip). In v1.9, the code looks like this: ``` using (ZipFile zip = new ZipFile()) { zip.AddEntry("Readme.txt", stringContent1); zip.AddEntry("readings/Data.csv", stringContent2); zip.AddE...
Create Zip archive from multiple in memory files in C#
[ "", "c#", "compression", "zip", "" ]
I am new to Python, and I'm working on writing some database code using the `cx_Oracle` module. In the [cx\_Oracle documentation](http://cx-oracle.sourceforge.net/html/module.html) they have a code example like this: ``` import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection....
``` error, = exc.args ``` This is a case of [sequence unpacking](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). A more readable way to write the same, and the style I personally favor, is: ``` [error] = exc.args ``` There are two bits required to understand the previous example: 1. When...
[http://www.python.org/doc/2.5.2/tut/node7.html](http://www.python.org/doc/2.5.2/tut/node7.html#SECTION007300000000000000000) Look for "sequence unpacking" in section 5.3.
Newbie Python Question about tuples
[ "", "python", "tuples", "cx-oracle", "" ]
Any idea on how to check whether that list is a subset of another? Specifically, I have ``` List<double> t1 = new List<double> { 1, 3, 5 }; List<double> t2 = new List<double> { 1, 5 }; ``` How to check that t2 is a subset of t1, using LINQ?
``` bool isSubset = !t2.Except(t1).Any(); ```
Use HashSet instead of List if working with sets. Then you can simply use [IsSubsetOf()](http://msdn.microsoft.com/en-us/library/bb358446.aspx) ``` HashSet<double> t1 = new HashSet<double>{1,3,5}; HashSet<double> t2 = new HashSet<double>{1,5}; bool isSubset = t2.IsSubsetOf(t1); ``` Sorry that it doesn't use LINQ. :-...
Check whether an array is a subset of another
[ "", "c#", "list", "linq", "subset", "" ]
I was wondering if there is an iterator in the STL that dereferences the object pointed before returning it. This could be very useful when manipulating containers aggregating pointers. Here's an example of what I would like to be able to do: ``` #include <vector> #include <iterator> #include <algorithm> using namesp...
Try Boost's [`indirect_iterator`](http://www.boost.org/doc/libs/1_37_0/libs/iterator/doc/indirect_iterator.html). An `indirect_iterator` has the same category as the iterator it is wrapping. For example, an `indirect_iterator<int**>` is a random access iterator.
Assuming your actual use case is a bit more complex than a container of integer pointers! You could check out the boost ptr containers <http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/reference.html> The containers contain dynamically allocated objects (ie pointers). But all access to the objects (dir...
Is there a dereference_iterator in the STL?
[ "", "c++", "stl", "iterator", "" ]
Unlike C++, in C# you can't overload the assignment operator. I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains... Here's...
It's still not at all clear to me that you really need this. Either: * Your Number type should be a struct (which is probable - numbers are the most common example of structs). Note that all the types you want your type to act like (int, decimal etc) are structs. or: * Your Number type should be immutable, making ev...
you can use the 'implicit' keyword to create an overload for the assignment: Suppose you have a type like Foo, that you feel is implicitly convertable from a string. You would write the following static method in your Foo class: ``` public static implicit operator Foo(string normalString) { //write your code here...
Is there a workaround for overloading the assignment operator in C#?
[ "", "c#", "operator-overloading", "" ]
Is there any built-in utility or helper to parse `HttpContext.Current.User.Identity.Name`, e.g. `domain\user` to get separately domain name if exists and user? Or is there any other class to do so? I understand that it's very easy to call `String.Split("\")` but just interesting
This is better (*easier to use, no opportunity of `NullReferenceExcpetion` and conforms MS coding guidelines about treating empty and null string equally*): ``` public static class Extensions { public static string GetDomain(this IIdentity identity) { string s = identity.Name; int stop = s.Inde...
`System.Environment.UserDomainName` gives you the domain name only Similarly, `System.Environment.UserName` gives you the user name only
Built-in helper to parse User.Identity.Name into Domain\Username
[ "", "c#", "asp.net", ".net", "authentication", "active-directory", "" ]
I am looking into building an **authentication** in my ASP.NET application with the following requirements. * A user has exactly one Role (i.e. Admin, SalesManager, Sales, ....) * A role has a set of permissions to CRUD access a subset of existing objects. I.e. "Sales has CREAD, READ, WRITE permission on object type...
I think what you need to do here is implement a set of permissions query methods in either your business objects or your controller. Examples: CanRead(), CanEdit(), CanDelete() When the page renders, it needs to query the business object and determine the users authorized capabilities and enable or disable functionali...
I think one of the best implementations that I think will fulfill your requirements is documented [here](http://www.codeproject.com/KB/web-security/objectlevelsecurity.aspx). The only issue is that this hooks into NHibernate, but you can use this as a template to create your own permissions implementation and simply ho...
ASP.NET: Permission/authentication architecture
[ "", "c#", "asp.net", "security", "forms-authentication", "" ]
I'm trying to launch another process from a service (it's a console app that collects some data and writes it to the registry) but for some reason I can't get it to launch properly. I basics of what I'm am trying to do is as follows: 1. Launch the process 2. Wait for the process to finish 3. Retrieve the return code ...
`WaitForSingleObject` and `GetExitCodeProcess` expect the process handle itself, not a pointer to the process handle. Remove the ampersands. Also, check the return values and call `GetLastError` when they fail. That will help you diagnose future problems. Never assume an API function will always succeed. Once you cal...
Following the update and edit, this sounds like one of many possible gotchas when launching a process from a service. Is there any possibility - any whatsoever - that your external process is waiting for user interaction? There are three major examples I can think of, one for instance would be a command-line applicatio...
Launching a Process from a Service
[ "", "c++", "service", "createprocess", "" ]
The following SQL separates tables according to their relationship. The problem is with the tables that sort under the 3000 series. Tables that are part of foreign keys and that use foreign keys. Anyone got some clever recursive CTE preferably or a stored procedure to do the necessary sorting?? Programs connectiong to ...
Thank you for a working solution NXC. You put me on the right track to solve the problem using a recursive CTE. ``` WITH TablesCTE(TableName, TableID, Ordinal) AS ( SELECT OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) AS TableName, so.id AS TableID, 0 AS Ordinal FROM dbo.sysobjects so INNER ...
My rendition with moderate tweaks: This one is SQL-2005+ and works on databases without the "rowguidcol": ``` WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS ( SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName, OBJECT_NAME(so.object_id) AS TableName, so.object_id AS TableID, ...
SQLServer: How to sort table names ordered by their foreign key dependency
[ "", "sql", "sql-server", "database", "" ]