source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
140,422
I'm looking for pseudocode, or sample code, to convert higher bit ascii characters (like, Ü which is extended ascii 154) into U (which is ascii 85). My initial guess is that since there are only about 25 ascii characters that are similar to 7bit ascii characters, a translation array would have to be used. Let me know if you can think of anything else.
For .NET users the article in CodeProject (thanks to GvS's tip ) does indeed answer the question more correctly than any other I've seen so far. However the code in that article (in solution #1) is cumbersome. Here's a compact version: // Based on http://www.codeproject.com/Articles/13503/Stripping-Accents-from-Latin-Characters-A-Foray-inprivate static string LatinToAscii(string inString){ var newStringBuilder = new StringBuilder(); newStringBuilder.Append(inString.Normalize(NormalizationForm.FormKD) .Where(x => x < 128) .ToArray()); return newStringBuilder.ToString();} To expand a bit on the answer, this method uses String.Normalize which: Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form. Specifically in this case we use the NormalizationForm FormKD , described in those same MSDN docs as such: FormKD - Indicates that a Unicode string is normalized using full compatibility decomposition. For more information about unicode normalization forms, see Unicode Annex #15 .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245/" ] }
140,439
How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears. I can't even bind to perform a simple query: import sysimport ldapServer = "ldap://my-ldap-server"DN, Secret, un = sys.argv[1:4]Base = "dc=mydomain,dc=co,dc=uk"Scope = ldap.SCOPE_SUBTREEFilter = "(&(objectClass=user)(sAMAccountName="+un+"))"Attrs = ["displayName"]l = ldap.initialize(Server)l.protocol_version = 3print l.simple_bind_s(DN, Secret)r = l.search(Base, Scope, Filter, Attrs)Type,user = l.result(r,60)Name,Attrs = user[0]if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'): displayName = Attrs['displayName'][0] print displayNamesys.exit() Running this with [email protected] password username gives me one of two errors: Invalid Credentials - When I mistype or intentionally use wrong credentials it fails to authenticate. ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'} Or ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'} What am I missing out to bind properly? I am getting the same errors on fedora and windows.
I was missing l.set_option(ldap.OPT_REFERRALS, 0) From the init.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/140439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4319/" ] }
140,453
My company is considering changing continuous integration servers (I won't say which one we have now, so I won't skew your responses in anyway :) ) I wondering if anybody has any recommendations? Best user experience, level of difficulty to maintain, etc... Our code is all in java, and we use ANT as a build tool.
I recently implemented a Hudson server. Having previously used Cruise Control, I am very satisfied with Hudson and very impressed with its ease of setup and use. Adding new projects is infinitely easier than it was with Cruise Control.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/140453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22221/" ] }
140,468
What is the longest string that can be created in .NET? The docs for the String class are silent on this question as far as I can see, so an authoritative answer might require some knowledge of internals. Would the maximum change on a 64-bit system? [This is asked more for curiosity than for practical use - I don't intend to create any code that uses gigantic strings!]
The theoretical limit may be 2,147,483,647, but the practical limit is nowhere near that. Since no single object in a .NET program may be over 2GB and the string type uses UTF-16 (2 bytes for each character), the best you could do is 1,073,741,823, but you're not likely to ever be able to allocate that on a 32-bit machine. This is one of those situations where "If you have to ask, you're probably doing something wrong."
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/140468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3776/" ] }
140,490
Which gets called first - the base constructor or "other stuff here"? public class MyExceptionClass : Exception{ public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here }}
The base constructor will be called first. try it: public class MyBase{ public MyBase() { Console.WriteLine("MyBase"); }}public class MyDerived : MyBase{ public MyDerived():base() { Console.WriteLine("MyDerived"); }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/140490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16872/" ] }
140,549
RFC 1738 specifies the syntax for URL's, and mentions that URLs are written only with the graphic printable characters of the US-ASCII coded character set. The octets 80-FF hexadecimal are not used in US-ASCII, and the octets 00-1F and 7F hexadecimal represent control characters; these must be encoded. It does not, however, say what code set these octets then represent. RFC 2396 seems to try and improve on the situation, but: For original character sequences that contain non-ASCII characters, however, the situation is more difficult. Internet protocols that transmit octet sequences intended to represent character sequences are expected to provide some way of identifying the charset used, if there might be more than one [RFC2277]. However, there is currently no provision within the generic URI syntax to accomplish this identification. An individual URI scheme may require a single charset, define a default charset, or provide a way to indicate the charset used. It is expected that a systematic treatment of character encoding within URI will be developed as a future modification of this specification. Is there any unambigous way in which a client can determine in which character set to interpret encoded octets, or in which a server can determine what a client used to encode with ? It looks to me like most servers default to UTF-8, but this seems to be a de facto choice more than a specified one.
As per your quote, URLs are ASCII. That's all. URIs OTOH, allow for bigger charsets; usually UTF-8 as you said yourself. The point to remember is that URLs are a subset of URIs. Therefore, the real question is, which of these is what you write in a browser? I'd guess you can write an URI, and the browser should try its best to transform to an URL (which is what HTTP/1.1 support, AFAICR). For non-ASCII characters, that means hexcodes, usually coding UTF-8.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ] }
140,550
What is the best way to store a large amount of text in a table in SQL server? Is varchar(max) reliable?
In SQL 2005 and higher, VARCHAR(MAX) is indeed the preferred method. The TEXT type is still available, but primarily for backward compatibility with SQL 2000 and lower.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/140550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17648/" ] }
140,613
OpenID is all good... UNTIL the provider goes down. At that point you're potentially locked out of EVERYTHING (since you jumped on the bandwagon and applied OpenID everywhere you could). This question came up because I can't, for the life of me, login with my myopenid.com provider. :-(
The fix is for your OpenID site to accept multiple OpenIDs per user account. Something that the spec recommends.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ] }
140,614
My Ubuntu server has Apache and Subversion installed. I use this server as a staging server, purely for testing purposes. I use Apache to host the web application, and Subversion to keep versioned copies of the source code. My current workflow: Make changes to a file Commit the file to the Subversion repository Upload the file new over SFTP to the Apache public directory View the changes in my web browser I would be much happier if my workflow was like this: Make changes to a file Commit the file to the Subversion repository In the background, Subversion puts a copy of the committed file into the Apache public directory View the changes in my web browser I have very little server admin experience, and any help or pointers are appreciated. I heard that post-commit hooks are what I need, and that I can write bash scripts to do this, but I'm not sure where to start and didn't really find anything after quite a lot of Googling. Thank you!
The "official" answer is here. I'm managing a website in my repository. How can I make the live site automatically update after every commit?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ] }
140,616
Is there a NAnt task that will echo out all property names and values that are currently set during a build? Something equivalent to the Ant echoproperties task maybe?
Try this snippet: <project> <property name="foo" value="bar"/> <property name="fiz" value="buz"/> <script language="C#" prefix="util" > <code> <![CDATA[ public static void ScriptMain(Project project) { foreach (DictionaryEntry entry in project.Properties) { Console.WriteLine("{0}={1}", entry.Key, entry.Value); } } ]]> </code> </script></project> You can just save and run with nant. And no, there isn't a task or function to do this for you already.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ] }
140,627
I just wrote my first web service so lets make the assumption that my web service knowlege is non existant. I want to try to call a dbClass function from the web service. However I need some params that are in the session. Is there any way I can get these call these session variables from the webservice??
If you are using ASP.NET web services and you want to have a session environment maintained for you, you need to embellish your web service method with an attribute that indicates you require a session. [WebMethod(EnableSession = true)]public void MyWebService(){ Foo foo; Session["MyObjectName"] = new Foo(); foo = Session["MyObjectName"] as Foo;} Once you have done this, you may access session objects similar to aspx. Metro.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ] }
140,640
Is there an NSIS var to get the path of the currently running installer?
Found it: $EXEPATH
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
140,643
When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown. These tables have execute permission for the schema where the view was created. If I execute the view's SQL Statement it works. What am I missing?
As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as. grant SELECT on TABLE_NAME to READ_USERNAME;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22769/" ] }
140,677
I had a discussion a few weeks back with some co-workers on refactoring, and I seem to be in a minority that believes "Refactor early, refactor often" is a good approach that keeps code from getting messy and unmaintainable. A number of other people thought that it just belongs in the maintenance phases of a project. If you have an opinion, please defend it.
Just like you said: refactor early, refactor often. Refactoring early means the necessary changes are still fresh on my mind. Refactoring often means the changes tend to be smaller. Delaying refactoring only ends up making a big mess which further makes it harder to refactor. Cleaning up as soon as I notice the mess prevents it from building up and becoming a problem later.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/140677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6897/" ] }
140,680
Is there a way in Firebug to start a new script file to apply to page? Basically I want to do work like I'd normally do on the Firebug console but be able to to paste in multi-line functions, etc. It doesn't seem like the console is amenable to that.
Down in the lower-right corner of the FireBug UI you should see a red square icon with an up arrow. Use that and stretch it to a size you like.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ] }
140,728
It often happens that characters such as é gets transformed to é , even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the Content-Type for the page is also set to UTF8. I know about utf8_encode/decode, but I'm not quite sure about where and how to use it. I have read the " The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) " article, but I need some MySQL / PHP specific pointers. How do I ensure that user entered data containing international characters doesn't get corrupted?
On the first look at http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet I think that one important thing is missing (perhaps I overlooked this one).Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a SET NAMES utf8 query prior to any other query you send to the MySQL server. If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using $db=new PDO($dsn, $user, $pass);$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8"); when initializing your db connection.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ] }
140,734
What would be the best practice way to handle the caching of images using PHP. The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag. When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size. The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner, Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.)
I would do it in a different manner. Problems:1. Having PHP serve the files out is less efficient than it could be.2. PHP has to check the existence of files every time an image is requested3. Apache is far better at this than PHP will ever be. There are a few solutions here. You can use mod_rewrite on Apache. It's possible to use mod_rewrite to test to see if a file exists, and if so, serve that file instead. This bypasses PHP entirely, and makes things far faster. The real way to do this, though, would be to generate a specific URL schema that should always exist, and then redirect to PHP if not. For example: RewriteCond %{REQUEST_URI} ^/images/cached/RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-fRewriteRule (.*) /images/generate.php?$1 [L] So if a client requests /images/cached/<something> and that file doesn't exist already, Apache will redirect the request to /images/generate.php?/images/cached/<something> . This script can then generate the image, write it to the cache, and then send it to the client. In the future, the PHP script is never called except for new images. Use caching. As another poster said, use things like mod_expires , Last-Modified headers, etc. to respond to conditional GET requests. If the client doesn't have to re-request images, page loads will speed dramatically, and load on the server will decrease. For cases where you do have to send an image from PHP, you can use mod_xsendfile to do it with less overhead. See the excellent blog post from Arnold Daniels on the issue, but note that his example is for downloads. To serve images inline, take out the Content-Disposition header (the third header() call). Hope this helps - more after my migraine clears up.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22776/" ] }
140,750
I would like to distribute my .NET programs without the .NET framework. Is it possible to compile a .NET program to machine code?
Yes, you can precompile using Ngen.exe, however this does not remove the CLR dependence. You must still ship the IL assemblies as well, the only benefit of Ngen is that your application can start without invoking the JIT, so you get a real fast startup time. According to CLR Via C#: Also, assemblies precompiled using Ngen are usually slower than JIT'ed assemblies because the JIT compiler can optimize to the targets machine (32-bit? 64-bit? Special registers? etc), while NGEN will just produce a baseline compilation. EDIT: There is some debate on the above info from CLR Via C#, as some say that you are required to run Ngen on the target machine only as part of the install process.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13301/" ] }
140,758
In Java you can do File.listFiles() and receive all of the files in a directory. You can then easily recurse through directory trees. Is there an analogous way to do this in Python?
Yes, there is. The Python way is even better. There are three possibilities: 1) Like File.listFiles(): Python has the function os.listdir(path). It works like the Java method. 2) pathname pattern expansion with glob: The module glob contains functions to list files on the file system using Unix shell like pattern, e.g. files = glob.glob('/usr/joe/*.gif') 3) File Traversal with walk: Really nice is the os.walk function of Python. The walk method returns a generation function that recursively list all directories and files below a given starting path. An Example: import osfrom os.path import joinfor root, dirs, files in os.walk('/usr'): print "Current directory", root print "Sub directories", dirs print "Files", files You can even on the fly remove directories from "dirs" to avoid walking to that dir: if "joe" in dirs: dirs.remove("joe") to avoid walking into directories called "joe". listdir and walk are documented here .glob is documented here .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ] }
140,908
Is there any framework for querying XML SQL Syntax, I seriously tire of iterating through node lists. Or is this just wishful thinking (if not idiotic) and certainly not possible since XML isn't a relational database?
XQuery and XPath... XQuery is more what you are looking for if a SQL structure is desirable.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ] }
140,926
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent? So something that would yield this kind of translation table: \r --> \r\n\n --> \r\n\n\n --> \r\n\r\n\n\r --> \r\n\r\n --> \r\n\r\n\n --> \r\n\r\n
I believe this will do what you need: using System.Text.RegularExpressions;// ...string normalized = Regex.Replace(originalString, @"\r\n|\n\r|\n|\r", "\r\n"); I'm not 100% sure on the exact syntax, and I don't have a .Net compiler handy to check. I wrote it in perl, and converted it into (hopefully correct) C#. The only real trick is to match "\r\n" and "\n\r" first. To apply it to an entire stream, just run in on chunks of input. (You could do this with a stream wrapper if you want.) The original perl: $str =~ s/\r\n|\n\r|\n|\r/\r\n/g; The test results: [bash$] ./test.pl\r -> \r\n\n -> \r\n\n\n -> \r\n\r\n\n\r -> \r\n\r\n -> \r\n\r\n\n -> \r\n\r\n Update: Now converts \n\r to \r\n, though I wouldn't call that normalization.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13154/" ] }
140,935
Anyone knows if is possible to have partial class definition on C++ ? Something like: file1.h: class Test { public: int test1();}; file2.h: class Test { public: int test2();}; For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes. I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs. Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class: class genericTest { public: int genericMethod();}; Then let's say for win32: class win32Test: public genericTest { public: int win32Method();}; And maybe: class macTest: public genericTest { public: int macMethod();}; Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this: #ifdef _WIN32 genericTest *test = new win32Test(); #elif MAC genericTest *test = new macTest(); #endif test->genericMethod(); Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code. That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that.
This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18623/" ] }
140,937
Here's what I'd like to do: I want to create a library project that contains my Resource files (ie, UI Labels and whatnot). I'd like to then use the resource library both in my UI and in my Tests. (Ie, basically have a common place for my resources that I reference from multiple projects.) Unfortunately, because the StronglyTypedResourceBuilder (the .Net class which generates the code for Resources) makes resource files internal by default, I can't reference my strongly typed resources in the library from another project (ie, my UI or tests), without jumping through hoops (ie, something similar to what is described here , or writing a public wrapper class/function). Unfortunately, both those solutions remove my ability to keep the references strongly-typed. Has anyone found a straight-forward way to create strongly typed .Net resources that can be referenced from multiple projects? I'd prefer to avoid having to use a build event in order to accomplish this (ie, to do something like replace all instances of 'internal' with 'public', but that's basically my fall-back plan if I can't find an answer..
Not sure which version of Visual Studio you are using, so I will put steps for either one: VS 2008 - When you open the resx file in design view, there is an option at the top beside Add Resource and Remove Resource, called Access Modifier, it is a drop down where you can change the generated code from internal to public. VS 2005 - You don't have the option to generate the code like in VS 2008. It was a feature that was added, because of this headache. There are work around's though. You could use a third party generator like this tool or you could use the InternalsVisibleTo attribute in your AssemblyInfo.cs to add the projects that will have access to the internal classes of your resource library.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6112/" ] }
140,996
In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this: <TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock> But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this: <TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock> However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property). Any ideas?
It looks strange, but it works. We do it in about 20 different places in our app. Hyperlink implicitly constructs a <Run/> if you put text in its "content", but in .NET 3.5 <Run/> won't let you bind to it, so you've got to explicitly use a TextBlock . <TextBlock> <Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}"> <TextBlock Text="{Binding Path=Name}"/> </Hyperlink></TextBlock> Update : Note that as of .NET 4.0 the Run.Text property can now be bound: <Run Text="{Binding Path=Name}" />
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/140996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22789/" ] }
141,045
I want to replace the first occurrence in a given string. How can I accomplish this in .NET?
string ReplaceFirst(string text, string search, string replace){ int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);} Example: string str = "The brown brown fox jumps over the lazy dog";str = ReplaceFirst(str, "brown", "quick"); EDIT : As @itsmatt mentioned , there's also Regex.Replace(String, String, Int32), which can do the same, but is probably more expensive at runtime, since it's utilizing a full featured parser where my method does one find and three string concatenations. EDIT2 : If this is a common task, you might want to make the method an extension method: public static class StringExtension{ public static string ReplaceFirst(this string text, string search, string replace) { // ...same as above... }} Using the above example it's now possible to write: str = str.ReplaceFirst("brown", "quick");
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
141,088
I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
foreach(KeyValuePair<string, string> entry in myDictionary){ // do something with entry.Value or entry.Key}
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/141088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9311/" ] }
141,108
Is it possible to find the foreach index? in a for loop as follows: for ($i = 0; $i < 10; ++$i) { echo $i . ' ';} $i will give you the index. Do I have to use the for loop or is there some way to get the index in the foreach loop?
foreach($array as $key=>$value) { // do stuff} $key is the index of each $array element
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/141108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18334/" ] }
141,123
Under what circumstances would this or would this not be safe? I have a branch that has a four changes (no file add or deletes). Would this be safe to delete? Edit:The reason for wanting to delete it is that it was misnamed and is going to lead to confusion.
I believe that CVS won't actually delete the branch, it will just remove the tag from the branch -- so the branch is still present in each ",v" file that is affected, it just won't be trivially accessible any more. The result is weird, but probably not dangerous.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8256/" ] }
141,126
What is important to keep in mind when designing a database? I don't want to limit your answer to my needs as I am sure that others can benefit from your insights as well. But I am planning a content management system for a multi-client community driven site.
"Normalize till it hurts; de-normalize till it works."
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19226/" ] }
141,140
The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment: void methodName() { int i = 7; for (int j = 0; j < 10; j++) { int i = j * 2; }} Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this! What's the rationale for this design decision for Java? Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)
I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw. in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious. ETA: it might also be related to exception handling in java. i thought part of this question was discussed in a question related to why variables declared in a try section were not available in the catch/finally scopes.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18103/" ] }
141,146
I want to know if my server is running Subversion 1.5. How can I find that out? Also would be nice to know my SVN client version number. svn help hasn't been helpful. Note: I don't want my project's revision number, etc. This question is about the Subversion software itself.
To find the version of the subversion REPOSITORY you can: Look to the repository on the web and on the bottom of the page it will say something like: "Powered by Subversion version 1.5.2 (r32768)." From the command line: <insert curl, grep oneliner here> If not displayed, view source of the page <svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/"> Now for the subversion CLIENT: svn --version will suffice
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/141146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
141,154
I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.
At a command line: SQLCMD -L or OSQL -L (Note: must be a capital L) This will list all the sql servers installed on your network. There are configuration options you can set to prevent a SQL Server from showing in the list. To do this... At command line: svrnetcn In the enabled protocols list, select 'TCP/IP', then click properties. There is a check box for 'Hide server'.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/141154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
141,198
Is there a way to detect if the user is holding down the shift key (or other modifier keys) when executing a javascript bookmarklet? In my tests of Safari 3.1 and Firefox 3, window.event is always undefined.
If you're looking for a way to detect the mouse position while the bookmarklet is being physically clicked, no, there is no way. Since the bookmarklet is positioned outside of any page (this area is generally called the browser "chrome" - which is confusing since there's now a browser with that name) it's not possible to detect JavaScript-related events there. That being said, if you created this as a Firefox extension then you would have access to event information, JavaScript, and keyboard modifiers. But that doesn't appear to be what you're looking for.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5260/" ] }
141,201
I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well. I understand that establish_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work: class Foo < ActiveRecord::Base establish_connection(('foo_' + ENV['RAILS_ENV']).intern)end
Also, it is a good idea to subclass your model that uses different database, such as: class AnotherBase < ActiveRecord::Base self.abstract_class = true establish_connection "anotherbase_#{RAILS_ENV}"end And in your model class Foo < AnotherBaseend It is useful when you need to add subsequent models that access the same, another database.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/809/" ] }
141,203
I'm trying to grok the purpose of .NET's SecureString. From MSDN: An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory. A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector. The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method. Is the automatic encryption the big payoff? And why can't I just say: SecureString password = new SecureString("password"); instead of SecureString pass = new SecureString();foreach (char c in "password".ToCharArray()) pass.AppendChar(c); What aspect of SecureString am I missing?
Some parts of the framework that currently use SecureString : WPF's System.Windows.Controls.PasswordBox control keeps the password as a SecureString internally (exposed as a copy through PasswordBox::SecurePassword ) The System.Diagnostics.ProcessStartInfo::Password property is a SecureString The constructor for X509Certificate2 takes a SecureString for the password The main purpose is to reduce the attack surface, rather than eliminate it. SecureStrings are "pinned" in RAM so the Garbage Collector won't move it around or make copies of it. It also makes sure the plain text won't get written to the Swap file or in core dumps. The encryption is more like obfuscation and won't stop a determined hacker, though, who would be able to find the symmetric key used to encrypt and decrypt it. As others have said, the reason you have to create a SecureString character-by-character is because of the first obvious flaw of doing otherwise: you presumably have the secret value as a plain string already, so what's the point? SecureString s are the first step in solving a Chicken-and-Egg problem, so even though most current scenarios require converting them back into regular strings to make any use of them at all, their existence in the framework now means better support for them in the future - at least to a point where your program doesn't have to be the weak link.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2258/" ] }
141,204
I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here. Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately? public class SomeDataClass : IDisposable{ private SqlConnection _conn; //constructors and methods private DoSomethingWithTheSqlConnection() { //some code excluded for brevity try { using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection)) { _SqlConnection.Open(); countOfSomething = Convert.ToInt32(cmd.ExecuteScalar()); } } finally { //is this the best way? if (_SqlConnection.State == ConnectionState.Closed) _SqlConnection.Close(); } //some code excluded for brevity } public Dispose() { _conn.Dispose(); }}
Wrap your database handling code inside a "using" using (SqlConnection conn = new SqlConnection (...)){ // Whatever happens in here, the connection is // disposed of (closed) at the end.}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ] }
141,232
I'm working on a project with a rather large Oracle database (although my question applies equally well to other databases). We have a web interface which allows users to search on almost any possible combination of fields. To make these searches go fast, we're adding indexes to the fields and combinations of fields on which we believe users will commonly search. However, since we don't really know how our customers will use this software, it's hard to tell which indexes to create. Space isn't a concern; we have a 4 terabyte RAID drive of which we are using only a small fraction. However, I'm worried about the possible performance penalties of having too many indexes. Because those indexes need to be updated every time a row is added, deleted, or modified, I imagine it'd be a bad idea to have dozens of indexes on a single table. So how many indexes is considered too many? 10? 25? 50? Or should I just cover the really, really common and obvious cases and ignore everything else?
It depends on the operations that occur on the table. If there's lots of SELECTs and very few changes, index all you like.... these will (potentially) speed the SELECT statements up. If the table is heavily hit by UPDATEs, INSERTs + DELETEs ... these will be very slow with lots of indexes since they all need to be modified each time one of these operations takes place Having said that, you can clearly add a lot of pointless indexes to a table that won't do anything. Adding B-Tree indexes to a column with 2 distinct values will be pointless since it doesn't add anything in terms of looking the data up. The more unique the values in a column, the more it will benefit from an index.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/141232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ] }
141,241
I've seen reference in some C# posted questions to a "using" clause.Does java have the equivalent?
Yes. Java 1.7 introduced the try-with-resources construct allowing you to write: try(InputStream is1 = new FileInputStream("/tmp/foo"); InputStream is2 = new FileInputStream("/tmp/bar")) { /* do stuff with is1 and is2 */} ... just like a using statement. Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6: InputStream is1 = new FileInputStream("/tmp/foo");try{ InputStream is2 = new FileInputStream("/tmp/bar"); try{ /* do stuff with is1 and is 2 */ } finally { is2.close(); }} finally { is1.close();}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ] }
141,262
I downloaded Hex Workshop, and I was told to read a .dbc file. It should contain 28,315 if you read offset 0x04 and 0x05 I am unsure how to do this? What does 0x04 mean?
0x04 is hex for 4 (the 0x is just a common prefix convention for base 16 representation of numbers - since many people think in decimal), and that would be the fourth byte (since they are saying offset, they probably count the first byte as byte 0, so offset 0x04 would be the 5th byte). I guess they are saying that the 4th and 5th byte together would be 28315, but did they say if this is little-endian or big-endian? 28315 (decimal) is 0x6E9B in hexadecimal notation, probably in the file in order 0x9B 0x6E if it's little-endian. Note: Little-endian and big-endian refer to the order bytes are written. Humans typical write decimal notation and hexadecimal in a big-endian way, so: 256 would be written as 0x0100 (digits on the left are the biggest scale) But that takes two bytes and little-endian systems will write the low byte first: 0x00 0x01. Big-endian systems will write the high-byte first: 0x01 0x00. Typically Intel systems are little-endian and other systems vary.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20256/" ] }
141,278
I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like: WHERE id IN (SELECT id FROM ...) The refactored query runs about 100x faster. (~50 seconds to ~0.3) I expected an improvement, but can anyone explain why it was so drastic? The columns used in the where clause were all indexed. Does SQL execute the query in the where clause once per row or something? Update - Explain results: The difference is in the second part of the "where id in ()" query - 2 DEPENDENT SUBQUERY submission_tags ref st_tag_id st_tag_id 4 const 2966 Using where vs 1 indexed row with the join: SIMPLE s eq_ref PRIMARY PRIMARY 4 newsladder_production.st.submission_id 1 Using index
A "correlated subquery" (i.e., one in which the where condition depends on values obtained from the rows of the containing query) will execute once for each row. A non-correlated subquery (one in which the where condition is independent of the containing query) will execute once at the beginning. The SQL engine makes this distinction automatically. But, yeah, explain-plan will give you the dirty details.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/141278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521/" ] }
141,284
What is the difference between using the Runnable and Callable interfaces when designing a concurrent thread in Java, why would you choose one over the other?
See explanation here . The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/141284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22061/" ] }
141,288
Is it possible to use the Flex Framework and Components, without using MXML? I know ActionScript pretty decently, and don't feel like messing around with some new XML language just to get some simple UI in there. Can anyone provide an example consisting of an .as file which can be compiled (ideally via FlashDevelop, though just telling how to do it with the Flex SDK is ok too) and uses the Flex Framework? For example, just showing a Flex button that pops open an Alert would be perfect. If it's not possible, can someone provide a minimal MXML file which will bootstrap a custom AS class which then has access to the Flex SDK?
I did a simple bootstrap similar to Borek (see below). I would love to get rid of the mxml file, but if I don't have it, I don't get any of the standard themes that come with Flex (haloclassic.swc, etc). Does anybody know how to do what Theo suggests and still have the standard themes applied? Here's my simplified bootstrapping method: main.mxml <?xml version="1.0" encoding="utf-8"?><custom:ApplicationClass xmlns:custom="components.*"/> ApplicationClass.as package components { import mx.core.Application; import mx.events.FlexEvent; import flash.events.MouseEvent; import mx.controls.Alert; import mx.controls.Button; public class ApplicationClass extends Application { public function ApplicationClass () { addEventListener (FlexEvent.CREATION_COMPLETE, handleComplete); } private function handleComplete( event : FlexEvent ) : void { var button : Button = new Button(); button.label = "My favorite button"; button.styleName="halo" button.addEventListener(MouseEvent.CLICK, handleClick); addChild( button ); } private function handleClick(e:MouseEvent):void { Alert.show("You clicked on the button!", "Clickity"); } }} Here are the necessary updates to use it with Flex 4: main.mxml <?xml version="1.0" encoding="utf-8"?><local:MyApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:local="components.*" /> MyApplication.as package components { import flash.events.MouseEvent; import mx.controls.Alert; import mx.events.FlexEvent; import spark.components.Application; import spark.components.Button; public class MyApplication extends Application { public function MyApplication() { addEventListener(FlexEvent.CREATION_COMPLETE, creationHandler); } private function creationHandler(e:FlexEvent):void { var button : Button = new Button(); button.label = "My favorite button"; button.styleName="halo" button.addEventListener(MouseEvent.CLICK, handleClick); addElement( button ); } private function handleClick(e:MouseEvent):void { Alert.show("You clicked it!", "Clickity!"); } }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ] }
141,291
I want to be able to list only the directories inside some folder.This means I don't want filenames listed, nor do I want additional sub-folders. Let's see if an example helps. In the current directory we have: >>> os.listdir(os.getcwd())['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_python-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.exe', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl', 'Tools', 'w9xpopen.exe'] However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following: >>> for root, dirnames, filenames in os.walk('.'):... print dirnames... break...['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools'] However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.
Filter the result using os.path.isdir() (and use os.path.join() to get the real path): >>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/141291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ] }
141,302
Is there a way to check if a file has been opened by ReWrite in Delphi? Code would go something like this: AssignFile(textfile, 'somefile.txt');if not textFile.IsOpen then Rewrite(textFile);
You can get the filemode. (One moment, I'll create an example). TTextRec(txt).Mode gives you the mode: 55216 = closed55217 = open read55218 = open writefmClosed = $D7B0;fmInput = $D7B1;fmOutput = $D7B2;fmInOut = $D7B3; Search TTextRec in the system unit for more information.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ] }
141,315
Is there a way to check to see if a date/time is valid you would think these would be easy to check: $date = '0000-00-00';$time = '00:00:00';$dateTime = $date . ' ' . $time;if(strtotime($dateTime)) { // why is this valid?} what really gets me is this: echo date('Y-m-d', strtotime($date)); results in: "1999-11-30", huh? i went from 0000-00-00 to 1999-11-30 ??? I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this? Edit:People are asking what i'm running:Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux
From php.net <?phpfunction isValidDateTime($dateTime){ if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) { if (checkdate($matches[2], $matches[3], $matches[1])) { return true; } } return false;}?>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ] }
141,337
Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects. Question: Should I ensure my objects have copy constructors and store copies of objects within my STL containers, or is it generally better to manage the life & scope myself and just store the pointers to those objects in my STL containers? I realize this is somewhat short on details, but I'm looking for the "theoretical" better answer if it exists, since I know both of these solutions are possible. Two very obvious disadvantage to playing with pointers:1) I must manage allocation/deallocation of these objects myself in a scope beyond the STL.2) I cannot create a temp object on the stack and add it to my containers. Is there anything else I'm missing?
Since people are chiming in on the efficency of using pointers. If you're considering using a std::vector and if updates are few and you often iterate over your collection and it's a non polymorphic type storing object "copies" will be more efficent since you'll get better locality of reference. Otoh, if updates are common storing pointers will save the copy/relocation costs.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13022/" ] }
141,344
How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one. Is there a better way of doing this? Something like FIND or FINDSTR operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there. FOR /F "delims=;" %%P IN ("%PATH%") DO ( @ECHO %%~P)
First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with. For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable. From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because: The trailing \ is optional in a path Most paths work equally well both with and without the trailing \ . The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing \ . This is probably the most common practical issue when searching a PATH for a match. There is one exception: The relative path C: (meaning the current working directory of drive C) is very different than C:\ (meaning the root directory of drive C) Some paths have alternate short names Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings. Windows accepts both / and \ as folder separators within a path. This is not seen very often, but a path can be specified using / instead of \ and it will function just fine within PATH (as well as in many other Windows contexts) Windows treats consecutive folder separators as one logical separator. C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append \ to a path without bothering to check if the trailing \ already exists. But this obviously can cause problems if trying to perform an exact string match. Exceptions: Not only is C: , different than C:\ , but C:\ (a valid path), is different than C:\\ (an invalid path). Windows trims trailing dots and spaces from file and directory names. "C:\test. " is equivalent to "C:\test" . The current .\ and parent ..\ folder specifiers may appear within a path Unlikely to be seen in real life, but something like C:\.\parent\child\..\.\child\ is equivalent to C:\parent\child A path can optionally be enclosed within double quotes. A path is often enclosed in quotes to protect against special characters like <space> , ; ^ & = . Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a ; , but the quotes may be present never-the-less. A path may be fully qualified or relative. A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths: D: is relative to the current working directory of volume D: \myPath is relative to the current working volume (could be C:, D: etc.) myPath is relative to the current working volume and directory It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain .\ . But Windows does search the current directory by default, so relative paths are rare in a Windows PATH. So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The ~s modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 - 6, and partially addresses issue 7. The ~s modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the ~s modifier will not append the \ to the path, nor will it convert the path into a valid 8.3 format. The problem with ~s is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with <letter>:<separator> but not <letter>:<separator><separator> , where <separator> is either \ or / . UNC paths are always fully qualified and must start with \\ . When comparing fully qualified paths we use the ~s modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH. There are some additional issues that complicate this problem: 9) Normal expansion is not reliable when dealing with a PATH that contains special characters. Special characters do not need to be quoted within PATH, but they could be. So a PATH like C:\THIS & THAT;"C:\& THE OTHER THING" is perfectly valid, but it cannot be expanded safely using simple expansion because both "%PATH%" and %PATH% will fail. 10) The path delimiter is also valid within a path name A ; is used to delimit paths within PATH, but ; can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue. jeb solved both issues 9 and 10 at 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell So we can combine the ~s modifier and path classification techniques along with my variation of jeb's PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments. @echo off:inPath pathVar:::: Tests if the path stored within variable pathVar exists within PATH.:::: The result is returned as the ERRORLEVEL::: 0 if the pathVar path is found in PATH.:: 1 if the pathVar path is not found in PATH.:: 2 if pathVar is missing or undefined or if PATH is undefined.:::: If the pathVar path is fully qualified, then it is logically compared:: to each fully qualified path within PATH. The path strings don't have:: to match exactly, they just need to be logically equivalent.:::: If the pathVar path is relative, then it is strictly compared to each:: relative path within PATH. Case differences and double quotes are:: ignored, but otherwise the path strings must match exactly.::::------------------------------------------------------------------------:::: Error checkingif "%~1"=="" exit /b 2if not defined %~1 exit /b 2if not defined path exit /b 2:::: Prepare to safely parse PATH into individual pathssetlocal DisableDelayedExpansionset "var=%path:"=""%"set "var=%var:^=^^%"set "var=%var:&=^&%"set "var=%var:|=^|%"set "var=%var:<=^<%"set "var=%var:>=^>%"set "var=%var:;=^;^;%"set var=%var:""="%set "var=%var:"=""Q%"set "var=%var:;;="S"S%"set "var=%var:^;^;=;%"set "var=%var:""="%"setlocal EnableDelayedExpansionset "var=!var:"Q=!"set "var=!var:"S"S=";"!":::: Remove quotes from pathVar and abort if it becomes emptyset "new=!%~1:"=!"if not defined new exit /b 2:::: Determine if pathVar is fully qualifiedecho("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && set "abs=1" || set "abs=0":::: For each path in PATH, check if path is fully qualified and then do:: proper comparison with pathVar.:: Exit with ERRORLEVEL 0 if a match is found.:: Delayed expansion must be disabled when expanding FOR variables:: just in case the value contains !for %%A in ("!new!\") do for %%B in ("!var!") do ( if "!!"=="" endlocal for %%C in ("%%~B\") do ( echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^ || (if %abs%==0 if /i "%%~A"=="%%~C" exit /b 0) )):: No match was found so exit with ERRORLEVEL 1exit /b 1 The function can be used like so (assuming the batch file is named inPath.bat): set test=c:\mypathcall inPath test && (echo found) || (echo not found) Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn't there. This is normally done simply by using something like path %path%;%newPath% . But Issue 9 demonstrates how this is not reliable. Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped ! will corrupt the value if delayed expansion is enabled. These problems are resolved using an amazing safe return technique that jeb invented here: http://www.dostips.com/forum/viewtopic.php?p=6930#p6930 @echo off:addPath pathVar /B:::: Safely appends the path contained within variable pathVar to the end:: of PATH if and only if the path does not already exist within PATH.:::: If the case insensitive /B option is specified, then the path is:: inserted into the front (Beginning) of PATH instead.:::: If the pathVar path is fully qualified, then it is logically compared:: to each fully qualified path within PATH. The path strings are:: considered a match if they are logically equivalent.:::: If the pathVar path is relative, then it is strictly compared to each:: relative path within PATH. Case differences and double quotes are:: ignored, but otherwise the path strings must match exactly.:::: Before appending the pathVar path, all double quotes are stripped, and:: then the path is enclosed in double quotes if and only if the path:: contains at least one semicolon.:::: addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined:: or if PATH is undefined.::::------------------------------------------------------------------------:::: Error checkingif "%~1"=="" exit /b 2if not defined %~1 exit /b 2if not defined path exit /b 2:::: Determine if function was called while delayed expansion was enabledsetlocalset "NotDelayed=!":::: Prepare to safely parse PATH into individual pathssetlocal DisableDelayedExpansionset "var=%path:"=""%"set "var=%var:^=^^%"set "var=%var:&=^&%"set "var=%var:|=^|%"set "var=%var:<=^<%"set "var=%var:>=^>%"set "var=%var:;=^;^;%"set var=%var:""="%set "var=%var:"=""Q%"set "var=%var:;;="S"S%"set "var=%var:^;^;=;%"set "var=%var:""="%"setlocal EnableDelayedExpansionset "var=!var:"Q=!"set "var=!var:"S"S=";"!":::: Remove quotes from pathVar and abort if it becomes emptyset "new=!%~1:"^=!"if not defined new exit /b 2:::: Determine if pathVar is fully qualifiedecho("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && set "abs=1" || set "abs=0":::: For each path in PATH, check if path is fully qualified and then:: do proper comparison with pathVar. Exit if a match is found.:: Delayed expansion must be disabled when expanding FOR variables:: just in case the value contains !for %%A in ("!new!\") do for %%B in ("!var!") do ( if "!!"=="" setlocal disableDelayedExpansion for %%C in ("%%~B\") do ( echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^ || (if %abs%==0 if /i %%A==%%C exit /b 0) )):::: Build the modified PATH, enclosing the added path in quotes:: only if it contains ;setlocal enableDelayedExpansionif "!new:;=!" neq "!new!" set new="!new!"if /i "%~2"=="/B" (set "rtn=!new!;!path!") else set "rtn=!path!;!new!":::: rtn now contains the modified PATH. We need to safely pass the:: value accross the ENDLOCAL barrier:::: Make rtn safe for assignment using normal expansion by replacing:: % and " with not yet defined FOR variablesset "rtn=!rtn:%%=%%A!"set "rtn=!rtn:"=%%B!":::: Escape ^ and ! if function was called while delayed expansion was enabled.:: The trailing ! in the second assignment is critical and must not be removed.if not defined NotDelayed set "rtn=!rtn:^=^^^^!"if not defined NotDelayed set "rtn=%rtn:!=^^^!%" !:::: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to:: restore the % and " characters. Again the trailing ! is critical.for /f "usebackq tokens=1,2" %%A in ('%%^ ^"') do ( endlocal & endlocal & endlocal & endlocal & endlocal set "path=%rtn%" !)exit /b 0
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ] }
141,348
I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript Date() object so I can easily perform comparisons and other things on it. I tried the parse() method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same Date() object: 1:00 pm 1:00 p.m. 1:00 p 1:00pm 1:00p.m. 1:00p 1 pm 1 p.m. 1 p 1pm 1p.m. 1p 13:00 13 I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my Date() object. What is the best way to do this?
A quick solution which works on the input that you've specified: function parseTime( t ) { var d = new Date(); var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ ); d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) ); d.setMinutes( parseInt( time[2]) || 0 ); return d;}var tests = [ '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm', '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p', '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];for ( var i = 0; i < tests.length; i++ ) { console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );} It should work for a few other varieties as well (even if a.m. is used, it'll still work - for example). Obviously this is pretty crude but it's also pretty lightweight (much cheaper to use that than a full library, for example). Warning: The code doe not work with 12:00 AM, etc.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18986/" ] }
141,351
My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a Python memory profiler (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server. What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. How do I get a core dump of a python process like this? Once I have one, how do I do something useful with it?
I will expand on Brett's answer from my recent experience. Dozer package is well maintained , and despite advancements, like addition of tracemalloc to stdlib in Python 3.4, its gc.get_objects counting chart is my go-to tool to tackle memory leaks. Below I use dozer > 0.7 which has not been released at the time of writing (well, because I contributed a couple of fixes there recently). Example Let's look at a non-trivial memory leak. I'll use Celery 4.4 here and will eventually uncover a feature which causes the leak (and because it's a bug/feature kind of thing, it can be called mere misconfiguration, cause by ignorance). So there's a Python 3.6 venv where I pip install celery < 4.5 . And have the following module. demo.py import timeimport celery redis_dsn = 'redis://localhost'app = celery.Celery('demo', broker=redis_dsn, backend=redis_dsn)@app.taskdef subtask(): [email protected] task(): for i in range(10_000): subtask.delay() time.sleep(0.01)if __name__ == '__main__': task.delay().get() Basically a task which schedules a bunch of subtasks. What can go wrong? I'll use procpath to analyse Celery node memory consumption. pip install procpath . I have 4 terminals: procpath record -d celery.sqlite -i1 "$..children[?('celery' in @.cmdline)]" to record the Celery node's process tree stats docker run --rm -it -p 6379:6379 redis to run Redis which will serve as Celery broker and result backend celery -A demo worker --concurrency 2 to run the node with 2 workers python demo.py to finally run the example (4) will finish under 2 minutes. Then I use sqliteviz ( pre-built version ) to visualise what procpath has recorder. I drop the celery.sqlite there and use this query: SELECT datetime(ts, 'unixepoch', 'localtime') ts, stat_pid, stat_rss / 256.0 rssFROM record And in sqliteviz I create a line chart trace with X=ts , Y=rss , and add split transform By=stat_pid . The result chart is: This shape is likely pretty familiar to anyone who fought with memory leaks. Finding leaking objects Now it's time for dozer . I'll show non-instrumented case (and you can instrument your code in similar way if you can). To inject Dozer server into target process I'll use Pyrasite . There are two things to know about it: To run it, ptrace has to be configured as "classic ptrace permissions": echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope , which is may be a security risk There are non-zero chances that your target Python process will crash With that caveat I: pip install https://github.com/mgedmin/dozer/archive/3ca74bd8.zip (that's to-be 0.8 I mentioned above) pip install pillow (which dozer uses for charting) pip install pyrasite After that I can get Python shell in the target process: pyrasite-shell 26572 And inject the following, which will run Dozer's WSGI application using stdlib's wsgiref 's server. import threadingimport wsgiref.simple_serverimport dozerdef run_dozer(): app = dozer.Dozer(app=None, path='/') with wsgiref.simple_server.make_server('', 8000, app) as httpd: print('Serving Dozer on port 8000...') httpd.serve_forever()threading.Thread(target=run_dozer, daemon=True).start() Opening http://localhost:8000 in a browser there should see something like: After that I run python demo.py from (4) again and wait for it to finish. Then in Dozer I set "Floor" to 5000, and here's what I see: Two types related to Celery grow as the subtask are scheduled: celery.result.AsyncResult vine.promises.promise weakref.WeakMethod has the same shape and numbers and must be caused by the same thing. Finding root cause At this point from the leaking types and the trends it may be already clear what's going on in your case. If it's not, Dozer has "TRACE" link per type, which allows tracing (e.g. seeing object's attributes) chosen object's referrers ( gc.get_referrers ) and referents ( gc.get_referents ), and continue the process again traversing the graph. But a picture says a thousand words, right? So I'll show how to use objgraph to render chosen object's dependency graph. pip install objgraph apt-get install graphviz Then: I run python demo.py from (4) again in Dozer I set floor=0 , filter=AsyncResult and click "TRACE" which should yield Then in Pyrasite shell run: objgraph.show_backrefs([objgraph.at(140254427663376)], filename='backref.png') The PNG file should contain: Basically there's some Context object containing a list called _children that in turn is containing many instances of celery.result.AsyncResult , which leak. Changing Filter=celery.*context in Dozer here's what I see: So the culprit is celery.app.task.Context . Searching that type would certainly lead you to Celery task page . Quickly searching for "children" there, here's what it says: trail = True If enabled the request will keep track of subtasks started by this task, and this information will be sent with the result ( result.children ). Disabling the trail by setting trail=False like: @app.task(trail=False)def task(): for i in range(10_000): subtask.delay() time.sleep(0.01) Then restarting the Celery node from (3) and python demo.py from (4) yet again, shows this memory consumption. Problem solved!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9585/" ] }
141,370
What is the best way to specify a property name when using INotifyPropertyChanged? Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead.
Don't forget one thing : PropertyChanged event is mainly consumed by components that will use reflection to get the value of the named property. The most obvious example is databinding. When you fire PropertyChanged event, passing the name of the property as a parameter, you should know that the subscriber of this event is likely to use reflection by calling, for instance, GetProperty (at least the first time if it uses a cache of PropertyInfo ), then GetValue . This last call is a dynamic invocation (MethodInfo.Invoke) of the property getter method, which costs more than the GetProperty which only queries meta data. (Note that data binding relies on the whole TypeDescriptor thing -- but the default implementation uses reflection.) So, of course using hard code property names when firing PropertyChanged is more efficient than using reflection for dynamically getting the name of the property, but IMHO, it is important to balance your thoughts. In some cases, the performance overhead is not that critical, and you could benefit from some kind on strongly typed event firing mechanism. Here is what I use sometimes in C# 3.0, when performances would not be a concern : public class Person : INotifyPropertyChanged{ private string name; public string Name { get { return this.name; } set { this.name = value; FirePropertyChanged(p => p.Name); } } private void FirePropertyChanged<TValue>(Expression<Func<Person, TValue>> propertySelector) { if (PropertyChanged == null) return; var memberExpression = propertySelector.Body as MemberExpression; if (memberExpression == null) return; PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name)); } public event PropertyChangedEventHandler PropertyChanged;} Notice the use of the expression tree to get the name of the property, and the use of the lambda expression as an Expression : FirePropertyChanged(p => p.Name);
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22813/" ] }
141,435
Can anyone explain what advantages there are to using a tool like MSBuild (or NAnt) to build a collection of projects versus running DevEnv.exe from the command-line? A colleague I had worked with in the past had explained that (at least with older versions of Visual Studio) using DevEnv.exe was much slower than the other techniques, but I haven't read any evidence of that or if that is now a moot point now that starting with 2005, Visual Studio uses MSBuild under the hood. I know one advantage of using MSBuild allows you to build your projects without requiring Visual Studio to be installed on the build machines, but I wasn't sure if there were others.
One reason is because there's much more to building a product than just compiling it. Tasks such as creating installs, updating version numbers, creating escrows, distributing the final packages, etc. can be much easier because of what these tools (and their extensions) provide. While you could do all this with regular scripts, using NAnt or MSBuild give you a solid framework for doing all this. There's a lot of community support for both, including additional tasks that can be downloaded (such as the MSBuild Community Tasks Project ). Plus, there's support for them in numerous third party and open source products. If you're just interested in compiling (and not the entire build process), you may find one time saving benefit of MSBuild is the support for building with multiple processors .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16563/" ] }
141,449
How do I create a file-like object (same duck type as File) with the contents of a string?
For Python 2.x, use the StringIO module. For example: >>> from cStringIO import StringIO>>> f = StringIO('foo')>>> f.read()'foo' I use cStringIO (which is faster), but note that it doesn't accept Unicode strings that cannot be encoded as plain ASCII strings . (You can switch to StringIO by changing "from cStringIO" to "from StringIO".) For Python 3.x, use the io module. f = io.StringIO('foo')
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/141449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ] }
141,467
I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas? Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.
Here's an extension that might help. It will traverse all nodes in your hierarchy of objects and pick out the ones that match a criteria. It assumes that each object in your hierarchy has a collection property that holds its child objects. Here's the extension: /// Traverses an object hierarchy and return a flattened list of elements/// based on a predicate./// /// TSource: The type of object in your collection.</typeparam>/// source: The collection of your topmost TSource objects.</param>/// selectorFunction: A predicate for choosing the objects you want./// getChildrenFunction: A function that fetches the child collection from an object./// returns: A flattened list of objects which meet the criteria in selectorFunction.public static IEnumerable<TSource> Map<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> selectorFunction, Func<TSource, IEnumerable<TSource>> getChildrenFunction){ // Add what we have to the stack var flattenedList = source.Where(selectorFunction); // Go through the input enumerable looking for children, // and add those if we have them foreach (TSource element in source) { flattenedList = flattenedList.Concat( getChildrenFunction(element).Map(selectorFunction, getChildrenFunction) ); } return flattenedList;} Examples (Unit Tests): First we need an object and a nested object hierarchy. A simple node class class Node{ public int NodeId { get; set; } public int LevelId { get; set; } public IEnumerable<Node> Children { get; set; } public override string ToString() { return String.Format("Node {0}, Level {1}", this.NodeId, this.LevelId); }} And a method to get a 3-level deep hierarchy of nodes private IEnumerable<Node> GetNodes(){ // Create a 3-level deep hierarchy of nodes Node[] nodes = new Node[] { new Node { NodeId = 1, LevelId = 1, Children = new Node[] { new Node { NodeId = 2, LevelId = 2, Children = new Node[] {} }, new Node { NodeId = 3, LevelId = 2, Children = new Node[] { new Node { NodeId = 4, LevelId = 3, Children = new Node[] {} }, new Node { NodeId = 5, LevelId = 3, Children = new Node[] {} } } } } }, new Node { NodeId = 6, LevelId = 1, Children = new Node[] {} } }; return nodes;} First Test: flatten the hierarchy, no filtering [Test]public void Flatten_Nested_Heirachy(){ IEnumerable<Node> nodes = GetNodes(); var flattenedNodes = nodes.Map( p => true, (Node n) => { return n.Children; } ); foreach (Node flatNode in flattenedNodes) { Console.WriteLine(flatNode.ToString()); } // Make sure we only end up with 6 nodes Assert.AreEqual(6, flattenedNodes.Count());} This will show: Node 1, Level 1Node 6, Level 1Node 2, Level 2Node 3, Level 2Node 4, Level 3Node 5, Level 3 Second Test: Get a list of nodes that have an even-numbered NodeId [Test]public void Only_Return_Nodes_With_Even_Numbered_Node_IDs(){ IEnumerable<Node> nodes = GetNodes(); var flattenedNodes = nodes.Map( p => (p.NodeId % 2) == 0, (Node n) => { return n.Children; } ); foreach (Node flatNode in flattenedNodes) { Console.WriteLine(flatNode.ToString()); } // Make sure we only end up with 3 nodes Assert.AreEqual(3, flattenedNodes.Count());} This will show: Node 6, Level 1Node 2, Level 2Node 4, Level 3
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18049/" ] }
141,487
class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.
for Admin in Django 1.0 and up, you'd need to use prepopulated_fields = {'slug': ('title',), } in your admin.py Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated. Outside of admin, you can use the slugify function in your views. In templates, you can use the |slugify filter. There is also this package which will take care of this automatically: https://pypi.python.org/pypi/django-autoslug
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ] }
141,498
Java has some very good open source static analysis tools such as FindBugs , Checkstyle and PMD . Those tools are easy to use, very helpful, runs on multiple operating systems and free . Commercial C++ static analysis products are available. Although having such products are great, the cost is just way too much for students and it is usually rather hard to get trial version. The alternative is to find open source C++ static analysis tools that will run on multiple platforms (Windows and Unix). By using an open source tool, it could be modified to fit certain needs. Finding the tools has not been easy task. Below is a short list of C++ static analysis tools that were found or suggested by others. C++ Check http://sf.net/projects/cppcheck/ Oink http://danielwilkerson.com/oink/index.html C and C++ Code Counter http://sourceforge.net/projects/cccc/ Splint (from answers) Mozilla's Pork (from answers) (This is now part of Oink) Mozilla's Dehydra (from answers) Use option -Weffc++ for GNU g++ (from answers) What are some other portable open source C++ static analysis tools that anyone knows of and can be recommended? Some related links. http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis http://www.chris-lott.org/resources/cmetrics/ A free tool to check C/C++ source code against a set of coding standards? http://spinroot.com/static/ Choosing a static code analysis tool
Concerning the GNU compiler, gcc has already a builtin option that enables additional warning to those of -Wall. The option is -Weffc++ and it's about the violations of some guidelines of Scott Meyers published in his books " Effective and More Effective C++ ". In particular the option detects the following items: Define a copy constructor and an assignment operator for classes with dynamically allocated memory. Prefer initialization to assignment in constructors. Make destructors virtual in base classes. Have "operator=" return a reference to *this. Don’t try to return a reference when you must return an object. Distinguish between prefix and postfix forms of increment and decrement operators. Never overload "&&", "||", or ",".
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22807/" ] }
141,500
I work on a small web team where I am the only .NET developer currently using Visual Studio 2008 Professional to build and maintain a few web applications. I am about to start training another member of our team so we purchased him a copy of Visual Studio 2008 Professional. I've looked into Visual Source Safe, but I'm dubious. I don't like that is file system based. Ideally, the system would work with SQL Server 2005 and plug into Visual Studio. Windows based solutions are the best because of the IT environment of the organization I work for. What are my options for a source control system? (Forgive me if the answer exists in another thread.)
Subversion has good integration with Visual Studio 2008 through VisualSVN and Ankh . SourceSafe is dangerous. You're right that a filesharing-based SCM is a bad idea, and Microsoft themselves have downplayed it and replaced it with a new SCM that comes with the Team edition of Visual Studio.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12252/" ] }
141,525
I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)... At a core level, what does bit-shifting ( << , >> , >>> ) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.
The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators. The Operators >> is the arithmetic (or signed) right shift operator. >>> is the logical (or unsigned) right shift operator. << is the left shift operator, and meets the needs of both logical and arithmetic shifts. All of these operators can be applied to integer values ( int , long , possibly short and byte or char ). In some languages, applying the shift operators to any datatype smaller than int automatically resizes the operand to be an int . Note that <<< is not an operator, because it would be redundant. Also note that C and C++ do not distinguish between the right shift operators . They provide only the >> operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators. (In all mainstream C and C++ implementations including GCC and Clang/LLVM, >> on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not undefined , though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers is undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.) Left shift (<<) Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit int would be: 00000000 00000000 00000000 00000110 Shifting this bit pattern to the left one position ( 6 << 1 ) would result in the number 12: 00000000 00000000 00000000 00001100 As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So 6 << 1 is equivalent to 6 * 2 , and 6 << 3 is equivalent to 6 * 8 . A good optimizing compiler will replace multiplications with shifts when possible. Non-circular shifting Please note that these are not circular shifts. Shifting this value to the left by one position ( 3,758,096,384 << 1 ): 11100000 00000000 00000000 00000000 results in 3,221,225,472: 11000000 00000000 00000000 00000000 The digit that gets shifted "off the end" is lost. It does not wrap around. Logical right shift (>>>) A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12: 00000000 00000000 00000000 00001100 to the right by one position ( 12 >>> 1 ) will get back our original 6: 00000000 00000000 00000000 00000110 So we see that shifting to the right is equivalent to division by powers of 2. Lost bits are gone However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern: 00111000 00000000 00000000 00000110 to the left 4 positions ( 939,524,102 << 4 ), we get 2,147,483,744: 10000000 00000000 00000000 01100000 and then shifting back ( (939,524,102 << 4) >>> 4 ) we get 134,217,734: 00001000 00000000 00000000 00000110 We cannot get back our original value once we have lost bits. Arithmetic right shift (>>) The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the sign bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving. For example, if we interpret this bit pattern as a negative number: 10000000 00000000 00000000 01100000 we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us: 11111000 00000000 00000000 00000110 or the number -134,217,722. So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/141525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ] }
141,545
Let's say I have a class that has a member called data which is a list. I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list. What's your technique for doing this? Do you just check the type by looking at __class__ ? Is there some trick I might be missing? I'm used to C++ where overloading by argument type is easy.
A much neater way to get 'alternate constructors' is to use classmethods. For instance: >>> class MyData:... def __init__(self, data):... "Initialize MyData from a sequence"... self.data = data... ... @classmethod... def fromfilename(cls, filename):... "Initialize MyData from a file"... data = open(filename).readlines()... return cls(data)... ... @classmethod... def fromdict(cls, datadict):... "Initialize MyData from a dict's items"... return cls(datadict.items())... >>> MyData([1, 2, 3]).data[1, 2, 3]>>> MyData.fromfilename("/tmp/foobar").data['foo\n', 'bar\n', 'baz\n']>>> MyData.fromdict({"spam": "ham"}).data[('spam', 'ham')] The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with isinstance(x, basestring) is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/141545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179/" ] }
141,556
I am about to start on a journey writing a windows forms application that will open a txt file that is pipe delimited and about 230 mb in size. This app will then insert this data into a sql server 2005 database (obviously this needs to happen swiftly). I am using c# 3.0 and .net 3.5 for this project. I am not asking for the app, just some communal advise here and potential pitfalls advise. From the site I have gathered that SQL bulk copy is a prerequisite, is there anything I should think about (I think that just opening the txt file with a forms app will be a large endeavor; maybe break it into blob data?). Thank you, and I will edit the question for clarity if anyone needs it.
Do you have to write a winforms app? It might be much easier and faster to use SSIS. There are some built-in tasks available especially Bulk Insert task . Also, worth checking Flat File Bulk Import methods speed comparison in SQL Server 2005. Update: If you are new to SSIS, check out some of these sites to get you on fast track. 1) SSIS Control Flow Basics 2) Getting Started with SQL Server Integration Services This is another How to: on importing Excel file into SQL 2005 .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ] }
141,560
I have a loop that looks something like this: for (int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum;} This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return null if there is an error, so I put the loop inside a try...catch block, like this: try { for (int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; }} catch (NumberFormatException ex) { return null;} But then I also thought of putting the try...catch block inside the loop, like this: for (int i = 0; i < max; i++) { String myString = ...; try { float myNum = Float.parseFloat(myString); } catch (NumberFormatException ex) { return null; } myFloats[i] = myNum;} Is there any reason, performance or otherwise, to prefer one over the other? Edit: The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?
PERFORMANCE: There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table. Here's a reference: http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html The table is described about half-way down.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13531/" ] }
141,562
I can select all the distinct values in a column in the following ways: SELECT DISTINCT column_name FROM table_name; SELECT column_name FROM table_name GROUP BY column_name; But how do I get the row count from that query? Is a subquery required?
You can use the DISTINCT keyword within the COUNT aggregate function: SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name This will count only the distinct values for that column.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/141562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3757/" ] }
141,599
What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'. Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp? Example: svn -v log -d 2008-9-23:2008-9:24 > report.txt
Very first hit by google for "svn log date range": http://svn.haxx.se/users/archive-2006-08/0737.shtml So svn log <url> -r {2008-09-19}:{2008-09-26} will get all changes for the past week, including today. And if you want to generate reports for a repo, there's a solution: Statsvn . HTH
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ] }
141,612
I'm working on database designs for a project management system as personal project and I've hit a snag. I want to implement a ticket system and I want the tickets to look like the tickets in Trac . What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing) Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again. Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.
I have implemented pure record change data using a "thin" design: RecordID Table Column OldValue NewValue-------- ----- ------ -------- -------- You may not want to use "Table" and "Column", but rather "Object" and "Property", and so forth, depending on your design. This has the advantage of flexibility and simplicity, at the cost of query speed -- clustered indexes on the "Table" and "Column" columns can speed up queries and filters. But if you are going to be viewing the change log online frequently at a Table or object level, you may want to design something flatter. EDIT : several people have rightly pointed out that with this solution you could not pull together a change set. I forgot this in the table above -- the implementation I worked with also had a "Transaction" table with a datetime, user and other info, and a "TransactionID" column, so the design would look like this: CHANGE LOG TABLE:RecordID Table Column OldValue NewValue TransactionID-------- ----- ------ -------- -------- -------------TRANSACTION LOG TABLE:TransactionID UserID TransactionDate------------- ------ ---------------
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ] }
141,641
I've been working with Perl long enough that many of its idiosyncracies have become second nature to me. When new programmers join our group, they frequently have little to no experience with Perl, and it's usually my task to train them (to the extent necessary). I'd like to know what to focus on when training a programmer who is new to Perl but has experience with other languages (this question is meant to be language-agnostic, but most developers I've worked with have come from Java). A few things occur to me: The proper use of sigils Referencing/Dereferencing Use of list functions like map , grep , sort Is there anything in particular that you've found it useful to focus on when helping a programmer to transition to Perl? Do you stress the similarities or the differences, or both in equal measure?
Check out the tables of contents for my books. Both Learning Perl and Intermediate Perl are designed to teach programmers the Perl language. We cover the 80% of Perl that most people use all of the time and developed that from years and years of teaching people Perl. Each book is designed as a tutorial, and there are exercises at the end of each chapter. I've also written the Learning Perl Student Workbook to provide additional exercises. Programming Perl is a good reference, too. There are actually very few rules that you need to know to "get" Perl, and most people don't get these rules right just by looking at code. Some things to teach new Perlers who are coming from another language: strict and warnings Scalar versus list context dynamic versus lexical scope The sigil is not the variable type List creation and manipulation (map, grep, sort) How to use CPAN effectively Closures and subroutines as data Recursion in Perl sucks Good luck :)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ] }
141,642
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. Some limitations are mentioned in the Closures in Python (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more. Seeing a code example for a concrete limitation would be great. Related questions : Can you explain closures (as they relate to Python)? What is a ‘Closure’? How does a javascript closure work ?
The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only: >>> def outer(x): ... def inner_reads():... # Will return outer's 'x'.... return x... def inner_writes(y):... # Will assign to a local 'x', not the outer 'x'... x = y... def inner_error(y):... # Will produce an error: 'x' is local because of the assignment,... # but we use it before it is assigned to.... tmp = x... x = y... return tmp... return inner_reads, inner_writes, inner_error... >>> inner_reads, inner_writes, inner_error = outer(5)>>> inner_reads()5>>> inner_writes(10)>>> inner_reads()5>>> inner_error(10)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 11, in inner_errorUnboundLocalError: local variable 'x' referenced before assignment A name that gets assigned to in a local scope (a function) is always local, unless declared otherwise. While there is the 'global' declaration to declare a variable global even when it is assigned to, there is no such declaration for enclosed variables -- yet. In Python 3.0, there is (will be) the 'nonlocal' declaration that does just that. You can work around this limitation in the mean time by using a mutable container type: >>> def outer(x):... x = [x]... def inner_reads():... # Will return outer's x's first (and only) element.... return x[0]... def inner_writes(y):... # Will look up outer's x, then mutate it. ... x[0] = y... def inner_error(y):... # Will now work, because 'x' is not assigned to, just referenced.... tmp = x[0]... x[0] = y... return tmp... return inner_reads, inner_writes, inner_error... >>> inner_reads, inner_writes, inner_error = outer(5)>>> inner_reads()5>>> inner_writes(10)>>> inner_reads()10>>> inner_error(15)10>>> inner_reads()15
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ] }
141,669
I am considering building an application that is a blend of a dynamic language (python or ruby) and compiled language and need some help getting convincing myself that this is a good idea. My thought are that I can use a dynamic language to get a lot of code written quickly, and then dropping down to a compiled language like c/c++ to implement performance critical code. I can see a lot of benefits of this approach: Increased Productivity by primarily coding in the dynamic language Availability of libraries from both languages But there are also some downsides: Maintaining a bridge between the two languages Dependency on two languages and language/library bugs instead of one What are the other pros/cons of this approach? Does anybody know about any resources and/or best practices around this?
I think your approach is very sensible. The way to address the downsides is to find out ahead of time how easy it is to interface the dynamic language with C or C++ before deciding whether or not to use it for your project. Also, you need to think about whether or not you want your application to be cross-platform. A dynamic language is likely to be much less platform dependent, than a compiled one. That may be a factor in deciding which parts of the app should be done in C or C++.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813/" ] }
141,682
I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION_SCHEMA. I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere. Are they not there? (I'm using MS SQL Server 2000). EDIT: I'm looking to get by the name of the constraint.
As I understand it, default value constraints aren't part of the ISO standard, so they don't appear in INFORMATION_SCHEMA. INFORMATION_SCHEMA seems like the best choice for this kind of task because it is cross-platform, but if the information isn't available one should use the object catalog views (sys.*) instead of system table views, which are deprecated in SQL Server 2005 and later. Below is pretty much the same as @user186476's answer. It returns the name of the default value constraint for a given column. (For non-SQL Server users, you need the name of the default in order to drop it, and if you don't name the default constraint yourself, SQL Server creates some crazy name like "DF_TableN_Colum_95AFE4B5". To make it easier to change your schema in the future, always explicitly name your constraints!) -- returns name of a column's default value constraint SELECT default_constraints.nameFROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_idWHERE schemas.name = 'dbo' AND tables.name = 'tablename' AND all_columns.name = 'columnname'
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/141682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9052/" ] }
141,707
I have a RHEL box that I need to put under a moderate and variable amount of CPU load (50%-75%). What is the best way to go about this? Is there a program that can do this that I am not aware of? I am happy to write some C code to make this happen, I just don't know what system calls will help.
This is exactly what you need (internet archive link): https://web.archive.org/web/20120512025754/http://weather.ou.edu/~apw/projects/stress/stress-1.0.4.tar.gz From the homepage:"stress is a simple workload generator for POSIX systems. It imposes a configurable amount of CPU, memory, I/O, and disk stress on the system. It is written in C, and is free software licensed under the GPL."
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ] }
141,718
I have a multi-user ASP.NET app running against SQL Server and want to have StoredProcA create a #temptable temp table - not a table variable - to insert some data, then branch to StoredProcB, StoredProcC, and StoredProcD to manipulate the data in #temptable per business rules. The web app uses connection pooling when talking to SQL. Will I get a new #temptable scratch area for each call of StoredProcA? Or will the connection pooling share the #temptable between users?
Connection pooling (with any modern version of SQL Server) will call sp_reset_connection when reusing a connection. This stored proc, among other things, drops any temporary tables that the connection owns.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/141718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260/" ] }
141,720
How do you compare two instances of structs for equality in standard C?
C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/141720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ] }
141,734
If I do not specify the following in my web.xml file: <session-config> <session-timeout>10</session-timeout></session-config> What will be my default session timeout? (I am running Tomcat 6.0)
If you're using Tomcat, it's 30 minutes. You can read more about it here .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ] }
141,752
My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values are different about 1/2 of the cases. Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug. For example: LEFTPOS and SPACING are defined floating point values.float def_x;int xpos;def_x = LEFTPOS + (xpos * (SPACING / 2)); The issue is in regards to the X360 compiler.
Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ] }
141,779
The problem/comic in question: http://xkcd.com/287/ I'm not sure this is the best way to do it, but here's what I've come up with so far. I'm using CFML, but it should be readable by anyone. <cffunction name="testCombo" returntype="boolean"> <cfargument name="currentCombo" type="string" required="true" /> <cfargument name="currentTotal" type="numeric" required="true" /> <cfargument name="apps" type="array" required="true" /> <cfset var a = 0 /> <cfset var found = false /> <cfloop from="1" to="#arrayLen(arguments.apps)#" index="a"> <cfset arguments.currentCombo = listAppend(arguments.currentCombo, arguments.apps[a].name) /> <cfset arguments.currentTotal = arguments.currentTotal + arguments.apps[a].cost /> <cfif arguments.currentTotal eq 15.05> <!--- print current combo ---> <cfoutput><strong>#arguments.currentCombo# = 15.05</strong></cfoutput><br /> <cfreturn true /> <cfelseif arguments.currentTotal gt 15.05> <cfoutput>#arguments.currentCombo# > 15.05 (aborting)</cfoutput><br /> <cfreturn false /> <cfelse> <!--- less than 15.05 ---> <cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br /> <cfset found = testCombo(arguments.currentCombo, arguments.currentTotal, arguments.apps) /> </cfif> </cfloop></cffunction><cfset mf = {name="Mixed Fruit", cost=2.15} /><cfset ff = {name="French Fries", cost=2.75} /><cfset ss = {name="side salad", cost=3.35} /><cfset hw = {name="hot wings", cost=3.55} /><cfset ms = {name="moz sticks", cost=4.20} /><cfset sp = {name="sampler plate", cost=5.80} /><cfset apps = [ mf, ff, ss, hw, ms, sp ] /><cfloop from="1" to="6" index="b"> <cfoutput>#testCombo(apps[b].name, apps[b].cost, apps)#</cfoutput></cfloop> The above code tells me that the only combination that adds up to $15.05 is 7 orders of Mixed Fruit, and it takes 232 executions of my testCombo function to complete. Is there a better algorithm to come to the correct solution? Did I come to the correct solution?
The point about an NP-complete problem is not that it's tricky on a small data set, but that the amount of work to solve it grows at a rate greater than polynomial, i.e. there is no O(n^x) algorithm. If the time complexity is O(n!), as in (I believe) the two problems mentioned above, that is in NP.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ] }
141,820
I know a Haskell module name, but I can't figure out in what package it is defined. This is bad because I can't compile without a package exposing this module. Specificaly it is Text.Regex that I can't locate, but I would like to know how to solve that problem in general.
http://www.haskell.org/ghc/docs/latest/html/users_guide/packages.html ghc-pkg find-module Text.Regex But that only works for (a) recent GHCs, and (b) packages installed on your system. You can also grep through the package file (e.g. /usr/lib/ghc-6.8.2/package.conf) to see what's installed. You can also use either the haskell API search engines hoogle or the hackage search engine hayoo . Text.Regex is in the package regex-base, and a few others built on top of it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5978/" ] }
141,855
Motivation I'd like to find a way to take an arbitrary color and lighten it a few shades, so that I can programatically create a nice gradient from the one color to a lighter version. The gradient will be used as a background in a UI. Possibility 1 Obviously I can just split out the RGB values and increase them individually by a certain amount. Is this actually what I want? Possibility 2 My second thought was to convert the RGB to HSV/HSB/HSL (Hue, Saturation, Value/Brightness/Lightness), increase the brightness a bit, decrease the saturation a bit, and then convert it back to RGB. Will this have the desired effect in general?
I would go for the second option. Generally speaking the RGB space is not really good for doing color manipulation (creating transition from one color to an other, lightening / darkening a color, etc). Below are two sites I've found with a quick search to convert from/to RGB to/from HSL: from the "Fundamentals of Computer Graphics" some sourcecode in C# - should be easy to adapt to other programming languages.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9960/" ] }
141,912
What are the alternative "design methods" to the Model View Controller? MVC seems to be popular (SO was built with it, I know that much) but is it the only method used?
There are many others: Model View Presenter (MVP) Supervising Controller Passive View Model View ViewModel (MVVM) This is common in WPF applications (though Prism uses the MVP pattern (usually))
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/141912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
141,973
Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks. EDIT: Here is what I have unsuccessfully tried: class Comment(db.Model): series = db.ReferenceProperty(reference_class=Series); def series_id(self): return self._series And in my template: <a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a> The result: <a href="games/view-series.html?series=#comm59">more</a>
Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '_' in python are generally accepted to be "protected" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes. However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example: class Comment(db.Model): series = db.ReferenceProperty(reference_class=Series); def series_id(self): return Comment.series.get_value_for_datastore(self) When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/141973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ] }
141,993
I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end. When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.) I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage. So, boiled down, the question is: Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.
Sounds like a job for XMLUnit http://www.xmlunit.org/ https://github.com/xmlunit Example: public class SomeTest extends XMLTestCase { @Test public void test() { String xml1 = ... String xml2 = ... XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences // can also compare xml Documents, InputSources, Readers, Diffs assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase }}
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/141993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ] }
142,000
I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with e.preventDefault() and runs an AJAX command. This works fine when the submit button is clicked but when a link with onclick='document.formName.submit();' is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?
A couple of suggestions: Overwrite the submit function to do your evil bidding var oldSubmit = form.submit; form.submit = function() { $(form).trigger("submit"); oldSubmit.call(form, arguments); } Why not bind to all the <a> tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag): $("form a").click(function() { $(this).parents().filter("form").trigger("submit"); });
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/142000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16624/" ] }
142,003
I have a scenario. (Windows Forms, C#, .NET) There is a main form which hosts some user control. The user control does some heavy data operation, such that if I directly call the UserControl_Load method the UI become nonresponsive for the duration for load method execution. To overcome this I load data on different thread (trying to change existing code as little as I can) I used a background worker thread which will be loading the data and when done will notify the application that it has done its work. Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl. The pseudocode would look like this: CODE 1 UserContrl1_LoadDataMethod(){ if (textbox1.text == "MyName") // This gives exception { //Load data corresponding to "MyName". //Populate a globale variable List<string> which will be binded to grid at some later stage. }} The Exception it gave was Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. To know more about this I did some googling and a suggestion came up like using the following code CODE 2 UserContrl1_LoadDataMethod(){ if (InvokeRequired) // Line #1 { this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod)); return; } if (textbox1.text == "MyName") // Now it won't give an exception { //Load data correspondin to "MyName" //Populate a globale variable List<string> which will be binded to grid at some later stage }} But it still seems that I've come back to square one. The Application againbecomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned. I don't know whether I perceived this right or wrong. I'm new to threading. How do I resolve this and also what is the effect of execution of Line#1 if block? The situation is this : I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread. So only accessing the value so that the corresponding data can be fetched from the database.
As per Prerak K's update comment (since deleted): I guess I have not presented the question properly. Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread. So only accessing the value so that corresponding data can be fetched from the database. The solution you want then should look like: UserContrl1_LOadDataMethod(){ string name = ""; if(textbox1.InvokeRequired) { textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; })); } if(name == "MyName") { // do whatever }} Do your serious processing in the separate thread before you attempt to switch back to the control's thread. For example: UserContrl1_LOadDataMethod(){ if(textbox1.text=="MyName") //<<======Now it wont give exception** { //Load data correspondin to "MyName" //Populate a globale variable List<string> which will be //bound to grid at some later stage if(InvokeRequired) { // after we've done all the processing, this.Invoke(new MethodInvoker(delegate { // load the control with the appropriate data })); return; } }}
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/142003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22858/" ] }
142,016
I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure. IE: given struct mstct { int myfield; int myfield2;}; I could write: mstct thing;printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing)); And get offset 4 for the output. How can I do it without that mstct thing declaration/allocating one? I know that &<struct> does not always point at the first byte of the first field of the structure, I can account for that later.
How about the standard offsetof() macro (in stddef.h)? Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like: #define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field))
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/142016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ] }
142,076
The scroll lock button seems to be a reminder of the good old green terminal days. Does anyone still use it? Should the 101 button keyboard become the 100 button keyboard?
In Excel, if you turn on scroll lock, using the arrow keys scrolls the spread sheet instead of changing the cell the cursor is in.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/142076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15053/" ] }
142,132
I know what MVC is and I work in webforms but I don't know how MVC will be that much different. I guess the code behind model will be different. So will it be like webforms minus the code behind and instead having it in a controller? I see there are other related posts but I don't they address this.
For starters, MVC does not use the <asp:control> controls, in preference for good old standard <input>'s and the like. Thus, you don't attach "events" to a control that get executed in a code-behind like you would in ASP. It relies on the standard http POST to do that. It does not use the viewstate object. It allows for more intelligent url mapping, though now that the Routing namespace has been spun off, I wonder if it can be used for WebForms? It is much easier to automate testing of web parts. It allows for much easier separation of UI logic from the "backend" components.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/142132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
142,142
Is there a query in SQL Server 2005 I can use to get the server's IP or name?
SELECT CONNECTIONPROPERTY('net_transport') AS net_transport, CONNECTIONPROPERTY('protocol_type') AS protocol_type, CONNECTIONPROPERTY('auth_scheme') AS auth_scheme, CONNECTIONPROPERTY('local_net_address') AS local_net_address, CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port, CONNECTIONPROPERTY('client_net_address') AS client_net_address The code here Will give you the IP Address; This will work for a remote client request to SQL 2008 and newer. If you have Shared Memory connections allowed, then running above on the server itself will give you "Shared Memory" as the value for 'net_transport', and NULL for 'local_net_address', and ' <local machine> ' will be shown in 'client_net_address'. 'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason. I advice strongly against using this answer . Enabling the shell out is a very bad idea on a production SQL Server.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/142142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ] }
142,184
I've seen a few COM controls which wrap the Gecko rendering engine ( GeckoFX , as well as the control shipped by Mozilla - mozctlx.dll ). Is there a wrapper for Webkit that can be included in a .NET Winform application?
There's a WebKit-Sharp component on Mono's GitHub Repository . I can't find any web-viewable documentation on it, and I'm not even sure if it's WinForms or GTK# (can't grab the source from here to check at the moment), but it's probably your best bet, either way.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/142184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ] }
142,252
This code works (C# 3) double d;if(d == (double)(int)d) ...; Is there a better way to do this? For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good) Note: Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.
d == Math.Floor(d) does the same thing in other words. NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/142252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ] }
142,273
We are beginning to go down the path of mobile browser support for an enterprise e-commerce webapp (Java/Servlet based). Of course there are many decisions to be made, but it seems to me the cornerstone is to be able to reliably detect mobile browsers, and make decisions on the content to be returned accordingly. Is there a standard way to make this determination (quickly) based on the http request, and ideally glean more information about the given browser and device making the request (screen size, html capabilities, etc?). I would also appreciate any supplemental information that would be of use from someone who has gone down this path of taking an existing large scale enterprise webapp and architect-ing out mobile browser support from the development side. [edit] I certainly understand the request header and the information about a database of standard user agents is a great help. For those talking about 'other' request header properties, if you could include similar standardized name / resource of values that would be a big help. [edit] Several users have proposed solutions that involve a call over the wire to some web service that will do the detection. While I'm sure this works, it is not a good solution for an enterprise e-commerce site for two reasons: 1) speed. A call over the wire for every page request to a third party would have huge performance implications. 2) dependency/legal. We'd tie our website response time and key functionality to their service, which is horrible for legal and risk reasons.
Wouldn't the standard way be to check the user agent? Here's a database of user agents you can use to detect mobile browsers.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/142273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17123/" ] }
142,282
If I have a UIView (or UIView subclass) that is visible, how can I tell if it's currently being shown on the screen (as opposed to, for example, being in a section of a scroll view that is currently off-screen)? To maybe give you a better idea of what I mean, UITableView has a couple of methods for determining the set of currently visible cells. I'm looking for some code that can make a similar determination for any given UIView .
Not tried any of this yet. But CGRectIntersectsRect() , -[UIView convertRect:to(from)View] and -[UIScrollView contentOffset] seem to be your basic building blocks here.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/142282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544/" ] }
142,317
I have the following code that shows either a bug or a misunderstanding on my part. I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow. Is this work as it should, or should I file a bug? import java.io.*;import java.net.*;import java.util.*;public class OOS { public static void main(String[] args) throws Exception { Thread t1 = new Thread(new Runnable() { public void run() { try { ServerSocket ss = new ServerSocket(12344); Socket s= ss.accept(); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); List same = new ArrayList(); same.add(0); oos.writeObject(same); same.clear(); same.add(1); oos.writeObject(same); } catch(Exception e) { e.printStackTrace(); } } }); t1.start(); Socket s = new Socket("localhost", 12344); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); // outputs [0] as expected System.out.println(ois.readObject()); // outputs [0], but expected [1] System.out.println(ois.readObject()); System.exit(0); }}
The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing). See the reset() method if you want to reset the graph.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/142317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ] }
142,319
This is a new gmail labs feature that lets you specify an RSS feed to grab random quotes from to append to your email signature. I'd like to use that to generate signatures programmatically based on parameters I pass in, the current time, etc. (For example, I have a script in pine that appends the current probabilities of McCain and Obama winning, fetched from intrade's API. See below.) But it seems gmail caches the contents of the URL you specify. Any way to control that or anyone know how often gmail looks at the URL? ADDED: Here's the program I'm using to test this. This file lives at http://kibotzer.com/sigs.php . The no-cache header idea, taken from here -- http://mapki.com/wiki/Dynamic_XML -- seems to not help. <?phpheader("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the pastheader("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");// HTTP/1.1header("Cache-Control: no-store, no-cache, must-revalidate");header("Cache-Control: post-check=0, pre-check=0", false);// HTTP/1.0header("Pragma: no-cache");//XML Headerheader("content-type:text/xml");?><!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd"><rss version="0.91"><channel><title>Dynamic Signatures</title><link>http://kibotzer.com</link><description>Blah blah</description><language>en-us</language><pubDate>26 Sep 2008 02:15:01 -0000</pubDate><webMaster>[email protected]</webMaster><managingEditor>[email protected] (Daniel Reeves)</managingEditor><lastBuildDate>26 Sep 2008 02:15:01 -0000</lastBuildDate><image><title>Kibotzer Logo</title><url>http://kibotzer.com/logos/kibo-logo-1.gif</url><link>http://kibotzer.com/</link><width>120</width><height>60</height><description>Kibotzer</description></image><item><title>Dynamic Signature 1 (<?php echo gmdate("H:i:s"); ?>) </title><link>http://kibotzer.com</link><description>This is the description for Signature 1 (<?php echo gmdate("H:i:s"); ?>) </description></item><item><title>Dynamic Signature 2 (<?php echo gmdate("H:i:s"); ?>) </title><link>http://kibotzer.com</link><description>This is the description for Signature 2 (<?php echo gmdate("H:i:s"); ?>) </description></item></channel></rss> --http://ai.eecs.umich.edu/people/dreeves - - search://"Daniel Reeves"Latest probabilities from intrade... 42.1% McCain becomes president (last trade 18:07 FRI) 57.0% Obama becomes president (last trade 18:34 FRI) 17.6% US recession in 2008 (last trade 16:24 FRI) 16.1% Overt air strike against Iran in '08 (last trade 17:39 FRI)
The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing). See the reset() method if you want to reset the graph.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/142319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ] }
142,331
I'm looking for books or online resources that go in detail over programming techniques for high performance computing using C++.
practically all HPC code I've heard of is either for solving sytems of linear equations or FFT's. Heres some links to start you off at least in the libraries used: BLAS - standard set of routines for linear algebra - stuff like matrix multiplication LAPACK - standard set of higher level linear algebra routines - stuff like LU decomp. ATLAS - Optimized BLAS implementation FFTW - Optimized FFT implementation PBLAS - BLAS for distributed processors SCALAPACK - distributed LAPACK implementation MPI - Communications library for distributed systems. PETSc - Scalable nonlinear and linear solvers (user-extensible, interface to much above)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/142331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3081/" ] }
142,356
What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type? I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it. Type type = typeof(FooBar)BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;type.GetConstructors(flags) .Where(constructor => constructor.GetParameters().Length == 0) .First();
type.GetConstructor(Type.EmptyTypes)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/142356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12784/" ] }
142,357
What are the best JVM settings you have found for running Eclipse?
It is that time of year again: "eclipse.ini take 3" the settings strike back! Eclipse Helios 3.6 and 3.6.x settings alt text http://www.eclipse.org/home/promotions/friends-helios/helios.png After settings for Eclipse Ganymede 3.4.x and Eclipse Galileo 3.5.x , here is an in-depth look at an "optimized" eclipse.ini settings file for Eclipse Helios 3.6.x: based on runtime options , and using the Sun-Oracle JVM 1.6u21 b7 , released July, 27th ( some some Sun proprietary options may be involved ). ( by "optimized", I mean able to run a full-fledge Eclipse on our crappy workstation at work, some old P4 from 2002 with 2Go RAM and XPSp3. But I have also tested those same settings on Windows7 ) Eclipse.ini WARNING : for non-windows platform, use the Sun proprietary option -XX:MaxPermSize instead of the Eclipse proprietary option --launcher.XXMaxPermSize . That is: Unless you are using the latest jdk6u21 build 7 . See the Oracle section below. -data../../workspace-showlocation-showsplashorg.eclipse.platform--launcher.defaultActionopenFile-vmC:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll-vmargs-Dosgi.requiredJavaVersion=1.6-Declipse.p2.unsignedPolicy=allow-Xms128m-Xmx384m-Xss4m-XX:PermSize=128m-XX:MaxPermSize=384m-XX:CompileThreshold=5-XX:MaxGCPauseMillis=10-XX:MaxHeapFreeRatio=70-XX:+CMSIncrementalPacing-XX:+UnlockExperimentalVMOptions-XX:+UseG1GC-XX:+UseFastAccessorMethods-Dcom.sun.management.jmxremote-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons Note: Adapt the p2.reconciler.dropins.directory to an external directory of your choice. See this SO answer .The idea is to be able to drop new plugins in a directory independently from any Eclipse installation. The following sections detail what are in this eclipse.ini file. The dreaded Oracle JVM 1.6u21 (pre build 7) and Eclipse crashes Andrew Niefer did alert me to this situation, and wrote a blog post , about a non-standard vm argument ( -XX:MaxPermSize ) and can cause vms from other vendors to not start at all. But the eclipse version of that option ( --launcher.XXMaxPermSize ) is not working with the new JDK (6u21, unless you are using the 6u21 build 7, see below). The final solution is on the Eclipse Wiki , and for Helios on Windows with 6u21 pre build 7 only: downloading the fixed eclipse_1308.dll (July 16th, 2010) and place it into (eclipse_home)/plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.0.v20100503 That's it. No setting to tweak here (again, only for Helios on Windows with a 6u21 pre build 7 ). For non-Windows platform, you need to revert to the Sun proprietary option -XX:MaxPermSize . The issue is based one a regression: JVM identification fails due to Oracle rebranding in java.exe , and triggered bug 319514 on Eclipse. Andrew took care of Bug 320005 - [launcher] --launcher.XXMaxPermSize: isSunVM should return true for Oracle , but that will be only for Helios 3.6.1. Francis Upton , another Eclipse committer, reflects on the all situation . Update u21b7, July, 27th : Oracle have regressed the change for the next Java 6 release and won't implement it again until JDK 7 . If you use jdk6u21 build 7 , you can revert to the --launcher.XXMaxPermSize (eclipse option) instead of -XX:MaxPermSize (the non-standard option). The auto-detection happening in the C launcher shim eclipse.exe will still look for the " Sun Microsystems " string, but with 6u21b7, it will now work - again. For now, I still keep the -XX:MaxPermSize version (because I have no idea when everybody will launch eclipse the right JDK). Implicit `-startup` and `--launcher.library` Contrary to the previous settings, the exact path for those modules is not set anymore, which is convenient since it can vary between different Eclipse 3.6.x releases: startup: If not specified, the executable will look in the plugins directory for the org.eclipse.equinox.launcher bundle with the highest version. launcher.library: If not specified, the executable looks in the plugins directory for the appropriate org.eclipse.equinox.launcher.[platform] fragment with the highest version and uses the shared library named eclipse_* inside. Use JDK6 The JDK6 is now explicitly required to launch Eclipse: -Dosgi.requiredJavaVersion = 1.6 This SO question reports a positive incidence for development on Mac OS. +UnlockExperimentalVMOptions The following options are part of some of the experimental options of the Sun JVM. -XX:+UnlockExperimentalVMOptions-XX:+UseG1GC-XX:+UseFastAccessorMethods They have been reported in this blog post to potentially speed up Eclipse. See all the JVM options here and also in the official Java Hotspot options page . Note: the detailed list of those options reports that UseFastAccessorMethods might be active by default. See also "Update your JVM" : As a reminder, G1 is the new garbage collector in preparation for the JDK 7, but already used in the version 6 release from u17. Opening files in Eclipse from the command line See the blog post from Andrew Niefer reporting this new option: --launcher.defaultActionopenFile This tells the launcher that if it is called with a command line that only contains arguments that don't start with " - ", then those arguments should be treated as if they followed " --launcher.openFile ". eclipse myFile.txt This is the kind of command line the launcher will receive on windows when you double click a file that is associated with eclipse, or you select files and choose " Open With " or " Send To " Eclipse. Relative paths will be resolved first against the current working directory, and second against the eclipse program directory. See bug 301033 for reference. Originally bug 4922 (October 2001, fixed 9 years later). p2 and the Unsigned Dialog Prompt If you are tired of this dialog box during the installation of your many plugins: , add in your eclipse.ini : -Declipse.p2.unsignedPolicy=allow See this blog post from Chris Aniszczy , and the bug report 235526 . I do want to say that security research supports the fact that less prompts are better. People ignore things that pop up in the flow of something they want to get done. For 3.6, we should not pop up warnings in the middle of the flow - no matter how much we simplify, people will just ignore them. Instead, we should collect all the problems, do not install those bundles with problems, and instead bring the user back to a point in the workflow where they can fixup - add trust, configure security policy more loosely, etc. This is called 'safe staging' . ---------- http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif Additional options Those options are not directly in the eclipse.ini above, but can come in handy if needed. The `user.home` issue on Windows7 When eclipse starts, it will read its keystore file (where passwords are kept), a file located in user.home . If for some reason that user.home doesn't resolve itself properly to a full-fledge path, Eclipse won't start. Initially raised in this SO question , if you experience this, you need to redefine the keystore file to an explicit path (no more user.home to resolve at the start) Add in your eclipse.ini : -eclipse.keyring C:\eclipse\keyring.txt This has been tracked by bug 300577 , it has been solve in this other SO question . Debug mode Wait, there's more than one setting file in Eclipse. if you add to your eclipse.ini the option: -debug , you enable the debug mode and Eclipse will look for another setting file: a .options file where you can specify some OSGI options. And that is great when you are adding new plugins through the dropins folder. Add in your .options file the following settings, as described in this blog post " Dropins diagnosis " : org.eclipse.equinox.p2.core/debug=trueorg.eclipse.equinox.p2.core/reconciler=true P2 will inform you what bundles were found in dropins/ folder, what request was generated, and what is the plan of installation. Maybe it is not detailed explanation of what actually happened, and what went wrong, but it should give you strong information about where to start: was your bundle in the plan? Was it installation problem (P2 fault) or maybe it is just not optimal to include your feature? That comes from Bug 264924 - [reconciler] No diagnosis of dropins problems , which finally solves the following issue like: Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipseUnzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5 This is a problematic configuration since OCL depends on EMF which is missing. 3.5M5 provides no diagnosis of this problem. Start eclipse. No obvious problems. Nothing in Error Log. Help / About / Plugin details shows org.eclipse.ocl.doc , but not org.eclipse.ocl . Help / About / Configuration details has no (diagnostic) mention of org.eclipse.ocl . Help / Installation / Information Installed Software has no mention of org.eclipse.ocl . Where are the nice error markers? Manifest Classpath See this blog post : In Galileo (aka Eclipse 3.5), JDT started resolving manifest classpath in libraries added to project’s build path. This worked whether the library was added to project’s build path directly or via a classpath container, such as the user library facility provided by JDT or one implemented by a third party. In Helios, this behavior was changed to exclude classpath containers from manifest classpath resolution. That means some of your projects might no longer compile in Helios. If you want to revert to Galileo behavior, add: -DresolveReferencedLibrariesForContainers=true See bug 305037 , bug 313965 and bug 313890 for references. IPV4 stack This SO question mentions a potential fix when not accessing to plugin update sites: -Djava.net.preferIPv4Stack=true Mentioned here just in case it could help in your configuration. JVM1.7x64 potential optimizations This article reports: For the record, the very fastest options I have found so far for my bench test with the 1.7 x64 JVM n Windows are: -Xincgc -XX:-DontCompileHugeMethods -XX:MaxInlineSize=1024 -XX:FreqInlineSize=1024 But I am still working on it...
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/142357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15352/" ] }
142,391
I am making extensive use of boost:shared_ptr in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr . Unfortunately this means that I can't pass this into any function that takes a shared_ptr . Consider this code: void bar(boost::shared_ptr<Foo> pFoo){ ...}void Foo::someFunction(){ bar(this);} There are two problems here. First, this won't compile because the T* constructor for shared_ptr is explicit. Second, if I force it to build with bar(boost::shared_ptr<Foo>(this)) I will have created a second shared pointer to my object that will eventually lead to a double-delete. This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?
You can derive from enable_shared_from_this and then you can use "shared_from_this()" instead of "this" to spawn a shared pointer to your own self object. Example in the link: #include <boost/enable_shared_from_this.hpp>class Y: public boost::enable_shared_from_this<Y>{public: shared_ptr<Y> f() { return shared_from_this(); }}int main(){ shared_ptr<Y> p(new Y); shared_ptr<Y> q = p->f(); assert(p == q); assert(!(p < q || q < p)); // p and q must share ownership} It's a good idea when spawning threads from a member function to boost::bind to a shared_from_this() instead of this. It will ensure that the object is not released.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/142391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031/" ] }
142,420
I have a method lets say: private static String drawCellValue( int maxCellLength, String cellValue, String align) { } and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how? Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use. Any ideas?
This should do it: private enum Alignment { LEFT, RIGHT }; String drawCellValue (int maxCellLength, String cellValue, Alignment align){ if (align == Alignment.LEFT) { //Process it... }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/142420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6618/" ] }
142,431
I'm setting up a server to offer JIRA and SVN. I figure, I'll use LDAP to keep the identity management simple. So, before I write one.... is there a good app out there to let users change their ldap password? I want something that lets a user authenticate with ldap and update their password. A form with username, old password, new password and verification would be enough. I can write my own, but it seems silly to do so if there's already a good app out there that handles this.... Thanks for the help.
This should do it: private enum Alignment { LEFT, RIGHT }; String drawCellValue (int maxCellLength, String cellValue, Alignment align){ if (align == Alignment.LEFT) { //Process it... }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/142431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9950/" ] }
142,481
Is there such a thing as unit test generation? If so... ...does it work well? ...What are the auto generation solutions that are available for .NET? ...are there examples of using a technology like this? ...is this only good for certain types of applications, or could it be used to replace all manually written unit testing?
Take a look at Pex . Its a Microsoft Research project. From the website: Pex generates Unit Tests from hand-written Parameterized Unit Tests through Automated Exploratory Testing based on Dynamic Symbolic Execution. UPDATE for 2019: As mentioned in the comments, Pex is now called IntelliTest and is a feature of Visual Studio Enterprise Edition. It supports emitting tests in MSTest, MSTest V2, NUnit, and xUnit format and it is extensible so you can use it with other unit test frameworks. But be aware of the following caveats: Supports only C# code that targets the .NET Framework. Does not support x64 configurations. Available in Visual Studio Enterprise Edition only
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/142481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ] }
142,504
What are some methods of utilising Eclipse for Dependency Management?
I really like the The Maven Integration for Eclipse (m2eclipse, Eclipse m2e) . I use it purely for the dependency management feature. It's great not having to go out and download a bunch of new jars new each time I set up a project.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/142504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ] }
142,508
I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this: #ifdef OSisWindows// do Windows-specific stuff#else// do Unix-specific stuff#endif Is there a way to do this? Is there a better way to do the same thing?
The Predefined Macros for OS site has a very complete list of checks. Here are a few of them, with links to where they're found: Windows _WIN32 Both 32 bit and 64 bit _WIN64 64 bit only __CYGWIN__ Unix (Linux, *BSD, but not Mac OS X) See this related question on some of the pitfalls of using this check. unix __unix __unix__ Mac OS X __APPLE__ Also used for classic __MACH__ Both are defined; checking for either should work. Linux __linux__ linux Obsolete (not POSIX compliant) __linux Obsolete (not POSIX compliant) FreeBSD __FreeBSD__ Android __ANDROID__
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/142508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10601/" ] }
142,545
The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.
I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__ module, it will be accessible as if a global from any other module that includes __builtin__ -- which is all of them, by default. a.py contains print foo b.py contains import __builtin____builtin__.foo = 1import a The result is that "1" is printed. Edit: The __builtin__ module is available as the local symbol __builtins__ -- that's the reason for the discrepancy between two of these answers. Also note that __builtin__ has been renamed to builtins in python3.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/142545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22897/" ] }