Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Simple LINQ query: ``` from transport in db.Transports select new { Current = transport.CurrentLocation, CurrentCarriers = transport.CurrentLocation.Carriers, }; ``` Problem: `CurrentLocation` may be null. If it is, executing this query throws a NullReference. I tried adding a check like ``` transport.CurrentLocation == null ? null : transport.CurrentLocation.Carriers ``` but Linq to sql does not seem to be able to parse that. Any nice solutions that do not involve sending an extra query for each transport?
I normally just use 'let'. ``` from x in Foo let y = x.Bar where y != null select y.Baz; ``` UPDATE: I think the ?? operator does translate to SQL.
If the foreign key on Transports is nullable, you'll have to check that column for null before you can try and get the CurrentLocation object. You could do something like this: ``` CurrentLocation = transport.currentLocationId != null ? transport.CurrentLocation : null; ```
Linq to sql: properties of properties that may be null
[ "", "c#", "linq-to-sql", "" ]
How can I generate a bitmap of a control on a winform using C#?
You might try [Control.DrawToBitmap()](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap.aspx).
Maybe this can help: <http://www.syncfusion.com/FAQ/windowsforms/faq_c3c.aspx#q870q>
How can I generate a Bitmap from a winform control?
[ "", "c#", ".net-3.5", "bitmap", "" ]
This is a cursory question I can't quite answer. The main program ``` class Program{ static void Main(string[] args){ Console.WriteLine("Begin"); var myClass = new MyClass(); Util.Print(myClass.Id); Util.Print(myClass.Server); Util.Print(myClass.Ping); Console.WriteLine("End"); } } ``` How do I implement the Util.Print method to get this output to the console: ``` Begin Id Server Ping End ```
Assuming you don't want to use strings, the most common answer is via an `Expression` - essentially emulating the missing `infoof`; you would have to use something like: ``` Console.WriteLine("Begin"); var myClass = new MyClass(); Util.Print(() => myClass.Id); Util.Print(() => myClass.Server); Util.Print(() => myClass.Ping); Console.WriteLine("End"); ``` Assuming they are all properties/fields (**edit** added method-call support): ``` public static class Util { public static void Print<T>(Expression<Func<T>> expr) { WriteExpression(expr); } public static void Print(Expression<Action> expr) // for "void" methods { WriteExpression(expr); } private static void WriteExpression(Expression expr) { LambdaExpression lambda = (LambdaExpression)expr; switch (lambda.Body.NodeType) { case ExpressionType.MemberAccess: Console.WriteLine(((MemberExpression)lambda.Body) .Member.Name); break; case ExpressionType.Call: Console.WriteLine(((MethodCallExpression)lambda.Body) .Method.Name); break; default: throw new NotSupportedException(); } } } ```
In addition to Marc's answer: [here is an article](http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html) which explains several ways to do what you want to do (one such method uses expressions).
Print property name (not what you would think)
[ "", "c#", "" ]
My problem is a little bit complicate. (I use PHP) I have two arrays, (simple arrays array[0] = string, array[1] = string...) OK, now I will display the content of two arrays in a webpage. The first array contain names and the second images URL. Images and names are already displayed (my problem isn't here). But now I want to do something else, add a check box near every image, those checkbox r active by default. Ok, now the user can uncheck some inbox; The final aim, is to get a new array containing only the values of the names and images that had been checked. I have thought of something simple, crawl the keys (number) of unchecked checkboxes and unset them from my array. But the problem that I didn't know how to deal with the check boxes
first of all i recomend having just one array: ``` $array = array (0 => array('name' => '....', 'url' => '....')) ``` i think this will make your life much easier. Also in the HTML you could also send the array key ``` foreach ($yourArray as $key=>$value) { ... <INPUT type="checkbox" name="chkArr[<?php echo $key ?>]" value="1" checked/> ``` then in your form action you itarate the intial array and remove the unchecked ones. ``` foreach ($yourArray as $key=>$value) { if (!isset($_POST['chkArr'][$key]) OR $_POST['chkArr'][$key]!='1') { unset($yourArray[$key]); } } ```
To receive inputs as arrays in PHP, you have to set their name using brackets in HTML: ``` <label><input type="checkbox" name="thename[]" value="" /> The text</label> ``` Then, when you access $\_REQUEST['thename'] you'll get an array. Inspect it to see its format and play with it :)
How to retrieve information from Check Box?
[ "", "php", "checkbox", "" ]
I was wondering if there is a way of overcoming an accuracy problem that seems to be the result of my machine's internal representation of floating-point numbers: For the sake of clarity the problem is summarized as: ``` // str is "4.600"; atof( str ) is 4.5999999999999996 double mw = atof( str ) // The variables used in the columns calculation below are: // // mw = 4.5999999999999996 // p = 0.2 // g = 0.2 // h = 1 (integer) int columns = (int) ( ( mw - ( h * 11 * p ) ) / ( ( h * 11 * p ) + g ) ) + 1; ``` Prior to casting to an integer type the result of the columns calculation is 1.9999999999999996; so near yet so far from the desired result of 2.0. Any suggestions most welcome.
A very simple and effective way to round a floating point number to an integer: ``` int rounded = (int)(f + 0.5); ``` Note: this only works if `f` is always positive. (thanks j random hacker)
When you use floating point arithmetic strict equality is almost meaningless. You usually want to compare with a range of acceptable values. Note that some values can *not* be represented exactly as floating point vlues. See [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) and [Comparing floating point numbers](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).
Dealing with accuracy problems in floating-point numbers
[ "", "c++", "floating-point", "floating-accuracy", "" ]
Ex. If I have something like this: ``` class C(object): @classmethod def f(cls, x): return x + x ``` This will work: ``` c = C() c.f(2) 4 ``` But is that bad form? Should I only call ``` C.f() ``` or ``` c.__class__.f() ``` Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class. ?
If you are tempted to call a class method from an instance you probably don't need a class method. In the example you gave a static method would be more appropriate precisely because of your last remark (no self/cls interaction). ``` class C(object): @staticmethod def f(x): return x + x ``` this way it's "good form" to do both ``` c = C() c.f(2) ``` and ``` C.f(2) ```
I don't recall using a classmethod like this from outside the class, but it is certainly ok for an instance method to call a classmethod on itself (e.g. `self.foo()` where `foo` is a classmethod). This makes sure that inheritance acts as expected, and will call `.foo()` in the right subclass instead of the base class.
Is it bad form to call a classmethod as a method from an instance?
[ "", "python", "class-method", "" ]
Currently I'm using a very ugly approach based on a regex for finding links and taking them apart. I'm unhappy with the code, so I'm asking for nicer solutions, preferably using only the stdlib. ### Edit The task at hand has 2 parts: 1. Find all distributions that match a certain criteria (like prefix of the name). 2. Find all versions available in each found distribution. The expected result is a mapping of distribution -> versions -> files.
its unfortunate, but due to the lack of xmlrpc on other indexes i need to keep my solution
There is an XML-RPC interface. See the [Python.org wiki page on Cheese Shop (old name for PyPi) API](http://wiki.python.org/moin/PyPiXmlRpc?action=show&redirect=CheeseShopXmlRpc). Excerpt from that wiki: ``` >>> import xmlrpclib >>> server = xmlrpclib.Server('http://pypi.python.org/pypi') >>> server.package_releases('roundup') ['1.1.2'] >>> server.package_urls('roundup', '1.1.2') [{'has_sig': True, 'comment_text': '', 'python_version': 'source', 'url': 'http://pypi.python.org/packages/source/r/roundup/roundup-1.1.2.tar.gz', 'md5_digest': '7c395da56412e263d7600fa7f0afa2e5', 'downloads': 2989, 'filename': 'roundup-1.1.2.tar.gz', 'packagetype': 'sdist', 'size': 876455}, {'has_sig': True, 'comment_text': '', 'python_version': 'any', 'url': 'http://pypi.python.org/packages/any/r/roundup/roundup-1.1.2.win32.exe', 'md5_digest': '983d565b0b87f83f1b6460e54554a845', 'downloads': 2020, 'filename': 'roundup-1.1.2.win32.exe', 'packagetype': 'bdist_wininst', 'size': 614270}] ``` `list_packages` and `package_releases` seem to be exactly what you're looking for. ### @Ronny's Comment You just have to write some code in Python to determine which of the listed packages satisfy the criterion; i.e. if the package name must start with `foo`: ``` >>> packages = server.list_packages() >>> match_foo = [package for package in packages if package.startswith('foo')] >>> print len(match_foo) 2 ```
What is an elegant way to find versions of packages on a pypi package index?
[ "", "python", "package", "search", "pypi", "" ]
I recently installed the add-on "DownThemAll" into my firefox and as I watched it download a huge amount of pk3 files(map files for an opensource First Person Shooter), I wondered if I could do the same with PHP. Here's what I'm thinking: ``` foreach(glob("http://www.someaddress.ext/path/*.pk3") as $link) { //do something to download... } ``` Yeah that's about as far as I've gotten. I'm wondering wheter to just initiate a download of to do it via a stream... I don't really know my way around this material, it's not what I usually do with PHP, but it's triggered my interest. So is there anybody who knows how to tackle this problem?
I'll throw you in the right direction. [cURL](http://is.php.net/manual/en/function.curl-exec.php) for the downloading and a regular expression to get all the paths in the link. Beware though, a link on a site can be a relative link. So you need to check for that.
This will do it (or help at least): ``` $pageRaw = fread_url('www.example.com'); //link extraction regex preg_match_all ("/a[\s]+[^>]*?href[\s]?=[\s\"\']+". "(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a>/", $pageRaw, &$matches); $matches = $matches[1]; foreach($matches as $link) { echo $link. '<br />'; } //falls back to fopen if curl is not there function fread_url($url,$ref="") { if(function_exists("curl_init")){ $ch = curl_init(); $user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; ". "Windows NT 5.0)"; $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); curl_setopt( $ch, CURLOPT_HTTPGET, 1 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 ); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_REFERER, $ref ); curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); $html = curl_exec($ch); curl_close($ch); } else{ $hfile = fopen($url,"r"); if($hfile){ while(!feof($hfile)){ $html.=fgets($hfile,1024); } } } return $html; } ```
Creating a PHP file that downloads all links from a certain site
[ "", "php", "download", "stream", "" ]
How can I detect in my python script if its being run by the debug interpreter (ie python\_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension. eg Id like to do something like this at the start of my python script: ``` #get paths to graphics dlls if debug_build: d3d9Path = "bin\\debug\\direct3d9.dll" d3d10Path = "bin\\debug\\direct3d10.dll" openGLPath = "bin\\debug\\openGL2.dll" else: d3d9Path = "bin\\direct3d9.dll" d3d10Path = "bin\\direct3d10.dll" openGLPath = "bin\\openGL2.dll" ``` I thought about adding an "IsDebug()" method to the extension which would return true if it is the debug build (ie was built with "#define DEBUG") and false otherwise. But this seems a bit of a hack for somthing Im sure I can get python to tell me...
[Distutils use `sys.gettotalrefcount` to detect a debug python build](http://bugs.python.org/file2086/build.py.diff): ``` # ... if hasattr(sys, 'gettotalrefcount'): plat_specifier += '-pydebug' ``` * this method doesn't rely on an executable name '`*_d.exe`'. It works for any name. * this method is cross-platform. It doesn't depend on '`_d.pyd`' suffix. See [Debugging Builds](http://docs.python.org/c-api/intro.html#debugging-builds) and [Misc/SpecialBuilds.txt](http://svn.python.org/view/python/trunk/Misc/SpecialBuilds.txt?view=markup)
Better, because it also works when you are running an embedded Python interpreter is to check the return value of ``` imp.get_suffixes() ``` For a debug build it contains a tuple starting with '\_d.pyd': ``` # debug build: [('_d.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)] # release build: [('.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)] ```
Python: How to detect debug interpreter
[ "", "python", "debugging", "" ]
How do I get the IP address of the server that calls my ASP.NET page? I have seen stuff about a Response object, but am very new at c#. Thanks a ton.
This should work: ``` //this gets the ip address of the server pc public string GetIPAddress() { IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // `Dns.Resolve()` method is deprecated. IPAddress ipAddress = ipHostInfo.AddressList[0]; return ipAddress.ToString(); } ``` <http://wec-library.blogspot.com/2008/03/gets-ip-address-of-server-pc-using-c.html> OR ``` //while this gets the ip address of the visitor making the call HttpContext.Current.Request.UserHostAddress; ``` <http://www.geekpedia.com/KB32_How-do-I-get-the-visitors-IP-address.html>
`Request.ServerVariables["LOCAL_ADDR"];` This gives the IP the request came in on for multi-homed servers
Getting the IP address of server in ASP.NET?
[ "", "c#", "asp.net", "dns", "referrer", "" ]
When a JSP finishes execution, will all variables declared in the JSP page be put up for garbage collection? If I declare a number of memory intensive Hashtables in the JSP, and I let the JSP finish execution without setting the variables to null beforehand, will the object stay in memory even after the JSP has finished executing? (I am not storing them in a persistent variable, such as session. Just in a local variable.)
If the variables are declared in request or page scope, yes they are eligible for garbage collection. Even if you set an object reference to null it is still consuming memory, only the reference count decreases by 1. If the reference count is 0 the garbage collector will free the memory.
If you want to find out exactly what Java logic code the JSP translates into, you can use [Jasper](http://en.wikipedia.org/wiki/Tomcat_Jasper#Jasper) to generate the code. (Different JSP engines will likely generate differing output, but the scope of variables and so on should conform to the spec.) You'll need [Tomcat](http://tomcat.apache.org/) and [Ant](http://ant.apache.org/). This sample batch script generates the Java code for *test.jsp* in the *output* directory: ``` @ECHO OFF SETLOCAL EnableDelayedExpansion SET ANT_HOME=C:\dev\apache-ant-1.7.1 SET TOMCAT_HOME=C:\Program Files\Apache Software Foundation\Tomcat 6.0 SET CLASSPATH=" FOR /r "%TOMCAT_HOME%\bin\" %%a IN (*.jar) DO SET CLASSPATH=!CLASSPATH!;%%a FOR /r "%TOMCAT_HOME%\lib\" %%a IN (*.jar) DO SET CLASSPATH=!CLASSPATH!;%%a SET CLASSPATH=!CLASSPATH!;%ANT_HOME%\lib\ant.jar" MKDIR output java org.apache.jasper.JspC -d .\output -webapp .\WebContent test.jsp ``` *WebContent* is the root directory of the web application. The generated code is a servlet and will follow the servlet lifecycle as defined in the spec.
What happens when a JSP finishes execution?
[ "", "java", "jsp", "memory", "garbage-collection", "" ]
I have this code: ``` #include <iostream> #include <mp4.h> int main (int argc, char * const argv[]) { // insert code here... std::cout << "Hello, World!\n"; MP4Read("filename", MP4_DETAILS_ALL ); return 0; } ``` And i've added -I/opt/local/include and -L/opt/local/lib to the path (where the mp4 library resides after installing it through macports), but all i get is: > Undefined symbols: "\_MP4Read", > referenced from: > \_main in main.o ld: symbol(s) not found Even though XCode finds it and autocompletes properly...
You need to link the library most likely, i.e. add -lmp4 or similar to your linking commands.
You have only specified the paths. You need to link in the mp4 library. Something like the following: ``` g++ -I /.../ -L /.../ -lmp4 -o out main.cpp ```
#include <lib.h> gives symbol not found, why?
[ "", "c++", "xcode", "" ]
HI, I need to add multiple configuration files in my application. What is the easiest way to read a key value from these files? Currently I am using xmldocument class and select the node using an xpath expression. Is there any other simple way to do this in C# 2.0
I had a similar need and found this to be extremely useful and simple. <http://www.codeproject.com/KB/cs/cs_ini.aspx> It is an INI file reader and writer, you just specify the header tag and the item name and it will read or write from a file. It gives you strings and you can cast them with some try blocks. INI is really a much simpler format than XML if you have less than fifty config options and they are not nested.
A bit of a hacky solution would be to read all of the configuration files into one in memory document then use xpath to select the right nodes. You've tagged this as c# 2.0, do you have access to LINQ to XML? That can make your queries a lot neater.
Adding multiple configuration files to an application
[ "", "c#", "c#-2.0", "" ]
*Assumption:* > Converting a > byte[] from Little Endian to Big > Endian means inverting the order of the bits in > each byte of the byte[]. Assuming this is correct, I tried the following to understand this: ``` byte[] data = new byte[] { 1, 2, 3, 4, 5, 15, 24 }; byte[] inverted = ToBig(data); var little = new BitArray(data); var big = new BitArray(inverted); int i = 1; foreach (bool b in little) { Console.Write(b ? "1" : "0"); if (i == 8) { i = 0; Console.Write(" "); } i++; } Console.WriteLine(); i = 1; foreach (bool b in big) { Console.Write(b ? "1" : "0"); if (i == 8) { i = 0; Console.Write(" "); } i++; } Console.WriteLine(); Console.WriteLine(BitConverter.ToString(data)); Console.WriteLine(BitConverter.ToString(ToBig(data))); foreach (byte b in data) { Console.Write("{0} ", b); } Console.WriteLine(); foreach (byte b in inverted) { Console.Write("{0} ", b); } ``` The convert method: ``` private static byte[] ToBig(byte[] data) { byte[] inverted = new byte[data.Length]; for (int i = 0; i < data.Length; i++) { var bits = new BitArray(new byte[] { data[i] }); var invertedBits = new BitArray(bits.Count); int x = 0; for (int p = bits.Count - 1; p >= 0; p--) { invertedBits[x] = bits[p]; x++; } invertedBits.CopyTo(inverted, i); } return inverted; } ``` The output of this little application is different from what I expected: ``` 00000001 00000010 00000011 00000100 00000101 00001111 00011000 00000001 00000010 00000011 00000100 00000101 00001111 00011000 80-40-C0-20-A0-F0-18 01-02-03-04-05-0F-18 1 2 3 4 5 15 24 1 2 3 4 5 15 24 ``` For some reason the data remains the same, unless printed using BitConverter. What am I not understanding? **Update** New code produces the following output: ``` 10000000 01000000 11000000 00100000 10100000 11110000 00011000 00000001 00000010 00000011 00000100 00000101 00001111 00011000 01-02-03-04-05-0F-18 80-40-C0-20-A0-F0-18 1 2 3 4 5 15 24 128 64 192 32 160 240 24 ``` But as I have been told now, my method is incorrect anyway because I should invert the bytes and not the bits? This hardware developer I'm working with told me to invert the bits because he cannot read the data. **Context where I'm using this** The application that will use this does not really work with numbers. I'm supposed to save a stream of bits to file where 1 = white and 0 = black. They represent pixels of a bitmap 256x64. byte 0 to byte 31 represents the first row of pixels byte 32 to byte 63 the second row of pixels. I have code that outputs these bits... but the developer is telling me they are in the wrong order... He says the bytes are fine but the bits are not. So I'm left confused :p
Your method may be correct at this point. There are different meanings of endianness, and it depends on the hardware. Typically, it's used for converting between computing platforms. Most CPU vendors (now) use the same bit ordering, but different byte ordering, for different chipsets. This means, that, if you are passing a 2-byte int from one system to another, you leave the bits alone, but swap bytes 1 and 2, ie: ``` int somenumber -> byte[2]: somenumber[high],somenumber[low] -> byte[2]: somenumber[low],somenumber[high] -> int newNumber ``` However, this isn't always true. Some hardware still uses inverted BIT ordering, so what you have may be correct. You'll need to either trust your hardware dev. or look into it further. I recommend reading up on this on Wikipedia - always a great source of info: <http://en.wikipedia.org/wiki/Endianness> --- Your ToBig method has a bug. At the end: ``` invertedBits.CopyTo(data, i); } return data; ``` You need to change that to: ``` byte[] newData = new byte[data.Length]; invertedBits.CopyTo(newData, i); } return newData; ``` You're resetting your input data, so you're receiving both arrays inverted. The problem is that arrays are reference types, so you can modify the original data.
No. Endianness refers to the order of **bytes**, not bits. Big endian systems store the most-significant byte first and little-endian systems store the least-significant first. The bits within a byte remain in the same order. Your ToBig() function is returning the original data rather than the bit-swapped data, it seems.
Why do I get the following output when inverting bits in a byte?
[ "", "c#", ".net", "endianness", "" ]
Some users are complaining that the applet no longer works, When they view the java console they are greeted with a java.lang.noClassDefFoundError and checking my access log's I see they have downloaded the jar file that contains the class, and then issue a get request for the particular class. Different users break on different classes. Some users are fine. Any ideas what could cause this/fix this. I have checked to make sure the file is in their java cache, cleared the cache etc. nothing seems to fix them. If they hit a qa site it breaks as well.
The jar is getting corrupted in transit, We are looking at getting patches from oracle/bea for the server. It appears that if a connection is too slow (Modem speeds) that weblogic will signal the end of a transfer by sending a packet with len=0. The network will signal java saying the download completed successfully and then java fails with a java.lang.noClassDefFoundError.
This can occur if the class itself can be loaded but some dependency of that class cannot be. Are there external JARs that are dependencies?
applet fails to load class from jar
[ "", "java", "jakarta-ee", "applet", "" ]
I am attempting to get the last modified time of a file that definately does exist: /document\_root/myfile.pdf -rwxr-xr-x 1 11018 11008 198621 Nov 26 2007 myfile.pdf When i run the following statement (through PHP CLI as root): filemtime('/document\_root/myfile.pdf'); I get errors: Warning: stat(): Stat failed for /document\_root/myfile.pdf (errno=2 - No such file or directory)
You're getting the **file path wrong** or you **don't have permission** to stat the relevant file. Wrong file path? ``` filemtime('/document_root/myfile.pdf'); ``` Right file path? ``` filemtime($_SERVER['DOCUMENT_ROOT'].'/myfile.pdf'); ``` Check the file's permissions: can the file be read by the user under which PHP is running?
You're not doing something like running this from within a function where you haven't passed through a value for document\_root?
PHP Warning when attempting to use stat() or filemtime()
[ "", "php", "linux", "command-line-interface", "" ]
Is there a way in Java to construct a `File` instance on a resource retrieved from a jar through the classloader? My application uses some files from the jar (default) or from a filesystem directory specified at runtime (user input). I'm looking for a consistent way of a) loading these files as a stream b) listing the files in the user-defined directory or the directory in the jar respectively Edit: Apparently, the ideal approach would be to stay away from `java.io.File` altogether. Is there a way to load a directory from the classpath and list its contents (files/entities contained in it)?
`ClassLoader.getResourceAsStream` and `Class.getResourceAsStream` are definitely the way to go for loading the resource data. However, I don't believe there's any way of "listing" the contents of an element of the classpath. In some cases this may be simply impossible - for instance, a `ClassLoader` *could* generate data on the fly, based on what resource name it's asked for. If you look at the `ClassLoader` API (which is basically what the classpath mechanism works through) you'll see there isn't anything to do what you want. If you know you've actually got a jar file, you could load that with `ZipInputStream` to find out what's available. It will mean you'll have different code for directories and jar files though. One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.
I had the same problem and was able to use the following: ``` // Load the directory as a resource URL dir_url = ClassLoader.getSystemResource(dir_path); // Turn the resource into a File object File dir = new File(dir_url.toURI()); // List the directory String files = dir.list() ```
Java resource as File
[ "", "java", "resources", "classloader", "" ]
I'm building a basic little AJAX shoutbox/chat for my website, but I'm not sure exactly how to implement the server polling. Here's the basic program flow I'm thinking of: 1. User comes to page and is shown the last 10 messages 2. To get messages sent by others, the client javascript would request a URL with a timestamp parameter (set to the value of the last message the client received) 3. The server returns all messages (up to a max of 10) since that timestamp. The only issue is how often to poll the server. Obviously it should poll each time a new message is added, but when you're just reading others' messages it needs to automatically update. Should it be a set time limit? eg: every 10 seconds. Or, should it vary depending on usage? eg: Check after 5 seconds. If there's no messages, don't check for another 10 seconds. If there's still no new messages, check in 15 seconds, then 20, up to maybe once every 30 seconds max. Each time there's a new message detected reset your timer back down to 5 seconds and start again. I'm just concerned about putting unnecessary stress on the server, considering that we could have hundreds of users concurrently online. ...or have I got the whole thing wrong? Is there a better way to implement a basic javascript chat?
Comet, described by Brian is a nice technique, but requires session support on the server, which is probably more advanced than you care to implement for a simple chat box. The best way to implement polling intervals is to imagine you having a chat window which you can minimize to do other stuff, or open to see if you have new messages. When you are in the middle of a conversation, you'll switch to it (poll) frequently. If you don't get any messages for a while, you will start looking rarer and rarer until you only check it occasionally. Assuming you don't need to do real-time typing, you can probably poll every 3 seconds or so when at peak activity, and if nothing shows up for 5-10 polls, start to crank the interval up (perhaps doubling it every time) until it hits 30-60 seconds. Getting a message back should reset the poll interval back to a few seconds, while sending a message should poll instantly, but probably doesn't need to effect the frequency of polling otherwise.
You might want to look into what are known as [Comet](http://en.wikipedia.org/wiki/Comet_(programming)) programming techniques to stream information down to your users, rather than having the client poll the server. This is actually a family of techniques, some of which may work better than others depending on the circumstances, such as what kind of server you're using and what kind of client compatibility you need. If your server can handle a large number of open connections at a time (as in, it does not use an entire thread or process per connection, such as [nginx](http://wiki.nginx.org/Main) or an [erlang](http://www.erlang.org/) based server), you may wish to use a long polling technique, where as soon one message is received, the client immediately requests another message. If there are no messages available, the server simply keeps the connection open, possibly sending occasionally dummy data as a keepalive, until a message becomes available.
Server polling intervals for a javascript chat client
[ "", "javascript", "ajax", "" ]
i have a question regarding the visitor pattern, I currently have two assemblies. My first assembly contains several interfaces. ``` public interface INode { void Visit(INodeVisitor visitor); } public interface INodeVisitor { void VisitContainer(IContainer container); } public interface IContainer : INode { } ``` And my second assembly ``` class Program { static void Main(string[] args) { ContainerVisitor visitor = new ContainerVisitor(); visitor.VisitContainer(new Container()); } } public class ContainerVisitor : INodeVisitor { public void VisitContainer(IContainer value) { Container container = value as Container; // Do some stuff... } } public class Container : IContainer { public void Visit(INodeVisitor visitor) { visitor.VisitContainer(this); } } ``` What i want to do is avoid the need to cast in the ContainerVisitor class, I want to reference the Container directly. I cannot change the interface INodeVisitor interface to use Container. Any ideas? Should i just cast? Cheers Rohan
The cast is unavoidable, but you could abstract it out a bit to remove it from the actual ContainerVisitor class. ``` public class NodeVisitor<T> : INodeVisitor where T : IContainer { public void VisitContainer(T node) { var container = node as T; if ( container != null ) { VisitTyped(container); } } protected abstract VisitContainerTyped(T container); } ``` Now ContainerVisitor can derive from NodeVisitor and avoid the cast ``` public class ContainerVisitor : NodeVisitor<Container>{ protected override void VisitContainerTyped(Container container){ // Do some stuff... } } ```
I don't think it is *valid* to assume that it is a `Container` instance. I could, perfectly validly, write my own `IContainer` implementation, and your implementation would choke on it, breaking the whole point of interface-based abstraction. You also can't (validly) just change the API to accept `Container` (using explicit implementation to support `IContainer`), since I could be using the interface rather than the class: ``` INodeVisitor visitor = new ContainerVisitor(); visitor.VisitContainer(myBespokeContainer); ``` If you want optional support for something from the base-class, then you are going to have to use "as" to detect it. Anything else and you are breaking the abstraction.
Visitor Pattern, remove the need to cast
[ "", "c#", "design-patterns", "visitor-pattern", "" ]
I'd like to take data entered in an MVC user form and display it in a different view. The class has the following private variable: ``` IList<string> _pagecontent = new List<string>(); ``` The following action accepts a FormCollection object, validates it, and passes it on to the "Preview" view as a List: ``` [Authorize(Roles = "Admins")] [ValidateInput(false)] [AcceptVerbs(HttpVerbs.Post)] public ActionResult UpdateContent(FormCollection collection) { if (ModelState.IsValid) { string PageToInsert = collection["PageToInsert"]; string PageHeader = collection["PageHeader"]; string PageBody = collection["PageBody"]; //validate, excluded... _pagecontent.Add(PageToInsert); _pagecontent.Add(PageHeader); _pagecontent.Add(PageBody); } return RedirectToAction("Preview", _pagecontent); } ``` The Preview view has the following Page Directive for passing a strongly typed object List: ``` <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Template.Master" Inherits="System.Web.Mvc.ViewPage<List<string>>" %> ``` I would expect to be able to use the Model object to get my data, but alas I cannot. At the following line, I get an `error index out of bounds` exception, stating the index must be non-negative and less than the size of the collection: ``` <% if (Model[0].ToString() == "0") { %> ``` And some strange parameters have been added to the URL, as it resolves to `http://localhost:1894/Admin/Preview?Capacity=4&Count=3` So I have two questions: 1. When I call RedirectToAction and pass it my List, why is it inaccessible in the view's Model object? 2. What is the proper way to go about doing what I'm trying to do, namely pass a collection of strings to a view for display there?
Try using TempData. It is like a single-shot session object. You put values you want into TempData, immediately redirect and get them out. There is a good writeup here: <http://blogs.teamb.com/craigstuntz/2009/01/23/37947/>
Be careful when using TempData. It works great in a single server environment but in a cloud environment it may not work as expected since you cannot guarantee that the request will hit the same machine. This happens because TempData rely on the asp.net session. But if you are using other session manager like SQL or AppFabric Cache it will work fine.
MVC - Passing Data with RedirectToAction()
[ "", "c#", "asp.net-mvc", "redirecttoaction", "" ]
I am looking to fileupload a picture jpeg,gif,etc into an SQL database on an updateprofilepicture page. Then on the profile page, I want to retrieve the image from an sql database and have it show up in an Asp:Image control. I have much code trying to do this and it doesn't work. The table contains a column of type Image.
As Joel mentioned you should use an HttpHandler or a page to display the image. Here is a sample code to output image (**Image.ashx**) : ``` // ProcessRequest method of Image.ashx long imageId = Convert.ToInt64(Request.QueryString["ImageId"]); using (var conn = new SqlConnection(connectionString)) using (var command = new SqlCommand( "SELECT ImageFile FROM ImageTable WHERE ImageId = @ImageID", conn)) { command.Parameters.Add("@ImageID", SqlDbType.Int).Value = imageId; conn.Open(); Response.ContentType = "image/gif"; Response.BinaryWrite((byte[]) command.ExecuteScalar()); } ``` and then use image in your page as : ``` <asp:Image id="Image1" runat="server" ImageUrl="Image.ashx?ImageID=12"/> ```
The important thing to remember here is that you shouldn't try to transmit the image data with the profile page itself. Instead, you want your profile page to generate HTML markup for the browser that looks something like this: ``` <img src="~/MyImageHandler.ashx?UserID=1234" alt="User 1234 avatar" width="100px" height="150px" /> ``` That is the ultimate result of your `<asp:Image .../>` control. Then the browser will send a completely separate Http request to retrieve the image. That's how pictures on web sites work. You then need to be able to handle that additional request. To do that, create an `Http handler (*.ashx file)` and use it to retrieve the appropriate image data from the database and send it to the browser.
ASP.NET store Image in SQL and retrieve for Asp:Image
[ "", "asp.net", "sql", "image", "" ]
Is there any real issue - such as performance - when the hibernate object model and the database physical model no longer match? Any concerns? Should they be keep in sync? Our current system was original designed for a low number of users so not much effort was done to keep the physical and objects in sync. The developers went about their task and the architects did not monitor. Now that we are in the process of rewriting/importing the legacy system into the new system, a concern has been raised in that the legacy system handles a lot of user volume and might bring the new system to its knees. **Update 20090331** From Pete's comments below - the concern was about table/data relationships in the data layer vs the object layer. If there is no dependencies between the two, then there is no performance hits if these relationships do not match? Is that correct? The concern from my view is that the development team spends a lot of time "tuning" the hibernate queries/objects but nothing at the database layer to improve the performance of the application. I would have assumed that they would tune at both layers. Could these issue be from just a poor initial design of the database to begin with and trying to cover/make up the difference by the use of Hibernate? (I am new to this project so playing catchup)
**Update: in response to comment:** It is CRUCIAL that the database be optimized in addition to the Hibernate use. When you think about it, after all the work hibernate does, in the end it is just querying the database. If the database doesn't perform well (wrong or missing indexes, poorly set up table spaces, etc) it doesn't matter how much you tune Hibernate. On the flip side if your database is set up well but Hibernate isn't (perhaps the caching is not set up properly, etc., and you are going back to the database a lot more then you need to) then performance will suffer as well. It is always important to tune the system end to end, but start at the foundation (database) and work up. **End Update** I'm curious what you mean about 'don't match' - do you mean columns have been added to tables that aren't represented in the hibernate data objects? Tables have been added? I don't think anything like that would affect performance (more likely data integrity if you are not inserting/updating all columns) In general, the goal of the object model should NOT be match the database schema verbatim. You want to abstract the underlying data complexity / joins / normalization, that is the whole point of using something like Hibernate. So for example lets say you have (keeping things very simple) 'orders' and 'order items', your application code should be able to do something like order.getItems() without having to know that underneath it is a one to many relationship. The details in your hibernate code control how the load is done (lazy, caching, etc). If that doesn't answer your question then please provide more detail
You could of course code your abstraction layer in asm - "might" (awful word for a developer) be faster. This is premature optimization - maybe breaking a clean project-layout. As in the hibernate-manual - optimization can look different ways - plain coding some parts "might" be part of it.
hibernate object vs database physical model
[ "", "java", "performance", "hibernate", "" ]
My friend is primarily a VB developer and he says time and time again how much more simple it is to code events in VB than C#. My take on the issue is that it probably is easier but if there was not a reason for the added complexity, they probably would have made it just as simple in C#. Can anyone tell me if there is any added flexibility or any ability, in general, that can be done with C# events and not VB.Net events?
The only thing that comes to mind for C# is the ability to subscribe to a void returning event (virtually all events) with an anonymous function. VB.Net 9.0 only supports Lambda Expressions which returns a value (this is fixed in VB 10.0). VB has a bit of flexibility not present in C# with regard to events * Support for [Relaxed Delegates](http://www.developer.com/net/vb/print.php/3664491). This allows VB to use event handlers which only need a subset of the parameters in the event type (mostly used with empty parameter functions) * The Handles clause makes it much easier to delete designer generate events as opposed to C# where you have to dig through the .Designer.cs file * The RaiseEvent keyword makes the null event check problem non-existent in VB.Net
I prefer VB to C# most of the time, but I'm pretty fluent in both. Off the top of my head there are two places I know where VB.Net makes it easier. One is that you don't ever have to check for `null` before raising an event. There might be some trade-off there, but I"m not aware of it. The other is the addition of the `Handles` keyword. You can declare a full method to handle event and wire it up to the event in one statement. This is a definite advantage for VB, because you could still do everything in long form without that keyword. It's just an extra little piece of syntactic sugar. The only way you can do that in C# is with a lambda expression/anonymous delegate. The rest of the syntax is pretty much a wash: do you prefer "`+=`" or "`AddHandler`"?
Is there anything you can do with a C# event that you cannot do with a VB Event?
[ "", "c#", "vb.net", "events", "delegates", "" ]
I have a Message class which parses text messages using lookup tables. I receive a lot of messages and create and destroy a lot of objects so I thought I declare those lookup tables as static members to prevent initializing the same tables with the same values again and again. Is it the correct approach or there's more appropriate C++ way? Thanks.
This sounds like the right way to do it, although I'd expect the compiler to optimize this. Have you benchmarked your application and does declaring the tables as static speed it up? Also note that if you have many large lookup tables, performance will increase, but the tables will be hold in memory all the time.
If your message classes share lookup information that it may be worth abstracting your static lookups into a class of their own so that they really are only initialised once. But regardless, static class members are definitely the way to go.
Should lookup tables be static
[ "", "c++", "static", "members", "" ]
This is a follow up to: [this question](https://stackoverflow.com/questions/495922/what-is-the-best-way-to-implement-a-heartbeat-in-c-to-check-for-socket-connecti) Basically, I have a server loop that manages a connection to one solitary client. At one point in the loop, if a ClientSocket exists it attempts a read to check if the client is still connected: ``` if (bufferedReader.read() == -1) { logger.info("CONNECTION TERMINATED!"); clientSocket.close(); setUpSocket(); // sets up the server to reconnect to the client } else { sendHeartBeat(); // Send a heartbeat to the client } ``` The problem is, that once a socket has been created the application will hang on the read, I assume waiting for data that will never come, since the client never sends to the server. Before this was OK, because this correctly handled disconnects (the read would eventually fail when the client disconnected) and the loop would attempt reestablish the connection. However, I now have added the above sendHeartBeat() method, which periodically lets the client know the server is still up. If the read is holding the thread then the heartbeats never happen! So, I assume I am testing if the connection is still up incorrectly. I could, as a quick hack, run the bufferedReader.read() in a seperate thread, but then I'll have all sorts of concurrency issues that I really don't want to deal with. So the question is a few fold: 1. Am I checking for a client disconnect correctly? 2. If not, how should I do it? 3. If I am doing it correctly how I do I get the read to not hold the process hostage? Or is threading the only way?
When you create your socket, first set a timeout: ``` private int timeout = 10000; private int maxTimeout = 25000; clientSocket.setSoTimeout(timeout); ``` With this, if a read times out you'll get `java.net.SocketTimeoutException` (which you have to catch). Thus, you could do something like this, assuming you've previously set the SO\_TIMEOUT as shown above, and assuming that the heartbeat will always get a response from the remote system: ``` volatile long lastReadTime; try { bufferedReader.read(); lastReadTime = System.currentTimeMillis(); } catch (SocketTimeoutException e) { if (!isConnectionAlive()) { logger.info("CONNECTION TERMINATED!"); clientSocket.close(); setUpSocket(); //sets up the server to reconnect to the client } else { sendHeartBeat(); //Send a heartbeat to the client } } public boolean isConnectionAlive() { return System.currentTimeMillis() - lastReadTime < maxTimeout; } ``` A common way of handling this is setting the timeout to some number (say 10 seconds) and then keeping track of the last time you successfully read from the socket. If 2.5 times your timeout have elapsed, then give up on the client and close the socket (thus sending a FIN packet to the other side, just in case). If the heartbeat will *not* get any response from the remote system, but is just a way of ultimately generating an IOException earlier when the connection has fallen down, then you could do this (assuming that the sendHeartBeat itself will not throw an IOException): ``` try { if (bufferedReader.read() == -1) { logger.info("CONNECTION TERMINATED with EOF!"); resetConnection(); } } catch (SocketTimeoutException e) { // This just means our read timed out ... the socket is still good sendHeartBeat(); //Send a heartbeat to the client } catch (IOException e) { logger.info("CONNECTION TERMINATED with Exception " + e.getMessage()); resetConnection(); } .... private void resetConnection() { clientSocket.close(); setUpSocket(); //sets up the server to reconnect to the client } ```
You are checking correctly, you can should add a try catch with IOException in case it occurs. There is a way to avoid threading, you can use a Selector with a non-bloking socket. ``` public void initialize(){ //create selector Selector selector = Selector.open(); ServerSocketChannel acceptSocket = ServerSocketChannel.open(); acceptSocket.configureBlocking(false); String bindIp = "127.0.0.1"; int bindPort = 80; acceptSocket.socket().bind(new InetSocketAddress(bindIp, bindPort)); //register socket in selector for ACCEPT operation acceptSocket.register(selector, SelectionKey.OP_ACCEPT); this.selector = selector; this.serverSocketChannel = serverSocketChannel; } public void serverStuff() { selector.select(maxMillisecondsToWait); Set<SelectionKey> selectedKeys = selector.selectedKeys(); if( selectedKeys.size() > 0 ) { if( key.isAcceptable() ){ //you can accept a new connection SocketChannel clientSk = serverSocketChannel.accept(); clientSk.configureBlocking(false); //register your SocketChannel in the selector for READ operations clientSk.register(selector, SelectionKey.OP_READ); } else if( key.isReadable() ){ //you can read from your socket. //it will return you -1 if the connection has been closed } } if( shouldSendHeartBeat() ){ SendHeartBeat } } ```
Checking if a ClientSocket has disconnected in java hangs
[ "", "java", "sockets", "" ]
I'm performing a regular expression match on a column of type `character varying(256)` in PostgreSQL 8.3.3. The column currently has no indices. I'd like to improve the performance of this query if I can. Will adding an index help? Are there other things I can try to help improve performance?
You cannot create an index that will speed up any generic regular expression; however, if you have one or a limited number of regular expressions that you are matching against, you have a few options. As Paul Tomblin mentions, you can use an extra column or columns to indicate whether or not a given row matches that regex or regexes. That column can be indexed, and queried efficiently. If you want to go further than that, [this paper](http://oak.cs.ucla.edu/~cho/papers/cho-regex.pdf) discusses an interesting sounding technique for indexing against regular expressions, which involves looking for long substrings in the regex and indexing based on whether those are present in the text to generate candidate matches. That filters down the number of rows that you actually need to check the regex against. You could probably implement this using [GiST](http://gist.cs.berkeley.edu/) indexes, though that would be a non-trivial amount of work.
An index can't do anything with a regular expression. You're going to have to do a full table scan. If at all possible, like if you're querying for the same regex all the time, you could add a column that specifies whether this row matches that regex and maintain that on inserts and updates.
What are some ways I can improve the performance of a regular expression query in PostgreSQL 8?
[ "", "sql", "regex", "performance", "postgresql", "" ]
I have an application that encrypts a section in the configuration file. In the first time that I try to read the encrypted section from the config file I get an error message: "Unrecognized attribute 'configProtectionProvider'. Note that attribute names are case-sensitive. " ``` config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Get the section in the file. ConfigurationSection section = config.GetSection("EncryptedSection"); if (section != null) { // Protect the section. section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider"); section.SectionInformation.ForceSave = true; // Save the change. config.Save(ConfigurationSaveMode.Modified); } ConfigurationManager.RefreshSection("EncryptedSection"); Properties.Settings.Default.Reset(); //This is the part where I read the encrypted section: ConfigurationManager.RefreshSection("EncryptedSection"); System.Collections.IDictionary HSMMasterKeyConfig = (System.Collections.IDictionary)System.Configuration.ConfigurationManager.GetSection("EncryptedSection"); ``` This only happens in the first time that I try to read the encrypted section. I have noticed that the .config file is getting updated immediately after the first save but from some reason I need to restart the application in order to use the encrypted section.
For your reference the issue was that the process that was trying to encrypt the config section didn't have admin rights. I added this process to the administrators group and that solved it.
Have you read through this... <http://bytes.com/groups/net/521818-configurationerrorexception-when-reading-protected-config-section> ... as it appears to be a conversation involving an MSFT support engineer that directly maps to your situation.
App.config - encrypted section error:
[ "", "c#", ".net", "xml", "configuration", "" ]
I am trying to save my contact, which has references to ContactRelation (just the relationship of the contact, married, single, etc) and Country. But everytime I try to save my contact, which is validated I get the exception "ADO.Net Entity Framework An entity object cannot be referenced by multiple instances of IEntityChangeTracker" ``` public Contact CreateContact(Contact contact) { _entities.AddToContact(contact); //throws the exception _entities.SaveChanges(); return contact ; } ``` I'm using a loosely coupled MVC design with Services and Repositories. I've read a lot of posts about this exception but none give me a working answer... Thank you, Peter
**[Update]** Because L2E is used you need to save all the linked objects first before you can save the main object. Which makes sense otherwise you would create (in my example) an artist without it's contact object. This isn't allowed by the database design. **[/Update]** Here's my implementation which worked. ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Exclude = "Id")] Artist artist, [Bind(Prefix = "Contact")] Contact contact, [Bind(Prefix = "Country")] Country country, [Bind(Prefix = "ContactRelationship")] ContactRelationship contactRelationship) { ViewData["Countries"] = new SelectList(new CountryService(_msw).ListCountries().OrderBy(c => c.Name), "ID", "Name"); ViewData["ContactRelationships"] = new SelectList(new ContactRelationshipService(_msw).ListContactRelationships().OrderBy(c => c.ID), "ID", "Description"); country = _countryService.GetCountryById(country.ID); contact.Country = country; contactRelationship = _contactRelationshipService.GetContactRelationship(contactRelationship.ID); contact.ContactRelationship = contactRelationship; if(_contactService.CreateContact(contact)){ artist.Contact = contact; if (_service.CreateArtist(artist)) return RedirectToAction("Index"); } return View("Create"); } ``` And then in my ContactRepository : ``` public Contact CreateContact(Contact contact) { _entities.AddToContact(contact); //no longer throws the exception _entities.SaveChanges(); return contact ; } ``` I also found on this website that it is best to keep the same context throughout the application so I'm now using a special Data class for this: Rick Strahl and Samuel Maecham have taught me that you should keep your datacontext per user per request. Which means putting it in the HttpContext for web applications. Read all about it [here](http://samscode.com/index.php/2009/12/making-entity-framework-v1-work-part-1-datacontext-lifetime-management/) ``` public class Data { public static MyDBEntities MyDBEntities { get { if (HttpContext.Current != null && HttpContext.Current["myDBEntities"] == null) { HttpContext.Current["myDBEntities"] = new MyDBEntities (); } return HttpContext.Current["myDBEntities"] as MyDBEntities; } set { if(HttpContext.Current != null) HttpContext.Current["myDBEntities"] = value; } } } ```
I've seen this before, you may have to convert the Reference field to an EntityKey before saving and then Load it after its saved. Try this code instead: ``` public Contact CreateContact(Contact contact){ contact.ConvertContactRelationToReference(); _entities.AddToContact(contact); //throws the exception _entities.SaveChanges(); contact.ContactRelation.Load(); return contact; } public partial class Contact { public void ConvertContactRelationToReference() { var crId = ContactRelation.Id; ContactRelation = null; ContactRelationReference.EntityKey = new EntityKey("MyEntities.ContactRelations", "Id", crId); } } ``` Of course, some of this code may need to be changed depending on your exact database structure.
ADO.Net Entity Framework An entity object cannot be referenced by multiple instances of IEntityChangeTracker
[ "", "c#", "entity-framework", "ado.net", "" ]
I'm trying to set up a Hibernate filter with annotations. I would like to specify it in a base class and make all sub classes use it but whenever I try to enable it, Hibernate fails to find the filter. Is it possible at all to inherit filter annotations?
Are you using the hibernate filter directly, or are you extending the hibernate filter for your own purposes? Annotations aren't inherited by default in Java, although if you were writing the annotation yourself, and I'm assuming hibernate didn't do this on their annotations, you can specify the @Inherited meta-annotation on your annotation to make it inherit. This only works for Type level annotations, though. Also, [some people](http://www.fusionsoft-online.com/articles-java-annotations.php) write an annotation manager to simulate full inheritance. You could do something like that, either extend hibernates mechanism or write a preprocessor that adds the annotations where they should have been inherited.
Since 3.5.0 it's at least possible for @MappedSuperclass. Not sure if that helps you... see: [HHH-4332](http://opensource.atlassian.com/projects/hibernate/browse/HHH-4332)
How can I inherit Hibernate filters with annotations?
[ "", "java", "hibernate", "filter", "annotations", "" ]
I've just recently discovered the functional programming style and I'm convinced that it will reduce development efforts, make code easier to read, make software more maintainable. However, the problem is I sucked at convincing anyone. Well, recently I was given a chance to give a talk on how to reduce software development and maintenance efforts, and I wanted to introduce them the concept of functional programming and how it benefit the team. I had this idea of showing people 2 set of code that does exactly the same thing, one coded in a very imperative way, and the other in a very functional way, to show that functional programming can made code way shorter, easier to understand and thus maintainable. Is there such an example, beside the famous sum of squares example by Luca Bolognese?
> I've just recently discovered the functional programming style [...] > Well, recently I was given a chance to give a talk on how to reduce > software development efforts, and I > wanted to introduce the concept of > functional programming. If you've only just discovered functional programming, I *do not* recommend trying to speak authoritatively on the subject. I know for the first 6 months while I was learnig F#, all of my code was just C# with a little more awkward syntax. However, after that period of time, I was able to write consistently good code in an idiomatic, functional style. I recommend that you do the same: wait for 6 months or so until functional programming style comes more naturally, then give your presentation. > I'm trying to > illustrate the benefits of functional > programming, and I had the idea of > showing people 2 set of code that does > the same thing, one coded in a very > imperative way, and the other in a > very functional way, to show that > functional programming can made code > way shorter, easier to understand and > thus maintain. Is there such example, > beside the famous sum of squares > example by Luca Bolognese? I gave an F# presentation to the .NET users group in my area, and many people in my group were impressed by F#'s pattern matching. Specifically, I showed how to traverse an abstract syntax tree in C# and F#: ``` using System; namespace ConsoleApplication1 { public interface IExprVisitor<t> { t Visit(TrueExpr expr); t Visit(And expr); t Visit(Nand expr); t Visit(Or expr); t Visit(Xor expr); t Visit(Not expr); } public abstract class Expr { public abstract t Accept<t>(IExprVisitor<t> visitor); } public abstract class UnaryOp : Expr { public Expr First { get; private set; } public UnaryOp(Expr first) { this.First = first; } } public abstract class BinExpr : Expr { public Expr First { get; private set; } public Expr Second { get; private set; } public BinExpr(Expr first, Expr second) { this.First = first; this.Second = second; } } public class TrueExpr : Expr { public override t Accept<t>(IExprVisitor<t> visitor) { return visitor.Visit(this); } } public class And : BinExpr { public And(Expr first, Expr second) : base(first, second) { } public override t Accept<t>(IExprVisitor<t> visitor) { return visitor.Visit(this); } } public class Nand : BinExpr { public Nand(Expr first, Expr second) : base(first, second) { } public override t Accept<t>(IExprVisitor<t> visitor) { return visitor.Visit(this); } } public class Or : BinExpr { public Or(Expr first, Expr second) : base(first, second) { } public override t Accept<t>(IExprVisitor<t> visitor) { return visitor.Visit(this); } } public class Xor : BinExpr { public Xor(Expr first, Expr second) : base(first, second) { } public override t Accept<t>(IExprVisitor<t> visitor) { return visitor.Visit(this); } } public class Not : UnaryOp { public Not(Expr first) : base(first) { } public override t Accept<t>(IExprVisitor<t> visitor) { return visitor.Visit(this); } } public class EvalVisitor : IExprVisitor<bool> { public bool Visit(TrueExpr expr) { return true; } public bool Visit(And expr) { return Eval(expr.First) && Eval(expr.Second); } public bool Visit(Nand expr) { return !(Eval(expr.First) && Eval(expr.Second)); } public bool Visit(Or expr) { return Eval(expr.First) || Eval(expr.Second); } public bool Visit(Xor expr) { return Eval(expr.First) ^ Eval(expr.Second); } public bool Visit(Not expr) { return !Eval(expr.First); } public bool Eval(Expr expr) { return expr.Accept(this); } } public class PrettyPrintVisitor : IExprVisitor<string> { public string Visit(TrueExpr expr) { return "True"; } public string Visit(And expr) { return string.Format("({0}) AND ({1})", expr.First.Accept(this), expr.Second.Accept(this)); } public string Visit(Nand expr) { return string.Format("({0}) NAND ({1})", expr.First.Accept(this), expr.Second.Accept(this)); } public string Visit(Or expr) { return string.Format("({0}) OR ({1})", expr.First.Accept(this), expr.Second.Accept(this)); } public string Visit(Xor expr) { return string.Format("({0}) XOR ({1})", expr.First.Accept(this), expr.Second.Accept(this)); } public string Visit(Not expr) { return string.Format("Not ({0})", expr.First.Accept(this)); } public string Pretty(Expr expr) { return expr.Accept(this).Replace("(True)", "True"); } } class Program { static void TestLogicalEquivalence(Expr first, Expr second) { var prettyPrinter = new PrettyPrintVisitor(); var eval = new EvalVisitor(); var evalFirst = eval.Eval(first); var evalSecond = eval.Eval(second); Console.WriteLine("Testing expressions:"); Console.WriteLine(" First = {0}", prettyPrinter.Pretty(first)); Console.WriteLine(" Eval(First): {0}", evalFirst); Console.WriteLine(" Second = {0}", prettyPrinter.Pretty(second)); Console.WriteLine(" Eval(Second): {0}", evalSecond);; Console.WriteLine(" Equivalent? {0}", evalFirst == evalSecond); Console.WriteLine(); } static void Main(string[] args) { var P = new TrueExpr(); var Q = new Not(new TrueExpr()); TestLogicalEquivalence(P, Q); TestLogicalEquivalence( new Not(P), new Nand(P, P)); TestLogicalEquivalence( new And(P, Q), new Nand(new Nand(P, Q), new Nand(P, Q))); TestLogicalEquivalence( new Or(P, Q), new Nand(new Nand(P, P), new Nand(Q, Q))); TestLogicalEquivalence( new Xor(P, Q), new Nand( new Nand(P, new Nand(P, Q)), new Nand(Q, new Nand(P, Q))) ); Console.ReadKey(true); } } } ``` The code above is written in an idiomatic C# style. It uses the visitor pattern rather than type-testing to guarantee type safety. This is about 218 LOC. Here's the F# version: ``` #light open System type expr = | True | And of expr * expr | Nand of expr * expr | Or of expr * expr | Xor of expr * expr | Not of expr let (^^) p q = not(p && q) && (p || q) // makeshift xor operator let rec eval = function | True -> true | And(e1, e2) -> eval(e1) && eval(e2) | Nand(e1, e2) -> not(eval(e1) && eval(e2)) | Or(e1, e2) -> eval(e1) || eval(e2) | Xor(e1, e2) -> eval(e1) ^^ eval(e2) | Not(e1) -> not(eval(e1)) let rec prettyPrint e = let rec loop = function | True -> "True" | And(e1, e2) -> sprintf "(%s) AND (%s)" (loop e1) (loop e2) | Nand(e1, e2) -> sprintf "(%s) NAND (%s)" (loop e1) (loop e2) | Or(e1, e2) -> sprintf "(%s) OR (%s)" (loop e1) (loop e2) | Xor(e1, e2) -> sprintf "(%s) XOR (%s)" (loop e1) (loop e2) | Not(e1) -> sprintf "NOT (%s)" (loop e1) (loop e).Replace("(True)", "True") let testLogicalEquivalence e1 e2 = let eval1, eval2 = eval e1, eval e2 printfn "Testing expressions:" printfn " First = %s" (prettyPrint e1) printfn " eval(e1): %b" eval1 printfn " Second = %s" (prettyPrint e2) printfn " eval(e2): %b" eval2 printfn " Equilalent? %b" (eval1 = eval2) printfn "" let p, q = True, Not True let tests = [ p, q; Not(p), Nand(p, p); And(p, q), Nand(Nand(p, q), Nand(p, q)); Or(p, q), Nand(Nand(p, p), Nand(q, q)); Xor(p, q), Nand( Nand(p, Nand(p, q)), Nand(q, Nand(p, q)) ) ] tests |> Seq.iter (fun (e1, e2) -> testLogicalEquivalence e1 e2) Console.WriteLine("(press any key)") Console.ReadKey(true) |> ignore ``` This is 65 LOC. Since it uses pattern matching rather than the visitor pattern, we don't lose any type-safety, and the code is very easy to read. *Any* kind of symbolic processing is orders of magnitude easier to write in F# than C#. [Edit to add:] Oh, and pattern matching isn't just a replacement for the visitor pattern, it also allows you to match against the *shape* of data. For example, here's a function which converts Nand's to their equivalents: ``` let rec simplify = function | Nand(p, q) when p = q -> Not(simplify p) | Nand(Nand(p1, q1), Nand(p2, q2)) when equivalent [p1; p2] && equivalent [q1; q2] -> And(simplify p1, simplify q1) | Nand(Nand(p1, p2), Nand(q1, q2)) when equivalent [p1; p2] && equivalent [q1; q2] -> Or(simplify p1, simplify q1) | Nand(Nand(p1, Nand(p2, q1)), Nand(q2, Nand(p3, q3))) when equivalent [p1; p2; p3] && equivalent [q1; q2; q3] -> Xor(simplify p1, simplify q1) | Nand(p, q) -> Nand(simplify p, simplify q) | True -> True | And(p, q) -> And(simplify p, simplify q) | Or(p, q) -> Or(simplify p, simplify q) | Xor(p, q) -> Xor(simplify p, simplify q) | Not(Not p) -> simplify p | Not(p) -> Not(simplify p) ``` Its not possible to write this code concisely at all in C#.
There are plenty examples out there but none will be as impact full as using a sample relevant to one of your projects at work. Examples like "Sum Of Squares" by Luca are awesome but if someone used that as proof as to how our code base could be written better I would not be convinced. All the example proves is some things are better wrote functionally. What you need to prove is your code base is better written functionally My advice would be to pick some popular trouble spots and some core spots in the code base, and rewrite them in a functional style. If you can demonstrate a substantially better solution, it will go a long way to winning over co-workers.
What task is best done in a functional programming style?
[ "", "c#", "f#", "c#-3.0", "functional-programming", "" ]
I have made a window with CreateWindowEx() function, now how do i get the width and height from that window i created? This sounds very basic thing to do, but i just couldnt find any answer ;\_; This is needed because the window height is created automatically depending on how the Windows wants to create it. Language C or C++
Use [GetWindowRect](http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx). Subtract the right from the left to get the width and the bottom from the top to get the height. ``` RECT rect; if(GetWindowRect(hwnd, &rect)) { int width = rect.right - rect.left; int height = rect.bottom - rect.top; } ``` As a side note, if you'd like the client area instead of the entire window. You can use [GetClientRect](http://msdn.microsoft.com/en-us/library/ms633503(VS.85).aspx). For other information about the window you can use [GetWindowInfo](http://msdn.microsoft.com/en-us/library/ms633516(VS.85).aspx).
I believe you're looking for [GetWindowInfo](http://msdn.microsoft.com/en-us/library/windows/desktop/ms633516(v=vs.85).aspx) Example: ``` HWND window = ::CreateWindowEx(...); WINDOWINFO info; if ( ::GetWindowInfo(window, &info) ) { ... } ```
How to get width and height from CreateWindowEx() window? C++
[ "", "c++", "c", "windows", "winapi", "window", "" ]
I have a testing struct definition as follows: ``` struct test{ int a, b, c; bool d, e; int f; long g, h; }; ``` And somewhere I use it this way: ``` test* t = new test; // create the testing struct int* ptr = (int*) t; ptr[2] = 15; // directly manipulate the third word cout << t->c; // look if it really affected the third integer ``` This works correctly on my Windows - it prints 15 as expected, but is it safe? Can I be really sure the variable is on the spot in memory I want it to be - expecially in case of such combined structs (for example f is on my compiler the fifth word, but it is a sixth variable)? If not, is there any other way to manipulate struct members directly without actually having struct->member construct in the code?
It looks like you are asking two questions **Is it safe to treat &test as a 3 length int arrray?** It's probably best to avoid this. This may be a defined action in the C++ standard but even if it is, it's unlikely that everyone you work with will understand what you are doing here. I believe this is not supported if you read the standard because of the potential to pad structs but I am not sure. **Is there a better way to access a member without it's name?** Yes. Try using the [offsetof](http://www.cplusplus.com/reference/clibrary/cstddef/offsetof.html) macro/operator. This will provide the memory offset of a particular member within a structure and will allow you to correctly position a point to that member. ``` size_t offset = offsetof(mystruct,c); int* pointerToC = (int*)((char*)&someTest + offset); ``` Another way though would be to just take the address of c directly ``` int* pointerToC = &(someTest->c); ```
No you can't be sure. The compiler is free to introduce padding between structure members.
Accessing struct members directly
[ "", "c++", "memory", "struct", "" ]
i want to be able to create a copy of the element that i want to drag. im using the standard ui draggable and droppable. i know about the helper clone option. but that does not create a copy. the dragged item gets reverted back to the original position.
Mark, Try this example: ``` $(document).ready(function(){ $(".objectDrag").draggable({helper:'clone'}); $("#garbageCollector").droppable({ accept: ".objectDrag", drop: function(event,ui){ console.log("Item was Dropped"); $(this).append($(ui.draggable).clone()); } }); }); ``` And the Html looks like this ``` <div class="objectDrag" style="width:10%; color:white;border:black 1px solid; background-color:#00A">Drag me</div> <div id="garbageCollector" style="width:100%; height:400px; background-color:#333; color:white;"> Drop items on me</div> ```
Since I'm not able to comment (yet) I'll leave this as a separate answer - in case someone, like me, will find this question: For the question from comment "But I want the cloned/dropped element to be in the same position it was dropped. do you know how i can do it?" I've found solution in different SO question, and the answer is to change this line: ``` $(this).append($(ui.draggable).clone()); ``` to ``` $(this).append($(ui.helper).clone()); ``` (change ui.draggable to ui.helper) Hope it helps.
clone node on drag
[ "", "javascript", "jquery", "clone", "draggable", "" ]
I am working on a system that requires interaction with a native C API using P/Invoke. Now I've (yet again) stumbled upon a problem which I cannot seem to solve in any way. The original function is designed to return 2 kinds of structures, based on a parameter that specifies which structure to use. The C header file defines the structures and function as follows: ``` #pragma pack(1) typedef struct { DWORD JobId; DWORD CardNum; HANDLE hPrinter; } CARDIDTYPE, FAR *LPCARDIDTYPE; #pragma pack() typedef struct { BOOL bActive; BOOL bSuccess; } CARD_INFO_1, *PCARD_INFO_1, FAR *LPCARD_INFO_1; typedef struct { DWORD dwCopiesPrinted; DWORD dwRemakeAttempts; SYSTEMTIME TimeCompleted; } CARD_INFO_2, *PCARD_INFO_2, FAR *LPCARD_INFO_2; BOOL ICEAPI GetCardId(HDC hdc, LPCARDIDTYPE pCardId); BOOL ICEAPI GetCardStatus(CARDIDTYPE CardId, DWORD level, LPBYTE pData, DWORD cbBuf, LPDWORD pcbNeeded ); ``` I have attempted to implement P/Invoke wrappers like this: ``` [StructLayout(LayoutKind.Sequential, Pack=1)] public class CARDIDTYPE { public UInt32 JobId; public UInt32 CardNum; public IntPtr hPrinter; } [StructLayout(LayoutKind.Sequential)] public class CARD_INFO_1 { public bool bActive; public bool bSuccess; } [StructLayout(LayoutKind.Sequential)] public class CARD_INFO_2 { public UInt32 dwCopiesPrinted; public UInt32 dwRemakeAttempts; public Win32Util.SYSTEMTIME TimeCompleted; } [DllImport("ICE_API.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardId(HandleRef hDC, [Out]CARDIDTYPE pCardId); [DllImport("ICE_API.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardStatus(CARDIDTYPE CardId, UInt32 level, [Out] byte[] pData, UInt32 cbBuf, out UInt32 pcbNeeded); ``` Calling the "GetCardId" seems to work fine. I get plausible data in CARDIDTYPE instance after calling it. However when I call "GetCardStatus" the problems start. The type of structure that should be returned is defined by the "level" param, and a value of 1 should result in a CARD\_INFO\_1 structure to be returnes in "pData". The documentation contains the following C example: ``` CARD_INFO_1 ci1; DWORD cbNeeded; ci1.bActive = TRUE; if (GetCardStatus(*lpCardID, 1, (LPBYTE)&ci1, sizeof(ci1), &cbNeeded )) { /* success */ } ``` My equivalent C# implementation is like this: ``` uint needed; byte[] byteArray = new byte[Marshal.SizeOf(typeof(CARD_INFO_1))]; if (GetCardStatus(cardId, 1, byteArray, (uint)byteArray.Length, out needed)) { /* success */ } ``` When I execute this C# code, the method returns false and Marshal.GetLastWin32Error() return -1073741737 (which does not make much sense to me). I see no reason why this call should fail, and definitely not with this error code. So I suspect I have got something wrong in my P/Invoke wrapper. I know that using "byte[]" as the type of pData is probably not correct, but according to some googling a "LPBYTE" translates to "[Out] byte[]". I guess the correct way to do this is to have pData as an IntPtr, and create the structure using Marshal.PtrToStructure(...). I have tried this, but the result is the same. Here is the code for this scenario: ``` [DllImport(@"ICE_API.DLL", CharSet = CharSet.Auto, EntryPoint = "_GetCardStatus@28", CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardStatus(CARDIDTYPE CardId, UInt32 level, IntPtr pData, UInt32 cbBuf, out UInt32 pcbNeeded); uint needed; int memSize = Marshal.SizeOf(typeof(CARD_INFO_1)); IntPtr memPtr = Marshal.AllocHGlobal(memSize); if (!GetCardStatus(cardId, 1, memPtr, (uint)memSize, out needed)) { int lastError = Marshal.GetLastWin32Error(); // error code is -1073741737 } CARD_INFO_1 info = (CARD_INFO_1)Marshal.PtrToStructure(memPtr, typeof(CARD_INFO_1)); Marshal.FreeHGlobal(memPtr); ``` **Edit:** One thing I forgot to mention is that for some reason the GetCardStatus call fails with an unknown entry point exception if I do not specify EntryPoint = "\_GetCardStatus@28". This has not happened to any other function I have wrapped, so it got me wondering a bit.
`_GetCardStatus@28` gave me an idea. Unless you are running on 64-bit Windows, you've got the number of arguments wrong. Your P/Invoke for `GetCardStatus` would be `_GetCardStatus@20`, because it has 5 32-bit arguments. Your C declaration of `GetCardStatus` seems to accept the `cardId` by value rather than by reference. Since `CARDIDTYPE` is 12 bytes long, this would give the correct length of the argument list (28). Moreover, this would explain both your receiving an error code of -1073741737 (C0000057, `STATUS_INVALID_PARAMETER`) — since you're not passing a valid `cardId` — *and* the access violation — `GetCardStatus` tries to write to `pcbNeeded`, which is garbage because the marshaler hasn't even pushed it! Ergo: ``` [DllImport("ICE_API.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardStatus ( IntPtr hPrinter, UInt32 cardNum, UInt32 jobId, UInt32 level, [In, Out] CARD_INFO_1 data, UInt32 cbBuf, out UInt32 pcbNeeded) ; [DllImport("ICE_API.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardStatus ( IntPtr hPrinter, UInt32 cardNum, UInt32 jobId, UInt32 level, [In, Out] CARD_INFO_2 data, UInt32 cbBuf, out UInt32 pcbNeeded) ; ``` Note reverse order of the three `CARDIDTYPE` members: `stdcall` pushes the parameters left-to-right (i.e. towards lower addresses), and my guess is that a `struct` is "pushed" as a unit. Also, if you later close the printer handle with `CloseHandle`, I'd suggest receiving the handle in `CARDIDTYPE` into an appropriate `SafeHandle`, not into a bare `IntPtr`, and declaring `GetCardStatus` to receive the safe handle.
As Anton suggests the problem lies in the parameters passed to the function. I did not notice this yesterday but the CARDIDTYPE structure is passed by pointer in the GetCardID function, and by value in the GetCardStatus function. In my calls I passed the CARDIDTYPE by pointer to the GetCardStatus also, forcing the P/Invoke framework to locate the correct function by specifying the exact function name as found in Dependecy Walker. I solved this by defining the CARDIDTYPE as a struct instead of a class, and pass it by reference to the GetCardId function. Further the CARDIDTYPE is marshaled as a Struct when passed to the GetCardStatus function. This in addition to Antons technique of using two function definitions with different pData types (CARD\_INFO\_1 and CARD\_INFO\_2) now works correctly. Here is the final definitions: ``` [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct CARDIDTYPE { public UInt32 JobId; public UInt32 CardNum; public IntPtr hPrinter; } [StructLayout(LayoutKind.Sequential)] public class CARD_INFO_1 { public bool bActive; public bool bSuccess; } [StructLayout(LayoutKind.Sequential)] public class CARD_INFO_2 { public UInt32 dwCopiesPrinted; public UInt32 dwRemakeAttempts; public Win32Util.SYSTEMTIME TimeCompleted; } [DllImport("ICE_API.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardId(HandleRef hDC, ref CARDIDTYPE pCardId); [DllImport(@"ICE_API.DLL", EntryPoint = "GetCardStatus", CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardStatus([MarshalAs(UnmanagedType.Struct)]CARDIDTYPE CardId, UInt32 level, [In, Out] CARD_INFO_1 pData, UInt32 cbBuf, out UInt32 pcbNeeded); [DllImport(@"ICE_API.DLL", EntryPoint = "GetCardStatus", CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool GetCardStatus([MarshalAs(UnmanagedType.Struct)]CARDIDTYPE CardId, UInt32 level, [In, Out] CARD_INFO_2 pData, UInt32 cbBuf, out UInt32 pcbNeeded); ``` Thank you both for your contribution to solving this problem :-)
P/Invoke function call problem
[ "", "c#", "function", "struct", "pinvoke", "" ]
I don't see it in the .sln file, which is what I expected.
Which project is the "startup" project only has any relevance for debugging, which means it's user metadata from the point of the solution and the projects. Regardless of which project is the "startup" project, the compiled code is the same. Because of this, the information is stored as a user setting in the Solution User Options file (solution.suo) which accompanies the Solution file (solution.sln). The .suo file "Records all of the options that you might associate with your solution so that each time you open it, it includes customizations that you have made" according to [MSDN](http://msdn.microsoft.com/en-us/library/xhkhh4zs.aspx). The .suo file is a binary file. If you want to read or change it programatically, you have to use [`IVsPersistSolutionOpts.LoadUserOptions`](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.shell.interop.ivspersistsolutionopts.loaduseroptions.aspx) from the `Microsoft.VisualStudio.Shell.Interop` namespace.
It's in the [Solutions User Options](http://msdn.microsoft.com/en-us/library/bb165909(VS.80).aspx) (.suo) file, which gets created next to the .sln file.
Where is "Set as Startup" defined and persisted in C# winforms solutions?
[ "", "c#", "projects-and-solutions", "" ]
I am submitted a getJSON request to a controller in my application, this controller is returning valid JSON with 2 "applications." I know this for a fact as if I move the alert statement to within jQuery's each function it will give me the expected result. I am attempting to store this data within a multidimensional array to later be used with extJS' Menu Control. Code: ``` Ext.onReady(function() { var applicationList = []; jQuery.getJSON('index.php/applications', function(data) { jQuery.each(data.applications, function (i, app) { applicationList[i] = []; applicationList[i]['text'] = app['title']; applicationList[i]['id'] = app['slug']; }); }); alert(applicationList[0]['text']); var applicationMenu = Ext.menu.Menu({ items: applicationList }); }); ``` JSON Response: ``` {"applications":[{"slug":"test","title":"Test"},{"slug":"hardware","title":"Hardware"}]} ``` Expected Result: > Test Actual Result (from Firebug): > applicationList[0] is undefined If I replace the `alert()` above, with the following code I get one alert window with the text "remove": ``` for (p in applicationList) { alert(p); } ``` Now, my thinking is that the JSON request isn't completing in-time for the `alert()` so I'll use a named callback function to ensure the request has completed: ``` var data; jQuery.getJSON('index.php/applications', get_applications(data)); function get_applications(data) { jQuery.each(data.applications, function (i, app) { applicationList[i] = []; applicationList[i]['text'] = app['title']; applicationList[i]['id'] = app['slug']; }); }; ``` But now Firebug is telling me that `data is undefined`... I feel like I am almost there, but I've been almost there for the past hour and I feel as if I am just polluting the source now in trying to get it to work.
This should do it: ``` Ext.onReady(function() { var applicationList = []; var applicationMenu; jQuery.getJSON('index.php/applications', function(data) { jQuery.each(data.applications, function (i, app) { applicationList[i] = []; applicationList[i]['text'] = app['title']; applicationList[i]['id'] = app['slug']; }); applicationMenu = Ext.menu.Menu({ items: applicationList }); }); }); ``` Your thinking is right; the reason it is not working is because AJAX is an asynchronous process and as you fire off the getJSON function javascript keeps on trucking along. Your solution doesn't work because making it a named callback is not changing the fact that it won't be fired until you've already tried to initialize the Menu. All my solution is doing is moving the Menu initilization code INSIDE the callback, as it is then and only then that you will have access to the filled out applicationList.
You're right, you should use your "applicationList" variable only after the getJSON callback has finished. You should call Ext.menu.Menu() inside your getJSON callback, after jQuery.each().
Multidimensional Arrays and jQuery's getJSON
[ "", "javascript", "jquery", "json", "" ]
This question is related to Symbian OS yet I think that C/C++ veteran can help me too. I'm compiling an open source library to Symbian OS. Using a GCCE compiler it compiles with no errors (after some tinkering :) ). I changed compiler to ARMV5 and now I have multiple errors with the definitions of static const structs, for example: I have a struct: ``` typedef struct Foos{ int a; int b; } Foos; ``` And the following definition of a const struct of type Foos ``` static const Foos foo = { .a = 1, .b = 2, }; ``` GCCE has no problem with this one and ARMV5 goes "expected an expression" error on the ".a = 1, .b = 2,". From what I googled regarding this I reckon that this method should be legal in C but illegal in C++, if that's the case then what are the possibilities for declaring const structs in C++ ? If that's not the case then any other help will be appreciated. Thanks in advance :)
``` static const struct Foos foo = { 1, 2 }; ``` Compiles with both g++ and gcc. You could ofcourse, as onebyone points out, define a constructor: ``` typedef struct Foos { int a; int b; Foos(int a, int b) : a(a), b(b) {} }; ``` Which you would initalize like so: ``` static const struct Foos foo(1, 2); ```
That's legal C99, but not legal C89 or C++. Presumably you're compiling this as C++, so if you use compiler options to enforce standards-compliance, then GCCE will reject it too. You can do `foo = {1, 2};` in C or C++. Obviously you lose the benefit of the field names being right there: you have to rely on getting the order right. Another good option in C++ is to define a constructor for your struct, and initialize with `static const Foos foo(1,2);`. This does prevent the struct being POD, however, so you can't make the same assumptions about its representation in memory.
defining static const structs
[ "", "c++", "c", "symbian", "" ]
Consider the following HTML. If I have a JSON reference to the <button> element, how can I get a reference to the outer <tr> element in both cases ``` <table id="my-table"> <tr> <td> <button>Foo</button> </td> <td> <div> <button>Bar</button> </div> </td> </tr> </table> <script type="text/js"> $('#table button').click(function(){ //$(this).parent().parent() will work for the first row //$(this).parent().parent().parent() will work for the second row //is there a selector or some magic json one liner that will climb //the DOM tree until it hits a TR, or do I have to code this myself //each time? //$(this).???? }); </script> ``` I know I could special case each condition, but I'm more interested "however deep you happen to be, climb the tree until you find element X" style solution. Something like this, but more jQuery like/less-verbose ``` var climb = function(node, str_rule){ if($(node).is(str_rule)){ return node; } else if($(node).is('body')){ return false; } else{ return climb(node.parentNode, str_rule); } }; ``` I know about the parent(expr) method, but from what I've seen is allows you filter parents one level up and NOT climb the tree until you find expr (I'd love code example proving me wrong)
The [parents](https://api.jquery.com/parents/) function does what you want: ``` $(this).parents("tr:first"); ```
Also, if you are using jQuery 1.3+ you can use the [closest](https://api.jquery.com/closest/) method ``` $(this).closest("tr"); ```
Is there a jQuery selector/method to find a specific parent element n levels up?
[ "", "javascript", "jquery", "dom", "jquery-selectors", "" ]
What is a good way to find the index of an element in a list in Python? Note that the list may not be sorted. Is there a way to specify what comparison operator to use?
The best way is probably to use the [list method .index](https://docs.python.org/tutorial/datastructures.html#more-on-lists). For the objects in the list, you can do something like: ``` def __eq__(self, other): return self.Value == other.Value ``` with any special processing you need. You can also use a for/in statement with enumerate(arr) Example of finding the index of an item that has value > 100. ``` for index, item in enumerate(arr): if item > 100: return index, item ``` [Source](http://www.daniweb.com/forums/thread174502.html)
From [Dive Into Python](http://www.diveintopython.net/native_data_types/lists.html): ``` >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements'] >>> li.index("example") 5 ```
Python: finding an element in a list
[ "", "python", "list", "" ]
Need: Find a way to add a valid tag/attribute/property to a normal html control. What I have is some javascript/jquery adding a click event to a link that will show or hide a div. The idea is to do this using $(document).ready and an anonymous method to create the method called by onClick at the page load. When clicked, a div will be shown with some text. This is all well and good except I can't figure out how to set up the text so that this can be done on the page load. What I'd like is something like: ``` <a href="..." class="showItLink" textToShow="This is the text to show">HI</a> ``` so that I can do this: ``` $(document).ready ( function() { $("..showItLink").click ( function(event) { var containerPosition; var createdDiv; //see if the div already exists createdDiv = $(this).children(".postComment"); if (createdDiv.length == 0) { //This is where the attribute is used so that the CreateDiv //method can take the textToShow and fill the div's innerText //with it V V V V V V createdDiv = CreateDiv(this.textToShow, "postComment"); $(this).append(createdDiv); $(this).children(".postComment").hide(); } $(createdDiv).toggle(); event.preventDefault(); } ); } ); ``` Now besides not being xhtml valid (meh), this only works in IE. Firefox just says it doesn't exist. (this.textToShow) I could use something like rel or rev, but that seems just as hackish. I was wondering if there is a valid way of doing this. **Solution from answer below** ``` comment = $(".showItLink").attr("comment"); ... createdDiv = CreateDiv(comment, "postComment"); ``` Paired with: ``` <a href="http://www.theironical.com" class="showItLink" comment="hihihi" >HI</a> ```
If you're using JQuery, just get and set the attributes with .attr(). Get: this.attr("textToShow") Set: this.attr("textToShow", value)
You can't get away with adding custom attributes to HTML elements whilst still being valid. It will generally work in current browsers, but it's a bit fragile in that if you happen to pick a name that is in use (now or in the future) as an HTML or JavaScript property by any browser, the clash will stop it from working. HTML5 proposes attributes whose names start with “data-​” as valid extension mechanisms. You could also consider namespaced elements in XHTML; this still isn't technically “valid XHTML” by the DTD but at least it is safe from collisions. > <a href="..." class="showItLink" textToShow="This is the text to show">HI I suggest using the ‘title’ attribute for this particular purpose.
Html/Javascript: Add Attribute to an HTML Control
[ "", "javascript", "jquery", "dynamic", "" ]
I have old code that uses `new Date(dateString)` to parse a date string. Compiling the code produces the deprecation warning *`Date(java.lang.String) in java.util.Date has been deprecated`*. The javadoc unhelpfully advises me to use `DateFormat.parse()`, even though the `DateFormat` class does not have a static `parse` method. Now, I know how to use `SimpleDateFormat`, but I want to make sure I'm getting the **exact same behaviour** of the deperecated `Date` constructor.
Here's my guess (I posted as community wiki so you can vote up if I'm right): ``` Date parsed; try { SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); parsed = format.parse(dateString); } catch(ParseException pe) { throw new IllegalArgumentException(pe); } ```
SimpleDateFormat is the way to go. Can I point out, however, that you may feel compelled to define one SimpleDateFormat instance and build Date objects using this. If you do, beware that SimpleDateFormat is not thread-safe and you may be exposing yourself to some potentially hard-to-debug issues! I'd recommend taking this opportunity to look at [Joda](http://joda-time.sourceforge.net/) which is a much better thought-out (and thread-safe) API. It forms the basis of JSR-310, which is the new proposed Java Date API. I understand this is a bit more work. However it's probably worthwhile given that you're having to refactor code at the moment.
A non-deprecated exact equivalent of Date(String s) in Java?
[ "", "java", "date", "" ]
I came across this code: ``` void f(const std::string &s); ``` And then a call: ``` f( *((std::string*)NULL) ); ``` And I was wondering what others think of this construction, it is used to signal that function f() should use some default value (which it computes) instead of some user provided value. I am not sure what to think of it, it looks weird but what do you think of this construction?
No. It is undefined behaviour and can lead to code to do anything (including reformatting you hard disk, core dumping or insulting your mother). If you need to be able to pass NULL, then use pointers. Code that takes a reference can assume it refers to a valid object. --- Addendum: The C++03 Standard (ISO/IEC 14882, 2nd edition 2003) says, in §8.3.2 "References", paragraph 4: > A reference shall be initialized to refer to a valid object > or function. [*Note:* in particular, a null reference cannot exist in a well-defined program, because the **only > way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, > which causes undefined behavior.** As described in 9.6, a reference cannot be bound directly to a bit-field. ] [Bold added for emphasis]
You will sometimes see constructions like this in fairly esoteric template library code, but only inside a `sizeof()` where it is harmless. Supposing you wanted to know the size of the return type of a function-like type `F` if it was passed a reference to a type `T` as an argument (both of those being template parameters). You could write: ``` sizeof(F(T())) ``` But what if T happens to have no public default constructor? So you do this instead: ``` sizeof(F(*((T *)0))) ``` The expression passed to `sizeof` never executes - it just gets analyzed to the point where the compiler knows the size of the result.
Is using NULL references OK?
[ "", "c++", "" ]
I'd like to map string to an instance member functions, and store each mapping in the map. What is the clean way of doing something like that? ``` class MyClass { //........ virtual double GetX(); virtual double GetSomethingElse(); virtual double GetT(); virtual double GetRR(); //........ }; class Processor { private: typedef double (MyClass::*MemFuncGetter)(); static map<std::string, MemFuncGetter> descrToFuncMap; public: static void Initialize(); void Process(Myclass m, string); }; void Processor::Initialize() { descrToFuncMap["X"]=&MyClass::GetX; descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse; descrToFuncMap["RR"]=&MyClass::GetRR; descrToFuncMap["T"]=&MyClass::GetT; }; void Processor::Process(MyClass ms, const std::string& key) { map<std::string, Getter>::iterator found=descrToFuncMap.find(key); if(found!=descrToFuncMap.end()) { MemFuncGetter memFunc=found->second; double dResult=(ms).*memFunc(); std::cout<<"Command="<<key<<", and result="<<result<<std::end; } } ``` let me know if you see a problem with this approach and what are common idioms for that? **Perhaps, I should use if-else-if statement chain, given that I have a limited number of member functions, instead of a confusing map of func pointers** BTW, I found some of the useful info here in the [c++-faq-lite](http://www.parashift.com/c++-faq-lite/pointers-to-members.html)
Looks fine to me, but for the fact that `descrToFuncMap` needs to be declared `static` if you intend to initialise it from inside the static function `Initialize()`. If you want to make sure that `Initialize()` gets called, and gets called just once, you can use the Singleton pattern. Basically, if you aren't doing multithreading, that just means wrapping `descrToFuncMap` inside its own class (called say `FuncMap`) with a private constructor that calls `Initialize()`. Then you add a `static` local variable of type `FuncMap` to `Processor::Process()` -- because the variable is `static`, it persists and is only initialised once. Example code (I now realise that `friend` isn't really necessary here): ``` class Processor { private: typedef double (MyClass::*MemFuncGetter)(); class FuncMap { public: FuncMap() { descrToFuncMap["X"]=&MyClass::GetX; descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse; descrToFuncMap["RR"]=&MyClass::GetRR; descrToFuncMap["T"]=&MyClass::GetT; } // Of course you could encapsulate this, but its hardly worth // the bother since the whole class is private anyway. map<std::string, MemFuncGetter> descrToFuncMap; }; public: void Process(Myclass m, string); }; void Processor::Process(MyClass ms, const std::string& key) { static FuncMap fm; // Only gets initialised on first call map<std::string, Getter>::iterator found=fm.descrToFuncMap.find(key); if(found!=fm.descrToFuncMap.end()) { MemFuncGetter memFunc=found->second; double dResult=(ms).*memFunc(); std::cout<<"Command="<<key<<", and result="<<result<<std::end; } } ``` This is not the "true" Singleton pattern as different functions could create their own, separate instances of `FuncMap`, but it's enough for what you need. For "true" Singleton, you would declare `FuncMap`'s constructor private and add a static method, say `getInstance()`, which defined the one-and-only instance as a `static` variable and returned a reference to that. `Processor::Process()` would then use this with ``` FuncMap& fm = FuncMap::getInstance(); ```
Avoid using 'virtual' if you are using maps of function pointers. In this context, using 'virtual' keyword will not help much. For example ``` descrToFuncMap["X"]=&MyClass::GetX; ``` will always call '*MyClass::GetX*' function even if *GetX* is overridden by the derived class of MyClass. Usually you won't have large number of functions in class, rather than using map you can create simple struct array and use a for loop. If the number of functions are small, there won't be any big performance difference in map and array. Something similar to code below will work ``` class MyClass { //........ double GetX(); double GetSomethingElse(); double GetT(); double GetRR(); //........ }; typedef double (MyClass::*MemFuncGetter)(); struct FuncTable { const char* m_pFuncName; MemFuncGetter m_pFuncPtr; }; class Processor { public: void Process(Myclass& m, string); }; static FuncTable descrToFuncMap[] { { "X", &MyClass::GetX}, { "SomethingElse", &MyClass::GetSomethingElse }, { "RR", &MyClass::GetRR}, { "T", &MyClass::GetT} }; void Processor::Process(MyClass& ms, const std::string& key) { int functablesize = sizeof(descrToFuncMap)/sizeof(descrToFuncMap[0]) for(int i=0; i< functablesize; ++i) { if( strcmp(key.c_str(), descrToFuncMap[i].m_pFuncName)==0) { MemFuncGetter memFunc=descrToFuncMap[i].m_pFuncPtr; double dResult=(ms).*memFunc(); std::cout<<"Command="<<key<<"result="<<result<<std::end; break; } } } ```
Store pointers to member function in the map
[ "", "c++", "design-patterns", "callback", "" ]
Scenario: A WCF service receives an XDocument from clients, processes it and inserts a row in an MS SQL Table. Multiple clients could be calling the WCF service simultaneously. The call usually doesn't take long (a few secs). Now I need *something* to poll the SQL Table and run another set of processes in an asynchronous way. The 2nd process doesn't have to callback anything nor is related to the WCF in any way. It just needs to read the table and perform a series of methods and maybe a Web Service call (if there are records of course), but that's all. The WCF service clients consuming the above mentioned service have no idea of this and don't care about it. I've read about [this question in StackOverflow](https://stackoverflow.com/questions/536681/can-i-use-threads-to-carry-out-long-running-jobs-on-iis) and I also know that a Windows Service would be ideal, but this WCF Service will be hosted on a Shared Hosting (discountasp or similar) and therefore, installing a Windows Service will not be an option (as far as I know). Given that the architecture is fixed (I.E.: I cannot change the table, it comes from a legacy format, nor change the mechanism of the WCF Service), what would be your suggestion to poll/process this table? I'd say I need it to check every 10 minutes or so. It doesn't need to be instant. Thanks.
Cheat. Expose this process as another WCF service and fire a go command from a box under your control at a scheduled time. Whilst you can fire up background threads in WCF, or use cache expiry as a poor man's scheduler those will stop when your app pool recycles until the next hit on your web site and the app pool spins up again. At least firing the request from a machine you control means you know the app pool will come back up every 10 minutes or so because you've sent a request in its direction.
A web application is not suited at all to be running something at a fixed interval. If there are no requests coming in, there is no code running in the application, and if the application is inactive for a while the IIS can decide to shut it down completely until the next request comes in. For some applications it isn't at all important that something is run at a specific interval, only that it has been run recently. If that is the case for your application then you could just keep track of when the table was last polled, and for every request check if enough time has passed for the table to be polled again. If you have access to administer the database, there is a scheduler in SQL Server. It can run queries, stored procedures, and even start processes if you have permission (which is very unlikely on a shared hosting, though). If you need the code on a specific interval, and you can't access the server to schedule it or run it as a service, or can't use the SQL Server scheduler, it's simply not doable.
Best approach to fire Thread/Process under IIS/WCF, in a shared hosting
[ "", "c#", "asp.net", "wcf", "multithreading", "shared-hosting", "" ]
I'd like to implement an interface that resides in an external assembly. However that particular interface has been marked as "internal". Is there a way I can still implement this interface for my own classes? I know how to call private/internal methods using reflection in C#, so I guess reflection should be used in this case too. However, I don't know how. And yes, I do know it usually isn't wise to use internal/private stuff, but in this case I see no other solution. **Update:** I'm not able to edit / change the external assembly in any way. It should be left untouched.
You can't do that, unless you can change the assembly containing the interface to add an [InternalsVisibleToAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx), targeting your own assembly.
Use the InternalsVisibleToAttribute in the external assembly to point to the assembly that you want to expose internal types to. <http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx>
Use an interface from an external assembly that's marked as "internal" (C#)
[ "", "c#", ".net", "reflection", "interface", "" ]
What's the uninitialized value in Python, so I can compare if something is initialized, like: ``` val if val == undefined ? ``` EDIT: added a pseudo keyword. EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.
Will throw a `NameError` exception: ``` >>> val Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'val' is not defined ``` You can either catch that or use `'val' in dir()`, i.e.: ``` try: val except NameError: print("val not set") ``` or ``` if 'val' in dir(): print('val set') else: print('val not set') ```
In python, variables either refer to an object, or they don't exist. If they don't exist, you will get a NameError. Of course, one of the objects they might refer to is `None`. ``` try: val except NameError: print "val is not set" if val is None: print "val is None" ```
Uninitialized value in Python?
[ "", "python", "" ]
In PHP you can use square brackets on an element to access attributes: ``` $node = /* SimpleXMLElement */ $id = $node['id']; ``` What's weird is that `$id` isn't a string, It's another `SimpleXMLElement`. Why isn't it a string? I find myself using `strval()` all over the place on this. How are the square brackets working? Can I do that with my own classes? I Haven't seen anything in the docs about this.
You can provide Array like access to your object by implementing the [ArrayAccess interface](https://www.php.net/ArrayAccess), which is part of the PHP Standard Library. This interface is one of those "even if you don't have the full PHP Standard Library extension installed, you still have this interface available in PHP 5" things. By implementing this interface, and defining four methods for your class ``` public boolean offsetExists ( string $offset ) public mixed offsetGet ( string $offset ) public void offsetSet ( string $offset , string $value ) public void offsetUnset ( string $offset ) ``` you should be able to use square brackets with your instantiated objects. As for SimpleXML itself, I'm not sure if it actually implements the ArrayAccess interface, or if there's something else going on behind the scenes in the PHP source that gives it these super powers.
I believe you can extend the SimpleXML class, and implement the ArrayAccess in that.
How does Simple XML use the [] operator?
[ "", "php", "arrays", "operators", "simplexml", "" ]
I've got the following request : ``` select * from tbA A, tbB B, tbC C, tbD D where A.ID=B.ID and B.ID2= C.ID2 and A.ID=D.ID and C.ID3=D.ID3 and B.ID4=D.ID4 and A.Foo='Foo' ``` I've heard several times that this join syntax is depreciated, and that I should use the 'JOIN' keyword instead. How do I do that in such a complicated join (multiple tables joined on multiple columns belonging to different tables)? Do you think this best practice still applies here ?
It's a matter of taste, but I like the JOIN keyword better. It makes the logic clearer and is more consistent with the LEFT OUTER JOIN syntax that goes with it. Note that you can also use INNER JOIN which is synonymous with JOIN. The syntax is ``` a JOIN b ON expression relating b to all of the tables before ``` b can be a join itself. For inner joins it doesn't matter, but for outer you can control the order of the joins like this: ``` select * from a left join d join c on d.i = c.i on a.k = d.k ``` Here a is left-joined to the inner join between d and c. Here is your query: ``` select * from tbA A join tbB B on A.ID = B.ID join tbC C on B.ID2 = C.ID2 join tbD D on A.ID = D.ID and C.ID3 = D.ID3 and B.ID4 = D.ID4 where A.Foo='Foo' ```
I find join syntax much easier to understand ``` select * from tbA A inner join tbB B on a.id = b.id inner join tbC C on b.id2 = c.id2 inner join tbD D on a.id = d.id and c.id3 = d.id3 and b.id4 = d.id4 where A.Foo='Foo' ``` Now you can clearly see how data are joined together and that it is not a very complicated join altogether. BTW, the database design in your example strongly smells of lacking normalization. Usually you should have either one table joining to many (a join b on a.bid = b.bid join c on a.cid= c.cid) or a chain (a join b on a.bid = b.bid join c on b.cid = c.cid). EDIT. Added optional keyword INNER which does not change result, but makes it more clear.
Should I use the sql JOIN keyword for complex joins on multiple tables?
[ "", "sql", "join", "" ]
In a GridView, I'm trying to show either one column or an other using a public Boolean property: ``` <Columns> ... <asp:BoundField Visible="<%= !ShowPurchaseDate %>" DataField="Published" HeaderText="Publicerad" SortExpression="PriceRange" DataFormatString="{0:yyyy.MM.dd}" HtmlEncode="false" /> <asp:BoundField Visible="<%= ShowPurchaseDate %>" DataField="OrderDate" HeaderText="Köpt" SortExpression="OrderDate" DataFormatString="{0:yyyy.MM.dd}" HtmlEncode="false" /> ... </Columns> ``` But I'm getting an error message saying that it's not possible to create a System.Boolean from a string that contains <% !ShowPurchaseDate %> for property Visisble. How can I achive this? UPDATE: <%# !ShowPurchaseDate %> doesn't work either as there's no databinding going on. Using a protected funktion doesn't work either (same error message as with property).
I solved it through: ``` gridMain.Columns[ShowPurchaseDate ? 3 : 4].Visible = false; ``` Is this the best solution?
Provide a protected method in the code behind that returns the boolean property as a string.
ASP.net: Dynamic BoundFields
[ "", "c#", "asp.net", "" ]
I have this code (question from exam) and there are many errors in the code, here is the code: ``` class A { int z; static int y; public: A() {(*this).incrementY();} int x () { y=y+2; return z;} static int getY(){ return z;} void incrementY() {y++} }; class B: A { public: B (): A() {(*this).incrementY();}; }; class C : public B { public: C(): B() {(*this).incrementY;() } }; int main() { A::x(); A a; a.getY(); A::getY(); B b; C c; C::getY(); b.x(); } ``` There is a private inheritance. This means that all the methods and variables in B become private to any class that inherits from B?
You are correct there (although it actually means that all *A*'s methods become inaccessible). However, there are a few other problems: ``` A::x() // will not work as x is not static. a.getY() // will not work as getY() is static. C::getY() // Cannot access getY() ```
There are so many that you cannot but get tired. Here are some: ``` void incrementY() {y++} ``` No `;` after `y++`. ``` 24. A::x(); ``` Non static member cannot be invoked via a class name. ``` 25. A a; ``` No definition of static member `y`. If `y` was a `const` this would've been okay. This is a bit tricky so I'll quote. > **9.4.2 Static data members** > > 2. The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void [...] > 3. If a static data member is of const effective literal type, its declaration in the class definition can specify > a constant-initializer brace-or-equal-initializer with an initializer-clause that is an integral constant expression. > A static data member of effective literal type can be declared in the class definition with the > constexpr specifier; if so, its declaration shall specify a constant-initializer brace-or-equal-initializer with an initializer-clause that is an integral constant expression. In both these cases, the member may appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer. ``` 26. a.getY(); 27. A::getY(); ``` Illegal reference to non-static member `A::z`. Taken care of by first observation. ``` 28. B b; 29. C c; 30. C::getY(); ``` `getY()` is a private member of `B`, not visible to `C`, let alone be public. ``` 31. b.x(); ``` The member function `x()` inherited from `A` is private.
C++ errors in code
[ "", "c++", "" ]
Why would the code below throw a io.system.directorynotfound exception? I can't recreate the problem myself but another user of my code does see it, any ideas why? Thanks ``` try { //create path string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs"; //check path exists if (!System.IO.File.Exists(strAppData)) { System.IO.Directory.CreateDirectory(strAppData); } System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData); int count = dir.GetFiles().Length; if (count > 100) { string[] files = System.IO.Directory.GetFiles(strAppData); foreach (string file in files) { System.IO.File.Delete(file); } } this.fileName = fileName; // delete the file if it exists if (File.Exists(fileName)) { //delete the file File.Delete(fileName); } // write the data to the file fs = File.OpenWrite(fileName); sWriter = new StreamWriter(fs); sWriter.WriteLine(headerText); sWriter.Flush(); sWriter.Close(); } catch (Exception exp) { throw new Exception(exp.Message); } ```
Have you tried using System.IO.Directory.Exists rather than System.IO.File.Exists when checking to see if the path exists?
You're checking for the existence of a directory using `System.IO.File` rather than `System.IO.Directory`. It probably works on your machine because that directory already exists, and so the check doesn't matter. Either way, you need to remember that the file system is volatile. Rather than checking existence, try to open the resource and handle the exception when it fails.
C# Why is my code throwing a io.system.directorynotfound?
[ "", "c#", "directory", "" ]
I have a problem I don't really understand. I have a class Node. ``` template<class T> class node { protected: T _data; public: node(T data); }; ``` This is in "node.h" file. In "node.cpp" file, there is this constructor: ``` #include "node.h" template<class T> node<T>::node (T data) { _data = data; } ``` While the compiler finds no error, the linker (ld) tells me: > > /usr/bin/ld: Undefined symbols: > > > > node<int>::node(int) the weird part... if I move the constructor from .cpp to .h file, everything works fine. Where is the problem?
The problem is that templates aren't classes - you don't normally write them in two separate files. Template classes are code that the compiler uses to *generate* classes. As such, your implementation code needs to effectively be inline, i.e., in the header as you discovered. For a fuller explanation of *why* it has to be this way, see the [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12).
As a general rule, you must put all template members inside of the header file. Templates are compiled in an as-used basis, and hence the entire definition needs to be available wherever they are used. Putting the code in the header file will solve that problem. The only time you can put a template definition in a CPP file is when the template will only be used within that CPP file. The reason being is that it meets the standard that the entire definition is available for compilation. Moving the contents of node.cpp to node.h will fix the problem. **Strange Scenarios** Then again, you can also put everything in a CPP file and include the CPP file. C++ is flexible in this way. I only mention this because I've seen in done before. I actually bruised my jaw when it hit the top of my desk.
c++ class with template cannot find its constructor
[ "", "c++", "templates", "" ]
I'm writing some code which needs to do string normalisation, I want to turn a given string into a camel-case representation (well, to the best guess at least). Example: ``` "the quick brown fox" => "TheQuickBrownFox" "the_quick_brown_fox" => "TheQuickBrownFox" "123The_quIck bROWN FOX" => "TheQuickBrownFox" "the_quick brown fox 123" => "TheQuickBrownFox123" "thequickbrownfox" => "Thequickbrownfox" ``` I think you should be able to get the idea from those examples. I want to strip out all *special* characters (', ", !, @, ., etc), capitalise every word (words are defined by a space, \_ or -) and any **leading numbers** dropped (trailing/ internal are ok, but this requirement isn't vital, depending on the difficulty really). I'm trying to work out what would be the best way to achieve this. My first guess would be with a regular expression, but my regex skills are bad at best so I wouldn't really know where to start. My other idea would be to loop and parse the data, say break it down into *words*, parse each one, and rebuilt the string that way. Or is there another way in which I could go about it?
How about a simple solution using [Strings.StrConv](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.strconv.aspx) in the Microsoft.VisualBasic namespace? (Don't forget to add a Project Reference to Microsoft.VisualBasic): ``` using System; using VB = Microsoft.VisualBasic; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(VB.Strings.StrConv("QUICK BROWN", VB.VbStrConv.ProperCase, 0)); Console.ReadLine(); } } } ```
This regex matches all words. Then, we `Aggregate` them with a method that capitalizes the first chars, and `ToLower`s the rest of the string. ``` Regex regex = new Regex(@"[a-zA-Z]*", RegexOptions.Compiled); private string CamelCase(string str) { return regex.Matches(str).OfType<Match>().Aggregate("", (s, match) => s + CamelWord(match.Value)); } private string CamelWord(string word) { if (string.IsNullOrEmpty(word)) return ""; return char.ToUpper(word[0]) + word.Substring(1).ToLower(); } ``` This method ignores numbers, by the way. To Add them, you can change the regex to `@"[a-zA-Z]*|[0-9]*"`, I suppose - but I haven't tested it.
String normalisation
[ "", "c#", ".net-3.5", "string", "normalization", "" ]
Consider the following html page, which can load in many large png files: ``` <html> <head> <script type="text/javascript"> function hide( ) { document.getElementById("here").innerHTML = "hidden"; } function show( ) { var loadMe = ""; for (var i=1; i<250; i++) { loadMe += "<img src='http://example.com/" + i + "_a.png'><br>"; loadMe += "<img src='http://example.com/" + i + "_b.png'><br>"; } document.getElementById("here").innerHTML = loadMe; } </script> </head> <body> <a href="javascript:hide();">hide</a> <a href="javascript:show();">show</a> <div id="here"></div> </body> </html> ``` In IE, Safari & Opera on a windows machine, the images on this page are only loaded once (monitored with FreeMeter) when the show and hide buttons are toggled. However, in Firefox (freshly installed), *some* images are loaded from the server multiple times (we never match the initial peak in network requests... a few things are loaded from the cache). The response headers of the images read: ``` Date Wed, 18 Mar 2009 11:42:02 GMT Server Apache/2.2.3 (Red Hat) Last-Modified Mon, 27 Oct 2008 19:19:47 GMT Etag "1abb7d7-292-45a41039f7ac0" Accept-Ranges bytes Content-Length 658 Cache-Control max-age=7257600 Expires Thu, 15 Apr 2010 20:00:00 GMT Connection close Content-Type image/png ``` Looking into **`about:cache`**, most of the images loaded appear to be listed there (although inspecting the cache between `hide`/`show` clicks, there appear to be missing images): ``` Number of entries: 462 Maximum storage size: 50000 KiB Storage in use: 5593 KiB ... Key: http://example.com/23_a.png Data size: 16139 bytes Fetch count: 13 Last modified: 2009-03-18 07:40:14 Expires: 2009-06-10 07:40:00 ``` What's firefox expecting from me to reload these images from the cache so we can go easy on the network calls? Thank you! --- **Update** If I open this page in a new tab after showing / hiding in the first tab, the second tab makes no network requests. The first tab continues to make network requests.
The bug is described [here](https://bugzilla.mozilla.org/show_bug.cgi?id=290032)
I can't tell you why Firefox is behaving this way (or better yet, how to override this behaviour), but I'd suggest a different approach that might circumvent the problem. Instead of building the HTML string over and over again and completely removing these `img` elements from the DOM, why not just build it once with an outer container `div` and `show`/`hide` the `div`? This way, the `img`s are always part of the DOM (and Firefox will most likely not feel the need to remove the images from the cache).
browser cache bypassed in firefox?
[ "", "javascript", "html", "firefox", "caching", "firebug", "" ]
Is there something I can call from a POJO to see if the code is currently in an App Server or outside of an App Server? Something like this (In rough PseudoCode): ``` System.getRunningEnvironment().equals(Environment.Glassfish) ``` or ``` System.getRunningEnvironment().equals(Environment.ApplicationServer) ``` or ``` System.getRunningEnvironment().equals(Environment.JavaSE) ```
If you can change AppServer initialization scripts (take a look at [this link](http://www.exampledepot.com/egs/java.lang/PropCmdLine.html)): Add -DRunningInAppServer=true at your AppServer initialization script. Add -DRunningInAppServer=false at your application initialization script. Then use this method: ``` public boolean isRunningInAppServer() { if ("true".equals(System.getProperty("RunningAppServer"))) { return true; } return false; } ```
The easiest way is, to check the existence of Java EE/App Server specific classes.
Can Java Code tell if it is in an App Server?
[ "", "java", "jakarta-ee", "jboss", "ejb-3.0", "application-server", "" ]
``` <% if(Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES) { %> ... <% } else { %> ... <% } %> ``` Gives me a InvalidOperationException? How do I write conditional html generation in ASP?
Use an inline statement as John\_ states, or, create a function in your code behind that performs the logic required. ``` protected string MyFunction(int nbrOrders) { if(nbrOrders>=Config.MAX_ENQUIRY_SALES) { return "TrueResult"; } else { return "FalseResult"; } } ``` Then use this as follows ``` <%# MyFunction(Convert.ToInt32(Eval("NbrOrders"))) %> ``` EDIT: I've just read a comment on another post that states you want to show different HTML depending on this result. In that case, you can try using the Visible flag of a placeholder containing your code. Such as: ``` <asp:PlaceHolder id="PlaceHolder1" runat="server" visible='<%# (Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES)%>'> <div>My True Html Here</div> </asp:PlaceHolder> <asp:PlaceHolder id="PlaceHolder2" runat="server" visible='<%# !(Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES)%>'> <div>My FalseHtml Here</div> </asp:PlaceHolder> ```
I'm not sure you can add brackets for the conditional binding, the only way I know of doing it is with an inline statement like so: ``` <%# Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES) ? Eval("IfTrueValue") : Eval("IfFalseValue") %> ```
ASP.Net conditional databinding
[ "", "c#", "asp.net", "" ]
I am looking to pass an event to a helper function. This function will attach a method to the event. However, I am having trouble properly passing the event. I have tried passing a `EventHandler<TEventArgs>`. It compiles, but events are not attached (but are still added; it seems a copy of the event handler is made). For example, if I have this: ``` public event EventHandler<EventArgs> MyEvent; ``` And the helper function: ``` public static void MyHelperFunction<TEventArgs>(EventHandler<TEventArgs> eventToAttachTo) { eventToAttachTo += (sender, e) => { Console.WriteLine("Hello world"); }; } ``` And the caller: ``` MyHelperFunction(MyEvent); MyEvent(null, new EventArgs()); // Does nothing. ```
The reason why this does not work is += when applied to a delegate creates a new delegate which is the combination of the old and the new. It does not modify the existing delegate. In order to get this to work you will have to pass the delegate by reference. ``` public static void Helper(ref EventHandler<EventArgs> e) { e+= (x,y) => {}; } ``` The reason this works outside of the method is because the LHS is still the actual field. So += will create a new delegate and assign back to the member field.
Just came up with this little helper. If it is your self-created Event you could use a wrapper like this. You can use your += operators to attach handlers as normal but can pass the wrapper around and even raise the event from elsewhere. ``` public class GenericEvent<T> where T:EventArgs { public event EventHandler<T> Source = delegate { }; public void Raise(object sender, T arg = default(T)) { Source(sender, arg); } public void Raise(T arg = default(T)) { Source(this, arg); } public void AddHandler(EventHandler<T> handler) { Source += handler; } public void RemoveHandler(EventHandler<T> handler) { Source -= handler; } public static GenericEvent<T> operator +(GenericEvent<T> genericEvent, EventHandler<T> handler) { genericEvent.AddHandler(handler); return genericEvent; } } ``` Create the event like: ``` public GenericEvent<EventArgs> MyEvent = new GenericEvent<EventArgs>(); ``` Attach handlers: ``` MyEvent += (s,e) => {}; ``` Raise event: ``` MyEvent.Raise(); ```
How can I pass an event to a function in C#?
[ "", "c#", "delegates", "" ]
This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code: ``` foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) ``` produces: ``` 1.0 1 2.0 2 3.0 3 4.0 None 5.0 None ``` **Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.** ``` 1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] ``` **Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.** ``` foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] ``` **and print:** ``` 1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... ``` **P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?**
The easiest way would be not to pass `bars` through the different functions, but to access it directly from `maptest`: ``` foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo): print foo, bars map(maptest, foos) ``` With your original `maptest` function you could also use a lambda function in `map`: ``` map((lambda foo: maptest(foo, bars)), foos) ```
Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle? Also, do you understand list comprehensions? ``` map(f, sequence) ``` is directly equivalent (\*) to: ``` [f(x) for x in sequence] ``` In fact, I think `map()` was once slated for removal from python 3.0 as being redundant (that didn't happen). ``` map(f, sequence1, sequence2) ``` is mostly equivalent to: ``` [f(x1, x2) for x1, x2 in zip(sequence1, sequence2)] ``` (there is a difference in how it handles the case where the sequences are of different length. As you saw, `map()` fills in None when one of the sequences runs out, whereas `zip()` stops when the shortest sequence stops) So, to address your specific question, you're trying to produce the result: ``` foos[0], bars foos[1], bars foos[2], bars # etc. ``` You could do this by writing a function that takes a single argument and prints it, followed by bars: ``` def maptest(x): print x, bars map(maptest, foos) ``` Alternatively, you could create a list that looks like this: ``` [bars, bars, bars, ] # etc. ``` and use your original maptest: ``` def maptest(x, y): print x, y ``` One way to do this would be to explicitely build the list beforehand: ``` barses = [bars] * len(foos) map(maptest, foos, barses) ``` Alternatively, you could pull in the `itertools` module. `itertools` contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want `itertools.repeat`, which will output its argument indefinitely as you iterate over it. This last fact means that if you do: ``` map(maptest, foos, itertools.repeat(bars)) ``` you will get endless output, since `map()` keeps going as long as one of the arguments is still producing output. However, `itertools.imap` is just like `map()`, but stops as soon as the shortest iterable stops. ``` itertools.imap(maptest, foos, itertools.repeat(bars)) ``` (\*) It's a little different in python 3.0. There, map() essentially returns a generator expression.
Using python map and other functional tools
[ "", "python", "dictionary", "functional-programming", "" ]
I have a bog-standard login form - an email text field, a password field and a submit button on an AIR project that's using HTML/jQuery. When I hit Enter on the form, the entire form's contents vanish, but the form isn't submitted. Does anyone know if this is a Webkit issue (Adobe AIR uses Webkit for HTML), or if I've bunged things up? I tried: ``` $('.input').keypress(function (e) { if (e.which == 13) { $('form#login').submit(); } }); ``` But that neither stopped the clearing behavior, or submitted the form. There's no action associated with the form - could that be the issue? Can I put a javascript function in the action?
``` $('.input').keypress(function (e) { if (e.which == 13) { $('form#login').submit(); return false; //<---- Add this line } }); ``` Check out this stackoverflow answer: [event.preventDefault() vs. return false](https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) Essentially, "return false" is the same as calling `e.preventDefault` and `e.stopPropagation()`.
In addition to return false as Jason Cohen mentioned. You may have to also preventDefault ``` e.preventDefault(); ```
Submitting a form on 'Enter' with jQuery?
[ "", "javascript", "jquery", "html", "webkit", "forms", "" ]
In his excellent book, CLR Via C#, Jeffrey Richter said that he doesn't like properties, and recommends not to use them. He gave some reason, but I don't really understand. Can anyone explain to me why I should or should not use properties? In C# 3.0, with automatic properties, does this change? **As a reference, I added Jeffrey Richter's opinions:** • A property may be read-only or write-only; field access is always readable and writable. If you define a property, it is best to offer both get and set accessor methods. • A property method may throw an exception; field access never throws an exception. • A property cannot be passed as an out or ref parameter to a method; a field can. For example, the following code will not compile: ``` using System; public sealed class SomeType { private static String Name { get { return null; } set {} } static void MethodWithOutParam(out String n) { n = null; } public static void Main() { // For the line of code below, the C# compiler emits the following: // error CS0206: A property or indexer may not // be passed as an out or ref parameter MethodWithOutParam(out Name); } } ``` • A property method can take a long time to execute; field access always completes immediately. A common reason to use properties is to perform thread synchronization, which can stop the thread forever, and therefore, a property should not be used if thread synchronization is required. In that situation, a method is preferred. Also, if your class can be accessed remotely (for example, your class is derived from System.MashalByRefObject), calling the property method will be very slow, and therefore, a method is preferred to a property. In my opinion, classes derived from MarshalByRefObject should never use properties. • If called multiple times in a row, a property method may return a different value each time; a field returns the same value each time. The System.DateTime class has a readonly Now property that returns the current date and time. Each time you query this property, it will return a different value. This is a mistake, and Microsoft wishes that they could fix the class by making Now a method instead of a property. • A property method may cause observable side effects; field access never does. In other words, a user of a type should be able to set various properties defined by a type in any order he or she chooses without noticing any different behavior in the type. • A property method may require additional memory or return a reference to something that is not actually part of the object's state, so modifying the returned object has no effect on the original object; querying a field always returns a reference to an object that is guaranteed to be part of the original object's state. Working with a property that returns a copy can be very confusing to developers, and this characteristic is frequently not documented.
Jeff's reason for disliking properties is because they look like fields - so developers who don't understand the difference will treat them as if they're fields, assuming that they'll be cheap to execute etc. Personally I disagree with him on this particular point - I find properties make the client code much simpler to read than the equivalent method calls. I agree that developers need to know that properties are basically methods in disguise - but I think that educating developers about that is better than making code harder to read using methods. (In particular, having seen Java code with several getters and setters being called in the same statement, I know that the equivalent C# code would be a lot simpler to read. The Law of Demeter is all very well in theory, but sometimes `foo.Name.Length` really is the right thing to use...) (And no, automatically implemented properties don't really change any of this.) This is slightly like the arguments against using extension methods - I can understand the reasoning, but the practical benefit (when used sparingly) outweighs the downside in my view.
Well, lets take his arguments one by one: > A property may be read-only or > write-only; field access is always > readable and writable. This is a win for properties, since you have more fine-grained control of access. > A property method may throw an > exception; field access never throws > an exception. While this is mostly true, you can very well call a method on a not initialized object field, and have an exception thrown. > • A property cannot be passed as an > out or ref parameter to a method; a > field can. Fair. > • A property method can take a long > time to execute; field access always > completes immediately. It can also take very little time. > • If called multiple times in a row, a > property method may return a different > value each time; a field returns the > same value each time. Not true. How do you know the field's value has not changed (possibly by another thread)? > The System.DateTime class has a > readonly Now property that returns the > current date and time. Each time you > query this property, it will return a > different value. This is a mistake, > and Microsoft wishes that they could > fix the class by making Now a method > instead of a property. If it is a mistake it's a minor one. > • A property method may cause > observable side effects; field access > never does. In other words, a user of > a type should be able to set various > properties defined by a type in any > order he or she chooses without > noticing any different behavior in the > type. Fair. > • A property method may require > additional memory or return a > reference to something that is not > actually part of the object's state, > so modifying the returned object has > no effect on the original object; > querying a field always returns a > reference to an object that is > guaranteed to be part of the original > object's state. Working with a > property that returns a copy can be > very confusing to developers, and this > characteristic is frequently not > documented. Most of the protestations could be said for Java's getters and setters too --and we had them for quite a while without such problems in practice. I think most of the problems could be solved by better syntax highlighting (i.e differentiating properties from fields) so the programmer knows what to expect.
Why should I avoid using Properties in C#?
[ "", "c#", "properties", "" ]
Using Java 6: I have a method that uses a Thread to run a task in the background. This task accesses files, so the method should not be able to have multiple threads running. I am trying to figure out if there is a way that I can search for active Threads at the beginning of my method. I want to know if there is an active Thread that is already running my task, so that I can handle the situation properly. Is this possible without having an actual instance of a previous Thread handy? I would like to avoid saving instances of the Thread globally.
You may want something a little more robust, like using a [ReentrantLock](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html) to prevent concurrent access to those resources.
Just for reference: you can get all active threads in the current thread's group and its subgroups (for a standalone program, this usually can get you all threads) with `java.lang.Thread.enumerate(Thread[])`. But this is *not* the way to solve your problem - as Brian said, use a lock.
Is there a way to search for and access Threads that are currently running?
[ "", "java", "multithreading", "" ]
**Background:** I have a web application for which I need to do database auditing for insert/deletes/updates (and maybe reads). I use LINQ as my ORM. Using some ideas I found on the web I've come up with a way of using attributes to decorate my entities which have associated audit tables. The audit table itself is required to include the same columns with the same types as the original table in addition to fields for the id and name of the current user, modification type, modification time, and whether the operation was successful or not. The auditing occurs during SubmitChanges -- my data context is abstract and I inherit and override SubmitChanges in my concrete implementation. The abstract data context actually derives from an AbstractAuditableDataContext which extends DataContext and adds a CurrentUser property with placeholders for the current user id and name. By default these are 0 and "system" for the instances where there isn't a logged in user -- say during registration or login when certain fields of the user table may be updated. The application is written in C# using ASP.NET MVC. **Problem:** What's the best way to populate the current user property of my derived data context? Should I create a utility class that gets injected in the AuditUtility that checks to see if the CurrentUser has been set and, if not, fills it in. For testing I'd mock this out, but in the live application it would probably use lazy-loading and get/set it in the session. Or should I modify the data context factory (used by all controllers) to perform this functionality. I already use a mock factory during unit testing so this wouldn't involve creating new classes. Or should the derivation be done outside the factory and the current user injected in during context creation. This would allow me to do "on behalf of" auditing. I realize that this is somewhat subjective, but I'd appreciate any thoughts/experiences you might contribute. Thanks.
I ended up creating an CurrentUserUtilityBase class that has a GetAuditUser method that takes the current data context and retrieves the user object that corresponds to the current user name in the HttpContext.User.Identity. It uses this object to extract the id and display name of the current user and create and return an AuditUser object containing these properties. My implementing class uses a factory to obtain an instance of my data context and invokes the base class method on this data context. The factory methods for my data context's use the current user utility to inject the current user for the context into the context after it is created.
If you're using Windows or Forms auth, you could check the HttpContext without passing anything in. If you're not in a web context, grab the user from the Thread. Maybe: ``` if(HttpContext.Current != null) { //grab the user from the HttpContext } else { //grab the user from the Thread } ```
LINQ auditing and current user with web application
[ "", "c#", "linq-to-sql", "auditing", "" ]
It seems like this setting should be stored in the solution file so it's shared across all users and part of source code control. Since we don't check in the suo file, each user has to set this separately which seems strange.
Why should it be a non-user-specific preference? If I've got a solution with 10 files in, and one developer is primarily testing/using one of those tools, why should that affect what I start up? I think MS made the right choice on this one. The project *I* want to start is far from necessarily the project that *other* developers want to start.
It is absolutely necessary that everyone can define their StartUp Project themselves, as [Jon has already said](https://stackoverflow.com/a/694742). But to have a dedicated default one would be great, and as I can tell, it is possible! **If you don’t have a .suo file in your solution directory, Visual Studio picks the first project in your .sln file as the default startup project.** 1. Close your Visual Studio and open the .sln file in your favorite text editor. Starting in line 4, you see all your projects encapsulated in `Project` – `EndProject` lines. 2. Cut and paste the desired default startup project to the top position. 3. Delete your .suo file. 4. Open your solution in Visual Studio. Ta daa!
Why is "Set as Startup" option stored in the suo file and not the sln file?
[ "", "c#", "visual-studio", "" ]
What Windows API functions are available to execute command prompt's functionality? For example, I like to execute dir command and want to show the output in GUI without using cmd.exe in Windows.
You can start `cmd /c dir S:\ome\Path` from your process and grab the output. Otherwise it's not possible. But if you're not interested in particular formatting details of `dir` then you're probably better off just enumerating files/directories and display them.
The dir command is built into the cmd.exe, it's not a separate executable. There's no way of executing it short of running cmd.exe. EDIT: As for the displaying of results, you need to fill in the STARTUPINFO.hStdXXX members, probably using an anonymous pipe. See [this example](http://edn.embarcadero.com/article/10387).
Executing command prompt's functionality using Win32
[ "", "c++", "c", "winapi", "" ]
Is there a built in function in C# / .net that will take a variable and describe / output it's contents? In PHP there are the [`print_r()`](http://php.net/print_r) and [`var_dump()`](http://php.net/var_dump) functions which achieve this (I realise the inherent difference between C# and PHP, just providing a example of output) As this is for a logging script it needs to be as lightweight and unintrusive as possible - I'm considering writing a function to do this however would prefer to use a built in if available. Examples of variables would be arrays / lists of custom objects, dumping out of eventargs passed to an event handler etc. I'd like to take this as far as possible whilst avoiding the expense of reflection. Thanks
See my answer to this question for a summary of different ways to get a string representation of an object: [String casts](https://stackoverflow.com/questions/697216/string-casts/697248#697248) Since you want this to be both very generic and lightweight your best option here is probably `Convert.ToString()`.
I'm not sure about any built-in dump functionality in C#, but you could simply use Reflection and iterate through a variable's type with **MethodInfo, PropertyInfo, FieldInfo** etc. **Edit**: Yes, I know it's not exactly lightweight.
C# Variable description function
[ "", "c#", ".net", "" ]
I'm just starting out with CakePHP, and I can't find any support for implementing an optimistic locking scheme. The closest I could find was a comment on this [CakePHP blog post](http://debuggable.com/posts/how-to-do-group-by-conditions-in-model-find()-calls:483fdc1c-8454-4593-a55e-37244834cda3) saying that it wasn't supported in June 2008. Does anyone know if that has changed, or if someone has published an extension or a tutorial on how to implement it yourself? For a description of optimistic locking, see [this answer](https://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking/129397#129397).
Tadashi Nakamura has posted an [OptimisticLock behaviour](https://github.com/tad80/OptimisticLock) on GitHub. It's not quite perfect, because it does the query for the last modified date before writing the changed record. That leaves you open to either silently overwriting another user's changes or hitting a deadlock. When I tried to write a behaviour like this, I wanted to include the last modified date in the update's where clause and fail if the rows affected is zero. At that time, there was no support for [adding an extra condition to an update query](https://stackoverflow.com/q/1479961/4794). I haven't used PHP lately, so I don't know if that has changed.
Not in the Core, and after a quick google it doesn appear that anyone is sharing a [behavior](http://book.cakephp.org/view/595/Creating-Behaviors) if they made one. That would be my suggested tactic.
Any support for optimistic locking in CakePHP?
[ "", "php", "cakephp", "optimistic-locking", "" ]
I have a custom collection type of data. This data is sorted by three properties in their order, e.g. take the following example: ``` class Data { public int PropertyA() { get; set; } public int PropertyB() { get; set; } public int PropertyC() { get; set; } } ``` The collection must maintain the order of A, B, C, e.g.: ``` [A, B, C] [1, 2, 5] [1, 3, 3] [1, 3, 4] [1, 4, 1] [2, 1, 2] [3, 3, 1] [3, 4, 2] ``` I'd like to write some tests to ensure that this order is maintained in the collection through the usual suspect Add and Remove operations. I'm using Gallio and MbUnit 3, and I think there must be an easy way to do this with their attributes, I just don't get it right now. Any ideas?
[MbUnit v3](http://www.gallio.org/) has a new useful [**Assert.Sorted**](http://www.gallio.org/api/html/Overload_MbUnit_Framework_Assert_Sorted.htm) method. You just need to pass the enumeration instance to evaluate. If the enumerated objects implements IEquatable, then everything is automatic. ``` [Test] public void MySimpleTest { var array = new int[] { 1, 5, 9, 12, 26 }; Assert.Sorted(array); } ``` Otherwise, you still have the possibility to specify a custom comparison criterion (with the new handy [structural equality comparer](http://www.gallio.org/api/html/T_MbUnit_Framework_StructuralEqualityComparer_1.htm), for example). ``` [Test] public void MyComplexTest { var array = new Foo[] { new Foo(123), new Foo(456), new Foo(789) }; Assert.Sorted(array, new StructuralEqualityComparer<Foo> { { x => x.Value } }); } ``` Have a look at the Gallio/MbUnit [API doc reference](http://www.gallio.org/api/index.aspx) for more details.
Yann Trevin has been working on a "CollectionContract" for MbUnit v3. I don't think it can handle ordered collections right now but I'm sure he'd be interested in adding that capability given an appropriate comparison delegate to describe the ordering invariant. You'll find a example of this in the "SampleCollectionTest" fixture of the MbUnit.Samples project in MbUnit v3.0.6. I recommend that you post your idea to the mbunitdev mailing list where he'll see it: <http://groups.google.com/group/mbunitdev>
MbUnit: Testing custom ordered collection
[ "", "c#", "unit-testing", "sorting", "collections", "mbunit", "" ]
Consider this Python segment: ``` def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = someTestFunction() if a != None: return a ... normal execution continues ``` Now, the question: the three-line segment in the beginning of SomeCallingFunction to get the value of the test function and bail out if it's not None, is repeated very often in many other functions. Three lines is too long. I want to shorten it to one. How do I do that? I can freely restructure this code and the contents of someTestFunction however needed. I thought of using exceptions, but those don't seem to help in cutting down the calling code length. (I've read a bit about Python decorators, but haven't used them. Would this be the place? How would it work?)
If you want to use a decorator, it would look like this: ``` def testDecorator(f): def _testDecorator(): a = someTestFunction() if a is None: return f() else: return a return _testDecorator @testDecorator def SomeCallingFunction(): ... normal execution ``` When the module is first imported, it runs `testDecorator`, passing it your original `SomeCallingFunction` as a parameter. A new function is returned, and that gets bound to the `SomeCallingFunction` name. Now, whenever you call `SomeCallingFunction`, it runs that other function, which does the check, and returns either `a`, or the result of the original `SomeCallingFunction`.
I often use a hash table in place of a series of elifs: ``` def someTestFunction(decorated_test): options = { 'val1': return_val_1, 'val2': return_val_2 } return options[decorated_test] ``` You can set up options as a defaultdict(None) to default to None if a key isn't found. If you can't get your tests in that form, then a series of if statements might actually be the best thing to do. One small thing you can do to shorten your code is to use this: ``` if a: return a ``` There may be other ways to shorten your code, but these are the ones I can come up with on the spot.
Shortening a oft-used code segment for testing a return value in Python
[ "", "python", "optimization", "" ]
If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?
Don't worry: Of course it saves the count and thus `len()` on lists is a pretty cheap operation. Same is true for strings, dictionaries and sets, by the way!
And one more way to find out how it's done is ~~[to look it up on Google Code Search](http://www.google.com/codesearch/p?hl=en#ggVSD6_h0Ho/Python-2.5/Objects/listobject.c&q=package:python-2.5%20listobject.c%20lang:c&l=370)~~ [look at the source on GitHub](https://github.com/python/cpython/blob/2.5/Objects/listobject.c#L379), if you don't want to download the source yourself. ``` static Py_ssize_t list_length(PyListObject *a) { return a->ob_size; } ```
Python: Do Python Lists keep a count for len() or does it count for each call?
[ "", "python", "" ]
I have a class that contains a number of standard fields and an arraylist. Is there any way to serialize the class using an XmlSerializer? Attempts so far result in an error message saying: ``` Unhandled Exception: System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type XMLSerialization.DataPoints was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. ``` Some cut-down representations of the classes are shown below: ``` public class StationData { private DateTime _CollectionDate; private string _StationID; private ArrayList _PolledData; public StationData() { } public DateTime CollectionDate { get { return _CollectionDate; } set { _CollectionDate = value; } } public string StationID { get { return _StationID; } set { _StationID = value; } } [XmlInclude(typeof(DataPoints))] public ArrayList PolledData { get { return _PolledData; } set { _PolledData = value; } } } public class DataPoints { private string _SubStationID; private int _PointValue; public DataPoints { } public string SubStationID { get { return _SubStationID; } set { _SubStationID = value; } } public int PointValue { get { return _PointValue; } set { _PointValue = value; } } } ```
I have had success with the following: ``` [XmlArray("HasTypeSpecialisations")] [XmlArrayItem("TypeObject", typeof(TypeObject), IsNullable = false)] public List<TypeObject> TypeSpecialisations ``` This results in: ``` <HasTypeSpecialisations> <TypeObject /> <TypeObject /> </HasTypeSpecialisations> ``` In your situation I would try something like: ``` [XmlArrayItem(typeof(DataPoints))] public ArrayList PolledData ``` Based on this link <http://msdn.microsoft.com/en-us/library/2baksw0z(VS.85).aspx> you should also be able to use this ``` [XmlElement(Type = typeof(DataPoints))] public ArrayList PolledData ```
The XmlSerializer generates some code at runtime to serialize your class. It is necessary for this class to know all types that can occur. The ArrayList does not give this information, but you can give it by using a [XmlInclude](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlincludeattribute.aspx) attribute on the property that returns the ArrayList. ``` [XmlInclude(typeof(DataPoints))] public ArrayList Points { ... } ``` You could also use the generic List<> class.
Serializing an arraylist in C#
[ "", "c#", "" ]
Can you explain to me why I should inherit from `ICloneable` and implement the `Clone()` method? If I want to do a deep copy, can't I just implement my method? Let's say `MyClone()`? Why should I inherit from `ICloneable`? What are the advantages? Is it just a matter of making code "more readable"?
You shouldn't. Microsoft recommends against implementing `ICloneable` because there's no clear indication from the interface whether your `Clone` method performs a "deep" or "shallow" clone. See [this blog post from Brad Abrams](http://blogs.msdn.com/brada/archive/2003/04/09/49935.aspx) back in 2003(!) for more information.
The `ICloneable` interface *by itself* isn't very useful, which is to say that there really aren't many situations where it's useful to know that an object is cloneable without knowing anything else about it. This is a very different situation from e.g. `IEnumerable` or `IDisposable`; there are many situations where it's useful to accept an `IEnumerable` without knowing anything other than how to enumerate it. On the other hand, `ICloneable` may be useful when applied as a generic constraint along with other constraints. For example, a base class might usefully support a number of derivatives, some of which could be usefully cloned, and some of which could not. If the base type itself exposed a public cloning interface, then any derivative type which could not be cloned would violate the Liskov Substitution Principle. The way to avoid this problem is to have the base type support cloning using a Protected method, and allow derived types to implement a public cloning interface as they see fit. Once that was accomplished, a method which wants to accept an object of a `WonderfulBase` type, and needs to be able to clone it, could be coded to accept a WonderfulBase object which supports cloning (using a generic type parameter with base-type and `ICloneable` constraints). Although the `ICloneable` interface would not itself indicate deep or shallow cloning, the documentation for `WonderfulBase` would indicate whether cloneable `WonderfulBase` should be deep- or shallow-cloned. Essentially, the `ICloneable` interface wouldn't accomplish anything that wouldn't be accomplished by defining `ICloneableWonderfulBase`, except that it would avoid having to define different names for every different cloneable base class.
Why should I implement ICloneable in c#?
[ "", "c#", ".net", "cloneable", "icloneable", "" ]
I recently asked this question: [Dynamically Query a Database to check for value](https://stackoverflow.com/questions/694849/dynamically-query-a-database-to-check-for-value/694860#694860) And I got an awesome and informative answer. But whenever I search on Google to find out more about "Ajax Requests" the codes never look similar to the one provided. Also I have used another tutorial that used this, is it a shorthand? Or is it jQuery or what? That horrible confusion, is messing up my ability so solve the following problem: Sending the value of the field to the PHP script. I tried using something along the lines of:: ``` $value = $GET["inputname"]; ``` but that does not seem to work. Could you please help? I am very adept in PHP but I am very new to javascript. THANKS!
``` $.get(url,{},verifyDb); ``` is the [jQuery ajax Get method](http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype). You can pass a parameter like this: ``` $.get(url,{inputname: "value goes here"},verifyDb); ``` $ is a shorthand for the jQuery object. I would familiarize yourself with the [jQuery docs](http://docs.jquery.com/Main_Page).
Maybe I'm an idiot but ``` $value = $GET["inputname"]; ``` Should be: ``` $value = $_GET["inputname"]; ``` Also, > But whenever I search on Google to > find out more about "Ajax Requests" > the codes never look similar to the > one provided. You need to be googling on '[jquery ajax requests](http://docs.jquery.com/Ajax)'
What is this kind of javascript? And Help with AJAX request
[ "", "javascript", "jquery", "ajax", "" ]
I'm just learning about dynamic memory allocation, but there is one thing i'd like to be explained. One use for dynamic allocation is for dynamic sized arrays, and thats clear to me. Another use is for normal objects. What is a situation one should use it? Is it because normally objects are pushed on the stack, and could be popped of? And how do you recognise a situation you should use dynamic memory allocation?
Another issue for dynamic memory is lifetime. Dynamic memory (new, malloc, etc ...) lives on the heap. It will stay alive until it is explicitly deleted by a piece of code through the appropriate memory function. This is very useful for long lived objects. Non dynamic memory, or the stack, has a very definite lifetime. The memory allocated on the stack will only be around while that method is executing. Once the method is finished the memory will be automatically reclaimed.
It's very common to not know how many items you have to deal with - they might come from a file or whatever. To store items which come from outside your program you need dynamic sized arrays. PS: Be sure to use STL classes like std::vector, not "arrays".
C++ Dynamic memory allocation
[ "", "c++", "" ]
I wrote a small Python application that runs as a daemon. It utilizes threading and queues. I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health. In a nutshell, I'd like to be able to do something like this: ``` python application.py start # launches the daemon ``` Later, I'd like to be able to come along and do something like: ``` python application.py check_queue_size # return info from the daemonized process ``` To be clear, I don't have any problem implementing the Django-inspired syntax. What I don't have any idea how to do is to send signals to the daemonized process (start), or how to write the daemon to handle and respond to such signals. Like I said above, I'm looking for general approaches. The only one I can see right now is telling the daemon constantly log everything that might be needed to a file, but I hope there's a less messy way to go about it. **UPDATE:** Wow, a lot of great answers. Thanks so much. I think I'll look at both Pyro and the web.py/Werkzeug approaches, since Twisted is a little more than I want to bite off at this point. The next conceptual challenge, I suppose, is how to go about talking to my worker threads without hanging them up. Thanks again.
What about having it run an http server? It seems crazy but running a simple web server for administrating your server requires just a few lines using web.py You can also consider creating a unix pipe.
Yet another approach: use [Pyro](https://pypi.python.org/pypi/Pyro4) (Python remoting objects). Pyro basically allows you to publish Python object instances as services that can be called remotely. I have used Pyro for the exact purpose you describe, and I found it to work very well. By default, a Pyro server daemon accepts connections from everywhere. To limit this, either use a connection validator (see documentation), or supply `host='127.0.0.1'` to the `Daemon` constructor to only listen for local connections. Example code taken from the Pyro documentation: **Server** ``` import Pyro.core class JokeGen(Pyro.core.ObjBase): def __init__(self): Pyro.core.ObjBase.__init__(self) def joke(self, name): return "Sorry "+name+", I don't know any jokes." Pyro.core.initServer() daemon=Pyro.core.Daemon() uri=daemon.connect(JokeGen(),"jokegen") print "The daemon runs on port:",daemon.port print "The object's uri is:",uri daemon.requestLoop() ``` **Client** ``` import Pyro.core # you have to change the URI below to match your own host/port. jokes = Pyro.core.getProxyForURI("PYROLOC://localhost:7766/jokegen") print jokes.joke("Irmen") ``` Another similar project is [RPyC](http://rpyc.wikidot.com/). I have not tried RPyC.
Communicating with a running python daemon
[ "", "python", "daemon", "" ]
What is the best way to convert decimal numbers (base ten) to sexagesimal (base sixty) represented as a string using 0-9, A-Z and a-x as the digits. I'm planning to code it in javascript but any help is appreciated. Usage Example: ``` >>decToSex(60); "10" >>decToSex(123); "23" >>decToSex(1000000); "4bke" >>decToSex(1234567.89); "5gu7.rO" ``` The final code I used, based on Paolo's answer: ``` var decToSex = function(){ var decToSexMap = ['0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x']; return function(number){ var negative = ''; if (number < 0){ var negative = '-'; } number = number.toString().split('.'); var integer = Math.abs(number[0]); var fraction = number[1]; var result = ''; do { result = decToSexMap[integer % 60] + result; integer = parseInt(integer / 60); } while (integer > 0); if (fraction){ var decimalPlaces = fraction.toString().length; result += '.'; fraction = parseFloat('.' + fraction); var x = 0; do { x++; var res = (fraction * 60).toString().split('.'); result = result + decToSexMap[res[0]]; if (res[1]) { fraction = parseFloat('.' + res[1]); } else { break; } } while (x < decimalPlaces); } return negative + result; } }(); ```
This works with the test data provided, but you probably wanna run a few more tests on it: ``` <script> var convert = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K', 'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q', 'r','s','t','u','v','w','x'); function decToSex(num) { var extract = num.toString().split('.'); num = extract[0]; var pieces = new Array(); do { pieces.push(convert[num % 60]); num = parseInt(num/60); } while (num > 0); pieces = pieces.reverse(); var rem = extract[1]; if(rem) { rem = parseFloat('.' + rem); var x = 0; var dec = new Array(); do { x++; var res = (rem * 60).toString().split('.'); dec.push(convert[res[0]]); if(res[1]) { rem = parseFloat('.' + res[1]); } else { break; } } while (x < 3); // work up to 3 decimal places, change for more. } var myResult = pieces.join(''); if(dec) { myResult += '.' + dec.join(''); } return myResult; } alert(decToSex(60)); alert(decToSex(123)); alert(decToSex(1000000)); alert(decToSex(1234567.89)); </script> ```
For what it's worth, here's a modification of the solution to convert to any base up to 64: ``` // Convert decimal into a base between 2 and 64 var decToBase = function() { var decToBaseMap = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'Y', 'Z', '+', '/']; return function(number, base) { if (base < 2 || base > 64) { return "#base should be between 2 and 64#"; } var negative = ''; if (number < 0) { negative = '-'; } number = number.toString().split('.'); var integer = Math.abs(number[0]); var fraction = number[1]; var result = ''; do { result = decToBaseMap[integer % base] + result; integer = parseInt(integer / base, 10); } while (integer > 0); if (fraction) { var decimalPlaces = fraction.toString().length; result += '.'; fraction = parseFloat('.' + fraction); var x = 0; do { x++; var res = (fraction * base).toString().split('.'); result = result + decToBaseMap[res[0]]; if (res[1]) { fraction = parseFloat('.' + res[1]); } else { break; } } while (x < decimalPlaces); } return negative + result; }; }(); alert(decToBase(2011, 64)); // displays "VR" ``` You can play with it here: <http://jsfiddle.net/kaicarver/d3Zn2/>
Converting decimals to sexagesimal (base sixty) in javascript
[ "", "javascript", "" ]
Im using janRain Php library for OpenId and yadis discovery and no matter what i do, i will work in stuff like user.openid.org or my own provider, but if i try to use the google endpoint, i cant get any discovery information. Even if i run the discovery example for the janrain library, i get the next result Claimed ``` Identifier http://www.google.com/accounts/o8/id No OpenID services discovered. ``` and it happens the same if I add the https:// before the url. My question is probably not how to make it work, but if its actually possible, what other choices do i have (that run in my site, no sassy auth wanted in the project). Why is openId so #@!#@ complex and undocumented?(note, i gave zend\_openid a couple of hours to have the same result)
it's working here. some hints: * as i understand it, `http(s)://www.google.com/accounts/o8/id` is not an openid endpoint, but googles *discovery* endpoint. you have to supply it a valid (google) OpenID Identifier, like `example.blogspot.com`, for which it returns Claimed Identifier, Server URL, Service types, etc. * i got the discovery example only working after fixing the `<?` and `<?=` in `discover.php` (replacing them with `<?php` and `<?php echo`). alternatively, you can `ini_set('short_open_tag', '1')`. it's off by default in `php.ini-recommended`. * does your PHP installation support SSL? see [README](http://openidenabled.com/files/php-openid/repos/2.x.x/README), specifically this part: ``` Not all PHP installations support SSL. You can find out if yours supports SSL by reading the "HTTP Fetching" section of the output of "examples/detect.php." If your installation does not support SSL, then https:// identity URLs and server URLs will not be supported by the library. An attempt to use such an identity URL will be equivalent to using an invalid OpenID. To enable SSL support, recompile PHP with OpenSSL support or install the appropriate OpenSSL module for your platform. If you are using CURL, CURL will need to be built with OpenSSL support. ```
This is a legitimate beef. Google says they support OpenID, but theirs doesn't work like ANYONE elses. MyOpenID.com, blogspot, aol, yahoo, wordpress, myspace, livejournal and many others all support the standard correctly and it works as expected. As does your own OpenID provider you can build using the CommunityID server project. /sigh
Janrain php library and google endpoint for OpenId
[ "", "php", "zend-framework", "openid", "janrain", "" ]
I have purchase this book for our group in the company, perhaps, to improve our design skills and ultimately have a better programming practices. As I read it, I find, mostly, a set of nifty tricks that can be used with template, and not sure if it is worthwhile - and not detrimental-to incorporate it into our code thus introducing code complexity/readability and un-maintainability. I would like to find out from follow practitioners, what do you use from that book? What is relevant and important to professional software development, what should be avoided? General thought about this book and how it fits into software development of large-scale system (on the same them, I love John Lakos book)? What is the Alexandrescu effect?
Outside of standard template uses, the operation I find most useful about the information talked about generic C++ programming, is the ability to use templates to create compile time errors for invalid code scenarios. Once you get the hang of it you can become very efficient at turning a class of what would be a runtime bug into a compile time error. I've had a lot of success doing that at work. Sure it produces completely unreadable messages and my coworkers occasionally drop by and say "what in the world is that?". But every time it was a bug and they weren't able to compile it. I also heavily comment the particular errors in the hope that it's moderately understandable.
Around 2005 I got heavily into expression templates and various compile-time tricks for making libraries that were very expressive to use, like internal domain-specific languages embedded in C++. In particular a fairly complete embedded SQL thing, similar to what has since come out as Linq on .NET. For users, it's fine. But for anyone else apart from me trying to maintain it, it presented a massively steep learning curve. So that's the problem with it; like any "clever" technique, it reduces the pool of people who can maintain it. This is fine for widely-used class libraries, which general users never need to understand the guts of. But for "in house" libraries owned by a specific team, they probably all need to be able to patch it or extend it sensibly. The more arcane possibilities of C++ templates seem to preclude this, in my experience. It was a lot of fun though.
Modern C++ Design Generic programming and Design Patterns Applied
[ "", "c++", "design-patterns", "templates", "" ]
I'm hoping someone can help with a problem...I don't work in anything related to programming, but we needed some asset tracking pretty badly, so in my spare time (not very much, we average 10hrs days) and with the tools at hand (a 600mhz pile running winXP) i built a little classic ASP site to handle all the tracking and orders. Everything was fine until I decided I had some more spare time and decided to upgrade a little. The whole thing is pretty messy, but worst of its god awful slow. So i decided to chuck my access db and JET drivers and go with MS SQL Server 2000 Express (don't forget, 600mhz and not much RAM). I started rebuilding, and everything seemed to be working great (and much faster) until I started getting errors. I figured out that for some queries, only a couple of the Columns would return any data. **For Example**: I have a shopitems table, with gID(uniqueID), iDesc(description), iLength, iQty, colID (cross reference). I do a query to get everything in a certain catagory: `Select * from shopitems where catID=22 order by gID asc`. Then i start stepping through and displaying it all. The problem is, only gID and colID fields have data, everything else is nothing. I opened up the Web Data Administrator app and run the query in there, and it returns everything nice and fine. So then i decided there is a bug somewhere, so I write a quick test page and same problem (except this time its gID and iLength that return data). Its all a mix of data types, iDesc is nText and iLength is int. I've gone through everything i can find, but i'm down to thinking its something i'm missing in SQL...anyone have any ideas? Also, I replicated this on my throw away computer at home, which actually has a modern processor and decent amounts of RAM, so its not the machine at all. Thanks for the help...i listen to the podcast and it seems like its been server/sql week for a while now, figured i'd ask someone here... ----EDIT---- Changed the code...a version of this code worked for a hot second, now not so much...if i comment out the ``` gID=rs1("gID") ``` then i get the value of iDesc, but not otherwise. ``` <%@ Language=vbscript %> ``` Damnit ``` Set db1 = Server.CreateObject("ADODB.Connection") 'db1.Open "Provider=MSDASQL;Driver={SQL Server};Server=Phsion;Database=master;" db1.Open "Provider=MSDASQL;DSN=SHOPWEB;" 'sqltxt="select gID, iLength, iDesc from shopitems where catID=45 order by CAST(idesc as varchar)" sqltxt="select iDesc, gID from ShopItems order by gID asc" set rs1=db1.execute(sqltxt) rs1.movefirst do until rs1.eof gID=rs1("gID") 'iLength=rs1("iLength") iDesc=rs1("iDesc") response.write("<br>gID: " & gid & "<br>") response.write("<br>iLength: " & iLength & "<br>") response.write("<br>iDesc: " & iDesc & "<br>") rs1.movenext loop rs1.close set rs1=nothing db1.close set db1=nothing ```
This is a confusing problem. Like mentioned, be sure to turn on option explicit to help find any variable name issues. If you have used **On Error Resume Next** then you can use **On Error Goto 0** to make sure you aren't suppressing errors Here is my take. Break this into it's own file if you can for debugging. If my loop produces output we can track things down. ``` <% Option Explicit On Error Goto 0 Dim db1, sqltxt, rs1 Dim gID, iLength, iDesc, arrRS Set db1 = Server.CreateObject("ADODB.Connection") 'db1.Open "Provider=MSDASQL;Driver={SQL Server};Server=Phsion;Database=master;" db1.Open "Provider=MSDASQL;DSN=SHOPWEB;" 'sqltxt="select gID, iLength, iDesc from shopitems where catID=45 order by CAST(idesc as varchar)" ' sqltxt="select iDesc, gID from ShopItems order by gID asc" ' set rs1=db1.execute(sqltxt) ' rs1.movefirst ' do until rs1.eof ' gID = rs1("gID") ' 'iLength=rs1("iLength") ' iDesc = rs1("iDesc") ' response.write("gID: " & gid & "") ' response.write("iLength: " & iLength & "") ' response.write("iDesc: " & iDesc & "") ' rs1.movenext ' loop ' rs1.close : set rs1=nothing sqltxt="select iDesc, gID from ShopItems order by gID asc" set rs1=db1.execute(sqltxt) '//Dump the recordset into an array arrRS = rs1.GetRows() '//We can close the rs now since we don't need it anymore rs1.close : set rs1=nothing '//We are going to basically dump a HTML table that should look like you SQL viewer Response.Write("<table>") '//Loop through all the rows For i = 0 To UBound(arrRS,2) Response.Write("<tr>") '//Loop through all the columns For j = 0 To UBound(arrRS,1) '//write out each column in the row Response.Write("<td>" & arrRS(j,i) & "</td>") '//Look I will be honest, I can't test this so your might have to swap the i and the j to get a full output Next Response.Write("</tr>") Next Response.Write("</table>") db1.close : set db1=nothing %> ```
Add `Option Explicit` at the top (within <% and %>) to make variable declaration required, then declare your variables using `Dim variable-name-goes-here` for all your variables, and voila, you will see the problem right away.
Classic ASP SQL Query Returns Two Columns Out Of Ten
[ "", "sql", "asp-classic", "" ]
In the company I work for we have a desktop application developed in .NET that we like to open up some parts for other software developers. I see it like some kind of public methods that other software can access. Is there any standard approach, best practices or other experience of this? I guess you could do this with Win32 calls, C/C++ programming etc. But I'm mainly a .NET developer and have some years of experience programmming in mainly VB.NET but also some C#. I hope finding a way to do this within .NET. But it should be accessible for software developed in other languages. Best regards/ Magnus
There are two ways to go about this. The first involves using the Plug In / Module pattern. [Start here](http://www.developerfusion.com/article/4371/writing-pluginbased-applications/) for that. A second way is to simply expose your API logic through well documented assemblies. The way you pick really boils down to how you want it implemented. For example, Adobe Photoshop uses the plug-in pattern to great extent. MS Office uses both plug-ins as well as provides an object interface for working with the application. **UPDATE:** Objects in .Net assemblies can be exposed to be consumed by external applications simply by setting the objects scope to Public. This includes windows forms, business objects, enum's, etc. Just think about it from the external developer's perspective. What information will they need to have in order to be successful at extending / controlling your product? Whatever that is, put it in the help file. Also, make use of the auto-documentation features of .Net. This includes adding xml documentation the the IDE already knows how to read and display via intellisense. For example: ``` /// <summary> /// Gets all active documents for the specified customer. /// </summary> /// <param name="customerId">The Id of the customer.</param> /// <returns>A list of documents for this customer.</returns> public static List<Document> GetDocuments(int customerId) { //... do something ... } ```
Create an API class that exposes what functions you want people to have access to and Register it for COM interop project ->properties -> build -> Register for COM interop
How to start creating an application API in .NET
[ "", "c#", ".net", "vb.net", "api", "" ]
``` FROM [TABELA DE PRODUTOS/ESTOQUE] AS T1 , [TABELA DE PRODUTOS] AS T2 , [TABELA DE MOVIMENTAÇÃO DE ESTOQUE] AS T3 , [TABELA DE FORNECEDORES] AS T4 , [TABELA DE PRODUTOS/ESTOQUE] AS T5 WHERE (((T1.Produto)=[T2].[ID]) ETC ``` So, how can I add a JOIN between those tables ? I need a left join, like: ``` FROM [TABELA DE PRODUTOS/ESTOQUE] <- TABLE1 LEFT JOIN [TABELA DE MOVIMENTAÇÃO DE ESTOQUE] <- TABLE2 ON TABLE1.ID=TABLE2.ID ``` Obs: Table1 and Table2 I just added to explain Thanks. --- Do I have to use UNION ?
No you don't have to use a union. If I understand your question correctly, it's as simple as combining things like this: ``` FROM [TABELA DE PRODUTOS/ESTOQUE] AS T1, [TABELA DE PRODUTOS] AS T2, [TABELA DE MOVIMENTAÇÃO DE ESTOQUE] AS T3A, [TABELA DE FORNECEDORES] AS T4, [TABELA DE PRODUTOS/ESTOQUE] AS T5, LEFT JOIN [TABELA DE MOVIMENTAÇÃO DE ESTOQUE] AS T3B ON T1.ID=T3B.ID WHERE (((T1.Produto)=[T2].[ID]) ```
``` FROM [TABELA DE PRODUTOS/ESTOQUE] AS TABLE1 LEFT JOIN [TABELA DE MOVIMENTAÇÃO DE ESTOQUE] AS TABLE2 ON TABLE1.ID=TABLE2.ID ```
Outer Join with some other tables in FROM
[ "", "sql", "join", "left-join", "" ]
Here is the situation. I have 3 tables, one super type, and two sub types, with a relationship between the sub types: ``` |----------------| |-------------------| |-------------------| | Post | | Top_Level | | Comment | |----------------| |-------------------| |-------------------| | PK | ID | | PK, FK | Post_ID | | PK, FK | Post_ID | | | DATE | | | Title | | FK | TopLv_ID | | | Text | |-------------------| |-------------------| |----------------| ``` Each post, either comment or top\_lev, is unique, but the entities share some attributes. So, comment and top\_lev are sub types of post. That is one portion. Additionally, comments are associated with a top\_lev post. This ER diagram illustrates this: <http://img11.imageshack.us/img11/9327/sampleer.png> What I am looking for is a list of Top\_Level posts ordered by activity on that top\_level post, either creation of the top\_level post, or a comment on that post. For example, assume we have the following data: ``` |------------------------| |------------------| |--------------------| | Post | | Top_Level | | Comment | |------------------------| |------------------| |--------------------| | ID | DATE | Text | | Post_ID | Title | | Post_ID |TopLv_ID | |----|------------|------| |----------|-------| |----------|---------| | 1 | 13/03/2008 | shy | | 1 | XYZ | | 2 | 1 | | 2 | 14/03/2008 | mrj | | 3 | ABC | | 4 | 1 | | 3 | 15/03/2008 | quw | | 7 | NMO | | 5 | 3 | | 4 | 16/03/2008 | ksi | |------------------| | 6 | 1 | | 5 | 17/03/2008 | kso | |--------------------| | 6 | 18/03/2008 | aoo | | 7 | 19/03/2008 | all | |------------------------| |--------------------------------| | RESULT | |--------------------------------| | ID | DATE | Title | Text | |----|------------|-------|------| | 7 | 19/03/2008 | 123 | all | | 1 | 13/03/2008 | ABC | shy | | 3 | 15/03/2008 | XYZ | quw | |--------------------------------| ``` Can this be done with a single select statement? If so, how?
I tried this query and it gives the output you describe: ``` SELECT pt.id, pt.`date`, t.title, pt.`text` FROM Top_Level t INNER JOIN Post pt ON (t.post_id = pt.id) LEFT OUTER JOIN (Comment c INNER JOIN Post pc ON (c.post_id = pc.id)) ON (c.toplv_id = t.post_id) GROUP BY pt.id ORDER BY MAX(GREATEST(pt.`date`, pc.`date`)) ASC; ``` Output: ``` +----+------------+-------+------+ | id | date | title | text | +----+------------+-------+------+ | 7 | 2008-03-19 | NMO | all | | 1 | 2008-03-13 | XYZ | shy | | 3 | 2008-03-15 | ABC | quw | +----+------------+-------+------+ ```
You've perhaps unintentionally pretty thoroughly obfuscated your question, making it very difficult to understand and answer (at least for those of us with small brains.) Could you possibly restate it with reasonable table and field names, and a more complete description of indexes? --- EDIT: Are you possibly describing a situation where products are sold, and also sometimes the same products can be included as components in other products recursively? If so, there are more conventional successful ways to model the situation.
What query will work for this sub-type / super-type relationship?
[ "", "sql", "mysql", "" ]
I would like to write an SQL query that searches for a keyword in a text field, but only if it is a "whole word match" (e.g. when I search for "rid", it should not match "arid", but it should match "a rid". I am using MySQL. Fortunately, performance is not critical in this application, and the database size and string size are both comfortably small, but I would prefer to do it in the SQL than in the PHP driving it.
You can use [`REGEXP`](http://dev.mysql.com/doc/refman/5.1/en/regexp.html) and the `[[:<:]]` and `[[:>:]]` word-boundary markers: ``` SELECT * FROM table WHERE keywords REGEXP '[[:<:]]rid[[:>:]]' ``` **Update for 2020: (actually 2018+)** MySQL updated its RegExp-Engine in version 8.0.4, so you [will now need to use](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#regexp-compatibility) the "[standard](https://www.regular-expressions.info/wordboundaries.html)" word boundary marker \b: ``` SELECT * FROM table WHERE keywords REGEXP '\\brid\\b' ``` Also be aware that you need to escape the backslash by putting a second backslash.
Found an answer to prevent the classic word boundary `[[::<::]]` clashing with special characters eg .@#$%^&\* Replace.. ``` SELECT * FROM table WHERE keywords REGEXP '[[:<:]]rid[[:>:]]' ``` With this.. ``` SELECT * FROM table WHERE keywords REGEXP '([[:blank:][:punct:]]|^)rid([[:blank:][:punct:]]|$)' ``` The latter matches (space, tab, etc) || (comma, bracket etc) || start/end of line. A more 'finished' word boundary match.
Search for "whole word match" in MySQL
[ "", "mysql", "sql", "full-text-search", "" ]
I wanted to know how the following works @ compiler level. ``` int const iVal = 5; (int&)iVal = 10; ``` A bit of m/c or compiler level answer would be great full. Thanks in advance.
It is [undefined behavior](http://en.wikipedia.org/wiki/Undefined_behavior). In the first line you define a constant integer. Henceforth, in your program, the compiler is permitted to just substitute iVal with the value 5. It may load it from memory instead, but probably won't, because that would bring no benefit. The second line writes to the memory location that your compiler tells you contains the number 5. However, this is not guaranteed to have any effect, as you've already told the compiler that the value won't change. For example, the following will define an array of **5** elements, and print an undefined value (or it can do anything it wants! it's undefined) ``` int const iVal = 5; (int&)iVal = 10; char arr[iVal]; cout << iVal; ``` The generated assembly might look something like: ``` sub ESP, 9 ; allocate mem for arr and iVal. hardcoded 5+sizeof(int) bytes ; (iVal isn't _required_ to have space allocated to it) mov $iVal, 10 ; the compiler might do this, assuming that you know what ; you're doing. But then again, it might not. push $cout push 5 call $operator_ltlt__ostream_int add ESP, 9 ```
C-style cast acts as a const\_cast. Like if you've written ``` const_cast<int&>( iVal ) = 10; ``` If you happen to do so and the compiler decides not to allocate actual memory for iVal, you run into undefined behaviour. For example, VC7 compiles it allright. It even runs it allright in Debug mode. In Release mode iVal value doesn't change after the assignment – it remains 5. So you should not do so ever.
How internally this works int const iVal = 5; (int&)iVal = 10;
[ "", "c++", "c", "compiler-construction", "" ]
``` RewriteEngine on RewriteRule ^/(dir1|dir2|dir3)/(.*)$ /targetfile.php [R,L] ``` `http://www.somesite.com/dir1` -> `http://www.somesite.com/targetfile.php` `http://www.somesite.com/dir2` -> `http://www.somesite.com/targetfile.php` `http://www.somesite.com/dir3` -> `http://www.somesite.com/targetfile.php` From what I've seen online, this should work. Unfortunately, it wont. Any insight?
If you want to use this in a .htaccess file, remove the leading slash from the pattern. And to match only full path segments, you have to alter the expression a little bit. So try this: ``` RewriteEngine on RewriteRule ^(dir1|dir2|dir3)(/|$) targetfile.php [R,L] ```
I don't believe the forward slashes are necessary, unless you want to restrict it to requiring the trailing slash after "dir1." Try: RewriteRule ^(dir1|dir2|dir3)$ targetfile.php [QSA,L]
mod_rewrite multiple directories to a php file
[ "", "php", ".htaccess", "mod-rewrite", "url-rewriting", "" ]
Map type from STL have next type: ``` std::map< Key, Data, Compare, Alloc > ``` As one of template parameters we could pass `Compare` predicate, why map accept this predicate as template parameter and not as object in constructor? It could has more flexible interface with something like `boost::function< bool, const T&, const T& >` in constructor. Ofcourse I'm understend that when STL was designed boost does not exists, but designers could be create something similar on boost::function. I belive it has some deep reasons. **EDITED** Sorry for dummy question, map have same posibility :) My question doesn't have sense after your answers.
Map DOES have such a constructor. From section 23.3.1 of the C++ Standard: ``` explicit map(const Compare& comp = Compare(), const Allocator& = Allocator()); ```
The template argument is the *type* of the predicate, not the value. The value *can* be provided as an argument to the constructor. You can specify any value that matches the type. As given, the default type is `std::less<Key>`, which pretty much only has one value, but you should be able to specify your own type for the `Compare` argument, including `boost::function`, and then use various values to control the behavior of your map objects.
std::map design: why map accept comparator as template parameter
[ "", "c++", "stl", "boost", "dictionary", "" ]
Can you tell me why the following code is giving me the following error - *call of overloaded "C(int)" is ambiguous* I would think that since C(char x) is private, only the C(float) ctor is visible from outside and that should be called by converting int to float. But that's not the case. ``` class C { C(char x) { } public: C(float t) { } }; int main() { C p(0); } ```
This is discussed in "Effective C++" by Scott Meyer. The reason this is ambiguous is that they wanted to ensure that merely changing the visibility of a member wouldn't change the meaning of already-existing code elsewhere. Otherwise, suppose your C class was in a header somewhere. If you had a private C(int) member, the code you present would call C(float). If, for some reason, the C(int) member was made public, the old code would suddenly call that member, even though neither the *old code, nor the function it called had changed*. EDIT: More reasons: Even worse, suppose you had the following 2 functions: ``` C A::foo() { return C(1.0); } C B::bar() { return C(1.0); } ``` These two functions could call different functions depending on whether either foo or bar was declared as a friend of C, or whether A or B inherits from it. Having *identical* code call different functions is scary. (That's probably not as well put as Scott Meyer's discussion, but that's the idea.)
0 is an `int` type. Because it can be implicitly cast to either a float or char equally, the call is ambiguous. **Visibility is irrelevant for these purposes.** Either put `0.0`, `0.`, or `0.0f`, or get rid of the `C(char)` constructor entirely. Edit: Relevant portion of the standard, section 13.3: > 3) [...] But, once the candidate functions and argument lists have been identified, the selection of the best function is the same in all cases: > > * First, a subset of the candidate functions—those that have the proper number of arguments and meet certain other conditions—is selected to form a set of viable functions (13.3.2). > * Then the best viable function is selected based on the implicit conversion sequences (13.3.3.1) needed to match each argument to the corresponding parameter of each viable function. > > 4) If a best viable function exists and is unique, overload resolution succeeds and produces it as the result. Otherwise overload resolution fails and the invocation is ill-formed. When overload resolution succeeds, and the best viable function is not accessible (clause 11) in the context in which it is used, the program is ill-formed. Note that visibility is not part of the selection process.
C++ - Constructor overloading - private and public
[ "", "c++", "compiler-construction", "constructor", "overloading", "private", "" ]
I'm trying to develop a standalone Java web service client with JAX-WS (Metro) that uses WS-Security with Username Token Authentication (Password digest, nonces and timestamp) and timestamp verification along with WS-Addressing over SSL. The WSDL I have to work with does not define any security policy information. I have been unable to figure out exactly how to add this header information (the correct way to do so) when the WSDL does not contain this information. Most examples I have found using Metro revolve around using Netbeans to automatically generate this from the WSDL which does not help me at all. I have looked into WSIT, XWSS, etc. without much clarity or direction. JBoss WS Metro looked promising not much luck yet there either. Anyone have experience doing this or have suggestions on how to accomplish this task? Even pointing me in the right direction would be helpful. I am not restricted to a specific technology other than it must be Java based.
I did end up figuring this issue out but I went in another direction to do so. My solution was to use CXF 2.1 and its JAX-WS implementation, combining the power of CXF with the existing Spring infrastructure I already had in place. I was skeptical at first because of the numerous jars required by CXF, but in the end it provided the best and simplest solution. Adapting an example from the [CXF website for client configuration](http://cwiki.apache.org/CXF20DOC/jax-ws-configuration.html), I used the custom CXF JAXWS namespace within spring and used an Out Interceptor for Username Token Authentication (Password digest, nonces and timestamp) and timestamp verification. The only other step to make this work was creating my own Password Callback handler that is executed for each outbound SOAP request. For SSL configuration, I again turned to [CXF and its SSL support via conduits](http://cwiki.apache.org/CXF20DOC/client-http-transport-including-ssl-support.html), although I could never make SSL work with a specific http:conduit name, I had to use the general purpose one that is not recommended for production environments. Below is an example of my config file. **Spring config file** ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:context="http://www.springframework.org/schema/context" xmlns:cxf="http://cxf.apache.org/core" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"> <context:property-placeholder location="meta/my.properties" /> <context:component-scan base-package="com.foo" /> <import resource="remoting.xml" /> <jaxws:client id="myWebService" address="${my.endpointAddress}" serviceClass="com.foo.my.ServicePortType"> <!-- Testing only, adds logging of entire message in and out --> <jaxws:outInterceptors> <ref bean="TimestampUsernameToken_Request" /> <ref bean="logOutbound" /> </jaxws:outInterceptors> <jaxws:inInterceptors> <ref bean="logInbound" /> </jaxws:inInterceptors> <jaxws:inFaultInterceptors> <ref bean="logOutbound" /> </jaxws:inFaultInterceptors> <!-- Production settings --> <!-- <jaxws:outInterceptors> <ref bean="TimestampUsernameToken_Request" /> </jaxws:outInterceptors> --> </jaxws:client > <!-- CXF Interceptors for Inbound and Outbound messages Used for logging and adding Username token / Timestamp Security Header to SOAP message --> <bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor" /> <bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor" /> <bean id="TimestampUsernameToken_Request" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor"> <constructor-arg> <map> <entry key="action" value="UsernameToken Timestamp" /> <entry key="user" value="${my.group}.${my.userId}" /> <entry key="passwordType" value="PasswordDigest" /> <entry key="passwordCallbackClass" value="com.foo.my.ClientPasswordHandler" /> </map> </constructor-arg> </bean> <!-- http:conduit namespace is used to configure SSL using keystores, etc *.http-conduit works but CXF says its only supposed to be for temporary use (not production), well until the correct way works, we're going to use it. --> <http:conduit name="*.http-conduit"> <http:tlsClientParameters secureSocketProtocol="SSL"> <!-- <sec:trustManagers> <sec:keyStore type="JKS" password="${my.truststore.password}" file="${my.truststore.file}" /> </sec:trustManagers> --> <sec:keyManagers keyPassword="${my.keystore.password}"> <sec:keyStore type="JKS" password="${my.keystore.password}" file="${my.keystore.file}" /> </sec:keyManagers> <!-- Cipher suites filters specify the cipher suite to allow/disallow in SSL communcation --> <sec:cipherSuitesFilter> <sec:include>.*_WITH_3DES_.*</sec:include> <sec:include>.*_EXPORT_.*</sec:include> <sec:include>.*_EXPORT1024_.*</sec:include <sec:include>.*_WITH_DES_.*</sec:include <sec:exclude>.*_WITH_NULL_.*</sec:exclude <sec:exclude>.*_DH_anon_.*</sec:exclude> </sec:cipherSuitesFilter> </http:tlsClientParameters> </http:conduit> </beans> ``` --- **Java Client Password Handler**: ``` import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.log4j.Logger; import org.apache.ws.security.WSPasswordCallback; /** * <p> * Provides a callback handler for use processing outbound/inbound SOAP messages. * ClientPasswordHandler sets the password used in the WS-Security UsernameToken * SOAP header. * * </p> * * Created: Apr 1, 2009 * @author Jared Knipp * */ public final class ClientPasswordHandler implements CallbackHandler { protected static Logger log = Logger.getLogger(ClientPasswordHandler.class); private static final PropertyManager PROPS = PropertyManager.getInstance(); private static String PASSWORD = PROPS.getPassword(); private static boolean IS_PASSWORD_CLEAR = PROPS.getIsClearPassword(); /** * Client password handler call back. This method is used to provide * additional outbound (or could be inbound also) message processing. * * Here the method sets the password used in the UsernameToken SOAP security header * element in the SOAP header of the outbound message. For our purposes the clear * text password is SHA1 hashed first before it is hashed again along with the nonce and * current timestamp in the security header. */ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { if(log.isDebugEnabled()) { log.debug("Setting password for UsernameToken"); } WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; // Check to see if the password is already Hashed via SHA1, if not then hash it first if(IS_PASSWORD_CLEAR) { synchronized(this) { PASSWORD = PasswordDigestUtil.doPasswordDigest(PASSWORD); IS_PASSWORD_CLEAR = false; PROPS.setIsClearPassword(IS_PASSWORD_CLEAR); PROPS.setPassword(PASSWORD); PROPS.saveProperties(); } } pc.setPassword(PASSWORD); } } ```
If the information isn't in the WSDL, are you sure it's in the service described by the WSDL? The WSDL is meant to provide all the information necessary to describe the service, including the security policies necessary to use the service. What platform did the WSDL come from? Is it possible that the WSDL is not the complete description? For instance, it might be a WSDL that is *include*d in another WSDL that *does* provide the security information.
JAX-WS Consuming web service with WS-Security and WS-Addressing
[ "", "java", "web-services", "jax-ws", "ws-security", "java-metro-framework", "" ]
I have 2 tables (srcTable1 & destTable) that have identical schemas. I am trying to copy all rows from srcTable to destTable and ignore the duplicates. I thought I could just add a WHERE clause with a subquery that would give me only the rows that aren't duplicates. However, it doesn't seem to work. I don't get any rows inserted or selected. ``` INSERT INTO destTable SELECT * FROM srcTable WHERE NOT EXISTS(SELECT * FROM destTable) ``` I realize I could do something like this: ``` INSERT INTO destTable SELECT * FROM srcTable WHERE MyKey IN (SELECT MyKey FROM destTable) ``` However, my tables have multiple keys and I can't think of how you could do this with multiple keys. Any idea what I'm doing wrong or do you have any better ideas?
Your problem is that you need another where clause in the subquery that identifies what makes a duplicate: ``` INSERT INTO destTable SELECT Field1,Field2,Field3,... FROM srcTable WHERE NOT EXISTS(SELECT * FROM destTable WHERE (srcTable.Field1=destTable.Field1 and SrcTable.Field2=DestTable.Field2...etc.) ) ``` As noted by another answerer, an outer join is probably a more concise approach. My above example was just an attempt to explain using your current query to be more understandible. Either approach could technically work. ``` INSERT INTO destTable SELECT s.field1,s.field2,s.field3,... FROM srcTable s LEFT JOIN destTable d ON (d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...) WHERE d.Key1 IS NULL ``` Both of the above approaches assume you are woried about inserting rows from source that might already be in destination. If you are instead concerned about the possibility that source has duplicate rows you should try something like. ``` INSERT INTO destTable SELECT Distinct field1,field2,field3,... FROM srcTable ``` One more thing. I'd also suggest listing the specific fields on your insert statement instead of using SELECT \*.
I realize this is old, but I got here from google and after reviewing the accepted answer I did my own statement and it worked for me hope someone will find it useful: ``` INSERT IGNORE INTO destTable SELECT id, field2,field3... FROM origTable ``` Edit: This works on MySQL I did not test on MSSQL
Copy rows from one table to another, ignoring duplicates
[ "", "sql", "t-sql", "" ]
Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database. An "editor" process is any editor for that database: it changes the database constantly. Now I want the player to reflect the editing changes quickly. I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes. I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size. I am thinking about using a log table and triggers, but I wonder if there is a simpler method.
A relational database is not your best first choice for this. Why? You want all of your editors to pass changes to your player. Your player is -- effectively -- a server for all those editors. Your player needs multiple open connections. It must listen to all those connections for changes. It must display those changes. If the changes are really large, you can move to a hybrid solution where the editors persist the changes *and* notify the player. Either way, the editors must notify they player that they have a change. It's much, much simpler than the player trying to discover changes in a database. --- A better design is a server which accepts messages from the editors, persists them, and notifies the player. This server is neither editor nor player, but merely a broker that assures that all the messages are handled. It accepts connections from editors and players. It manages the database. There are two implementations. Server IS the player. Server is separate from the player. The design of server doesn't change -- only the protocol. When server is the player, then server calls the player objects directly. When server is separate from the player, then the server writes to the player's socket. When the player is part of the server, player objects are invoked directly when a message is received from an editor. When the player is separate, a small reader collects the messages from a socket and calls the player objects. The player connects to the server and then waits for a stream of information. This can either be input from the editors or references to data that the server persisted in the database. If your message traffic is small enough so that network latency is not a problem, editor sends all the data to the server/player. If message traffic is too large, then the editor writes to a database and sends a message with just a database FK to the server/player. --- Please clarify "If the editor crashes while notifying, the player is permanently messed up" in your question. This sounds like a poor design for the player service. It can't be "permanently messed up" unless it's not getting state from the various editors. If it's getting state from the editors (but attempting to mirror that state, for example) then you should consider a design where the player simply gets state from the editor and cannot get "permanently messed up".
SQLite has an [`update_hook`](https://www.sqlite.org/c3ref/update_hook.html) function which does what you want. > SQLite C Interface > > Data Change Notification Callbacks ``` void *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); ``` > The `sqlite3_update_hook()` interface registers a callback function with > the database connection identified by the first argument to be invoked > whenever a row is updated, inserted or deleted in a rowid table. Any > callback set by a previous call to this function for the same database > connection is overridden. Unfortunately it isn't exposed by the Python sqlite module... Here is a slightly hacky workaround that digs into the C api (from Python code) to make use of it: <https://stackoverflow.com/a/16920926>
How do I notify a process of an SQLite database change done in a different process?
[ "", "python", "sqlite", "notifications", "" ]
Can someone explain why this doesn't work like I think it should. ``` double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.3, 2.3, 2.4, 2.5 }; double[] numbers2 = { 2.2 }; IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2); foreach (double number in onlyInFirstSet) Console.WriteLine(number); /* This code produces the following output: 2 2.1 2.3 2.4 2.5 */ ``` What I would expect is 2, 2.1, 2.3, 2.3, 2.3, 2.4, 2.5. Why would except return a distinct list? Is this a bug? Update: Ok, totally missed that point in the docs. Funny 4 people respond with the same answer. You would think you would just up vote the guy who answered it first.:)
> Why would except return a distinct list? Is this a bug? Nope. `Except` produces a **set difference**. See the [documentation](http://msdn.microsoft.com/en-us/library/bb300779.aspx): > Produces the set difference of two sequences by using the default equality comparer to compare values. To do what you want, just use `Where` to filter the values appropriately. For example: ``` "abcdddefffg".Where(e => !"cde".Contains(e)); // Produces "abfffg". ```
This is actually the correct behaviour. The `Except` method is documented to return the *set* difference of the two IEnumerable arguments. Since by definition, sets cannot contain duplicate elements, these are eliminated in the result. See the [MSDN docs](http://msdn.microsoft.com/en-us/library/bb300779.aspx) for more info.
Enumerable.Except Problem
[ "", "c#", "linq", "" ]
I am working in Java and am wondering, are multi-dimensional arrays like grids where rows are elements and columns are dimensions, or are they hyper-geometric figures that we can't see?
A 1D array is like a list, a 2D array is like a table with columns and rows, a 3D array is like a cube, x, y and z and anything more than that would be hyper-geometric. You could represent a cube with time with a 4D array.
Sometimes it's useful to think of multidimensional arrays as geometric: lists, tables, cubes. Other times, such as when the arrays aren't of equal length, it's not. They might be: * lists of tables * lists of lists of lists * tables of cubes At some (early) point it's time to make some `class`es.
Multi-Dimensional Arrays
[ "", "java", "arrays", "" ]
I'm in a bit of a fiddle in that I don't know why my code brings up the following error when compiling: ``` 1>..\SA.cpp(81) : error C2664: 'CFE' : cannot convert parameter 1 from 'int' to 'int []' 1> Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast ``` Essentially I am trying to: Step1: Convert from a vector to an array using: ``` int* VecToArray(vector<int> Vec) { int ary[Vec.size()]; for(int i = 0; i < Vec.size(); i++) ary[i] = Vec[i]; return ary; } ``` Step2: Calling upon a function into which the array is an paremeter and it returns a pointer from a newly generated array: ``` int* CFE(int density[]) { ...do stuff to generate 'double Energy[]'.... return Energy; } ``` Step 3: Using this pointer in a third function to calcualte the sum of Energy[]: ``` double ObjFunction (double *E_Array) { double SumEnergy = 0; int n = 10; // Is irrelivant for (int i = 0; i < n; i++) { SumEnergy += E_Array[i]; } return SumEnergy; } ``` To make for simpler coding I've used the functions like so, where VectorName is an integer vector: ``` double TotalEnergy = ObjFunction ( CFE ( VecToArray ( VectorName ) ) ); ``` I am obviously getting the parameter types wrong somewhere, though I just cant see why myself. Could anyone with a more experienced eye assist in spotting it/them?
Where does `Energy` come from? If it's a `double[]` then you can't just cast it to an `int*`. `std::vector<int>` is guaranteed to be contiguous, so if you want to convert a `std::vector<int> VectorName` to an `const int*` use `&VectorName[0]`. If, on the other hand, your CFE function modifies the array is passed, it's probably better off creating it locally.
Not sure about the compiler error, but you are going to have big problems if you return a local array from a function.
Error in returning a pointer from a function that points to an array
[ "", "c++", "arrays", "pointers", "function", "return", "" ]
I'm new to XML-RPC and I would like to know if there is any good tutorial to use XML-RPC with the Last.fm API. Is it possible to call the API methods using the xmlrpclib module like in the following example? ``` import xmlrpclib myserver = xmlrpclib.ServerProxy('http://ws.audioscrobbler.com/2.0/') ```
Your code looks just fine. You might not know this, but most XML-RPC endpoints (such as Last.fm's) support [XML-RPC introspection](http://xmlrpc-c.sourceforge.net/introspection.html). For instance, if you want to find out what methods it exposes, do this: ``` import xmlrpclib svc = xmlrpclib.ServerProxy('http://ws.audioscrobbler.com/2.0/') print svc.system.listMethods() ``` And you'll be given a list of the methods exposed by the XML-RPC endpoint. By the way, that bit of code up there demonstrates how to use a `ServerProxy` object to call a method exposed by the endpoint it's tied to, in this case, the `system.listMethods` method. If you wanted to call the `user.getTopTags` (as demonstrated on the [API documentation homepage](http://www.last.fm/api/xmlrpc)) method exposed by Last.fm, you'd do this: ``` print svc.user.getTopTags({'user': 'foo', 'api_key': 'bar'}) ``` Dead simple! Of course, you'll need an API key from Last.fm before you can use the API.
# pylast --- ### Last fm library in Python The [pylast library](http://pypi.python.org/pypi/pylast/0.3.1) is a good choice for this work. The library has a very large set of functionality covering all the major parts of the [last.fm API](http://www.last.fm/api). ### Functionality This includes: Albums, Artists, Auth, Events, Geo, Libraries, Playlists, Tags, Tasteometer ratings, Users and Venues. Using a library such as this means that a lot of the work is done for you, so you dont spend time reinventing the wheel. (The library iteself is 3,000+ lines of code). ### License Because of the license which this library is released under, it is possible to modify the code yourself. There is also a community of people working to hightlight any bugs in the library at <http://sourceforge.net/tracker/?group_id=66150&atid=513503>
Is there any good Python tutorial/guide to use XML-RPC with Last.fm API?
[ "", "python", "web-services", "xml-rpc", "" ]
Please can someone tell me a simple way to find href and src tags in an html file using regular expressions in Java? And then, how do I get the URL associated with the tag? Thanks for any suggestion.
Using regular expressions to pull values from HTML is always a mistake. HTML syntax is a lot more complex that it may first appear and it's very easy for a page to catch out even a very complex regular expression. Use an [HTML Parser](http://www.google.co.uk/search?&q=java+html+parser) instead. See also [What are the pros and cons of the leading Java HTML parsers?](https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers)
The other answers are true. Java Regex API is not a proper tool to achieve your goal. Use efficient, secure and well tested high-level tools mentioned in the other answers. If your question concerns rather Regex API than a real-life problem (learning purposes for example) - you can do it with the following code: ``` String html = "foo <a href='link1'>bar</a> baz <a href='link2'>qux</a> foo"; Pattern p = Pattern.compile("<a href='(.*?)'>"); Matcher m = p.matcher(html); while(m.find()) { System.out.println(m.group(0)); System.out.println(m.group(1)); } ``` And the output is: ``` <a href='link1'> link1 <a href='link2'> link2 ``` Please note that lazy/reluctant qualifier \*? must be used in order to reduce the grouping to the single tag. Group 0 is the entire match, group 1 is the next group match (next pair of parenthesis).
How to use regular expressions to parse HTML in Java?
[ "", "java", "regex", "" ]
Anyone know an easy way to get the date of the first day in the week (monday here in Europe). I know the year and the week number? I'm going to do this in C#.
I had issues with the solution by @HenkHolterman even with the fix by @RobinAndersson. Reading up on the ISO 8601 standard resolves the issue nicely. Use the first Thursday as the target and not Monday. The code below will work for Week 53 of 2009 as well. ``` public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear) { DateTime jan1 = new DateTime(year, 1, 1); int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek; // Use first Thursday in January to get first week of the year as // it will never be in Week 52/53 DateTime firstThursday = jan1.AddDays(daysOffset); var cal = CultureInfo.CurrentCulture.Calendar; int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); var weekNum = weekOfYear; // As we're adding days to a date in Week 1, // we need to subtract 1 in order to get the right date for week #1 if (firstWeek == 1) { weekNum -= 1; } // Using the first Thursday as starting week ensures that we are starting in the right year // then we add number of weeks multiplied with days var result = firstThursday.AddDays(weekNum * 7); // Subtract 3 days from Thursday to get Monday, which is the first weekday in ISO8601 return result.AddDays(-3); } ```
### Note The below answer uses the .NET Calendar rules. It does not promise ISO8601 conformance. See some of the other answers here when you need that. Week numbering is a mess, always try to find out what rules you need to follow first. --- The code below correctly puts the start of week 1, 2009 at 29-12-2008. The CalendarWeekRule probably should be a parameter. Note that the weekNum should be >= 1 ``` static DateTime FirstDateOfWeek(int year, int weekNum, CalendarWeekRule rule) { Debug.Assert(weekNum >= 1); DateTime jan1 = new DateTime(year, 1, 1); int daysOffset = DayOfWeek.Monday - jan1.DayOfWeek; DateTime firstMonday = jan1.AddDays(daysOffset); Debug.Assert(firstMonday.DayOfWeek == DayOfWeek.Monday); var cal = CultureInfo.CurrentCulture.Calendar; int firstWeek = cal.GetWeekOfYear(firstMonday, rule, DayOfWeek.Monday); if (firstWeek <= 1) { weekNum -= 1; } DateTime result = firstMonday.AddDays(weekNum * 7); return result; } ```
Calculate date from week number
[ "", "c#", ".net", "week-number", "" ]
I've been using [this](https://stackoverflow.com/questions/92093/removing-leading-zeroes-from-a-field-in-a-sql-statement) for some time: ``` SUBSTRING(str_col, PATINDEX('%[^0]%', str_col), LEN(str_col)) ``` However recently, I've found a problem with columns with all "0" characters like '00000000' because it never finds a non-"0" character to match. An alternative technique I've seen is to use `TRIM`: ``` REPLACE(LTRIM(REPLACE(str_col, '0', ' ')), ' ', '0') ``` This has a problem if there are embedded spaces, because they will be turned into "0"s when the spaces are turned back into "0"s. I'm trying to avoid a scalar UDF. I've found a lot of performance problems with UDFs in SQL Server 2005.
``` SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col)) ```
Why don't you just cast the value to `INTEGER` and then back to `VARCHAR`? ``` SELECT CAST(CAST('000000000' AS INTEGER) AS VARCHAR) -------- 0 ```
Better techniques for trimming leading zeros in SQL Server?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "string", "" ]
I have seen and used C++ code like the following: ``` int myFourcc = 'ABCD'; ``` It works in recent versions of GCC, not sure how recent. Is this feature in the standard? What is it called? I have had trouble searching the web for it... EDIT: I found this info as well, for future observers: from [gcc documentation](http://gcc.gnu.org/onlinedocs/cpp/Implementation_002ddefined-behavior.html#Implementation_002ddefined-behavior "gcc documentation") > The compiler values a multi-character character constant a character at a time, shifting the previous value left by the number of bits per target character, and then or-ing in the bit-pattern of the new character truncated to the width of a target character. The final bit-pattern is given type int, and is therefore signed, regardless of whether single characters are signed or not (a slight change from versions 3.1 and earlier of GCC). If there are more characters in the constant than would fit in the target int the compiler issues a warning, and the excess leading characters are ignored. > > For example, 'ab' for a target with an 8-bit char would be interpreted as `(int) ((unsigned char) 'a' * 256 + (unsigned char) 'b')', and '\234a' as` (int) ((unsigned char) '\234' \* 256 + (unsigned char) 'a')'.
"Note that according to the C standard there is no limit on the length of a character constant, but the value of a character constant that contains more than one character is implementation-defined. Recent versions of GCC provide support multi-byte character constants, and instead of an error the warnings *multiple-character character constant* or *warning: character constant too long for its type* are generated in this case."
See section 6.4.4.4, paragraph 10 of the C99 standard: > An integer character constant has type `int`. The value of an integer character constant > containing a single character that maps to a single-byte execution character is the > numerical value of the representation of the mapped character interpreted as an integer. > The value of an integer character constant containing more than one character (e.g., > `'ab'`), or containing a character or escape sequence that does not map to a single-byte > execution character, is implementation-defined. If an integer character constant contains > a single character or escape sequence, its value is the one that results when an object with > type `char` whose value is that of the single character or escape sequence is converted to > type `int`. Recall that *implementation-defined* means that the implementation (in this case, the C compiler) can do whatever it wants, but it **must be documented**. Most compilers will convert it to an integral constant corresponding to the concatenation of the octets corresponding to the individual characters, but the endianness could be either little- or big-endian, depending on the endianness of the target architecture. Therefore, portable code should not use multi-character constants and should instead use plain integral constants. Instead of `'abcd'`, which could be of either endianness, use either 0x61626364 or 0x64636261, which have known endiannesses (big and little respectively).
Is int x = 'fooo' a compiler extension?
[ "", "c++", "c", "gcc", "" ]
What is inlining? What is it used for? Can you inline something in C#?
**What it is** In the terms of C and C++ you use the inline keyword to tell the compiler to call a routine without the overhead of pushing parameters onto the stack. The Function instead has it's machine code inserted into the function where it was called. This can create a significant increase in performance in certain scenarios. **Dangers** The speed benefits in using "inlining" decrease significantly as the size of the inline function increases. Overuse can actually cause a program to run slower. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. **Inlining in C#** In C# inlining happens at the JIT level in which the JIT compiler makes the decision. There is currently no mechanism in C# which you can explicitly do this. If you wish to know what the JIT compiler is doing then you can call: `System.Reflection.MethodBase.GetCurrentMethod().Name` at runtime. If the Method is inlined it will return the name of the caller instead. In C# you cannot force a method to inline but you can force a method not to. If you really need access to a specific callstack and you need to remove inlining you can use: `MethodImplAttribute` with `MethodImplOptions.NoInlining`. In addition if a method is declared as virtual then it will also not be inlined by the JIT. The reason behind this is that the final target of the call is unknown. [More on inlining](https://learn.microsoft.com/en-us/archive/blogs/davidnotario/jit-optimizations-inlining-i)
For definition and discussion of inlining, [see this question](https://stackoverflow.com/questions/132738/why-should-i-ever-use-inline-code). In C# you don't need to instruct the compiler or run-time to inline because the run-time will do it automatically. P.S. This answer is also correct for Java.
Inlining Functions
[ "", "c#", "inlining", "" ]
I would like to find a way to loop through all the active processes and do diagnostics checks on them (mem usage, cpu time etc) kinda similar to the task manager. The problem is broken down into two parts: 1. Finding all the processes 2. Finding diagnostics attributes about them I am not sure even in what namespace to go looking about it. Any help / tips / links is grateful.
**Finding all of the processes** You can do this through the Process class ``` using System.Diagnostics; ... var allProcesses = Process.GetProcesses(); ``` **Running Diagnostics** Can you give us some more information here? It's not clear what you want to do. The Process class provides a bit of information though that might help you out. It is possible to query this class for * All threads * Main Window Handle * All loaded modules * Various diagnostic information about Memory (Paged, Virtual, Working Set, etc ...) * Basic Process Information (id, name, disk location) **EDIT** OP mentioned they want to get memory and CPU information. These properties are readily available on the Process class (returned by GetProcesses()). Below is the MSDN page that lists all of the supported properties. There are various memory and CPU ones available that will suite your needs. <http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx> **Code:** Add this line to your using list: ``` using System.Diagnostics; ``` Now you can get a list of the processes with the Process.GetProcesses() method, as seen in this example: ``` Process[] processlist = Process.GetProcesses(); foreach (Process theprocess in processlist) { Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id); } ```
Finding all processes is rather easy actually: ``` using System.Diagnostics; Process[] processes = Process.GetProcesses(); foreach (Process process in processes) { // Get whatever attribute for process. } ```
How can I list all processes running in Windows?
[ "", "c#", ".net", "pid", "diagnostics", "" ]
I have a binary named `A` that generates output when called. If I call it from a Bash shell, most of the output is suppressed by `A > /dev/null`. All of the output is suppressed by `A &> /dev/null` I have a python script named `B` that needs to call `A`. I want to be able to generate output from `B`, while suppressing all the output from `A`. From within `B`, I've tried `os.system('A')`, `os.system('A > /dev/null')`, and `os.system('A &> /dev/null')`, `os.execvp('...')`, etc. but none of those suppress all the output from A. I could run `B &> /dev/null`, but that suppresses all of `B`'s output too and I don't want that. Anyone have suggestions?
If you have Python 2.4, you can use [the subprocess module](http://docs.python.org/library/subprocess.html): ``` >>> import subprocess >>> s = subprocess.Popen(['cowsay', 'hello'], \ stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0] >>> print s _______ < hello > ------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || ```
``` import os import subprocess command = ["executable", "argument_1", "argument_2"] with open(os.devnull, "w") as fnull: result = subprocess.call(command, stdout = fnull, stderr = fnull) ``` If the command doesn't have any arguments, you can just provide it as a simple string. If your command relies on shell features like wildcards, pipes, or environment variables, you'll need to provide the whole command as a string, and also specify `shell = True`. This should be avoided, though, since it represents a security hazard if the contents of the string aren't carefully validated.
Suppress output in Python calls to executables
[ "", "python", "redirect", "" ]