source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
185,967 | Note: Originally this question was asked for PostgreSQL, however, the answer applies to almost any database which has a JDBC driver that can detect foreign-key associations. Querying PostgreSQL data dictionary for foreign-keys and relationship between tables is very straightforward, but how can I use that information to generate a graph of the relations between tables? Any recommendations about tools that can do this? EDIT: I know GraphVIZ/DOT can be useful, however, I don't know have any idea regarding how to code an app that would generate the directed graph .DOT file. | Dot is part of the graphviz package, which is a pretty damn cool/useful tool. Of course, you'll need something to generate the dot files for graphviz. I've used SchemaSpy once or twice in the past, and it works pretty well, provided you have the relationships defined in the database. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861/"
]
} |
185,972 | In javascript, we can do: ["a string", 10, {x : 1}, function() {}].push("another value"); What is the Scala equivalent? | Arrays in Scala are very much homogeneous. This is because Scala is a statically typed language. If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are). List is the canonical example there, but Vector is also an option. Then you can do something like this: Vector("a string", 10, Map("x" -> 1), ()=>()) + "another value" The result will be of type Vector[Any] . Not very useful in terms of static typing, but everything will be in there as promised. Incidentally, the "literal syntax" for arrays in Scala is as follows: Array(1, 2, 3, 4) // => Array[Int] containing [1, 2, 3, 4] See also : More info on persistent vectors | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20689/"
]
} |
185,993 | Is there good example code or a test project for explaining the Model–view–presenter (MVP) pattern . There are a lot of explanation links, but I want to have some good example code to show others without reinventing the wheel. | Jeremy Miller's "Build your own CAB" series is fantastic. You get a nice dose of MVP (along with some other smart client patterns such as Pub/Sub). http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
]
} |
186,015 | I have had to do this several times, usually when trying to find in what files a variable or a function is used. I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways. | grep -r REGEX . Replace . with whatever directory you want to search from. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25910/"
]
} |
186,024 | (function() { //codehere })(); What is special about this kind of syntax?What does ()(); imply? | The creates an anonymous function, closure and all, and the final () tells it to execute itself. It is basically the same as: function name (){...}name(); So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it. This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21572/"
]
} |
186,035 | I have a simple "accordion" type page containing a list of H3 headers and DIV content boxes (each H3 is followed by a DIV). On this page I start with all DIVs hidden. When a H3 is clicked the DIV directly below (after) is revealed with jQuery's "slideDown" function while all other DIVs are hidden with the "slideUp" function. The "slideUp" function inserts the following inline style into the specified DIVs: style="display: none;" I am wondering if there is any way for me to show all the DIVs expanded when a user prints the page (as I do when a user has JavaScript disabled). I am thinking it is impossible because the inline style will always take precedence over any other style declaration. Is there another solution? Solution Sugendran's solution is great and works in the browsers (FF2, IE7 and IE6) I've tested so far. I wasn't aware there was any way to override inline styles which I'm pretty sure is something I've looked up before so this is great to find out. I also see there is this answer here regarding this. I wish search wasn't so difficult to navigate here :-). Lee Theobald's solution would be great but the "slideUp" function adds the style="display:none;" bit. My solution works fine, but is overkill when the !important declaration works. | You can use the !important clause in CSS. This will override the inline style. So if you setup a print media stylesheet - you can do something like div.accordian { display:block !important; } | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
} |
186,044 | I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning. After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was. Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take? | For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning. As you said, relative positioning and normal flow layout make this sort of task quite difficult. Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users. In this case I would avoid it. Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning within the nearest "positioned" parent element. Note: A "positioned" element can be any of the following: relative, fixed, absolute, or sticky. To explain: <div id="parentDIV" style="position:relative"> <div id="childDIV" style="position:absolute;left:20px;top:20px;"> I'm absolutely positioned within parentDIV. </div></div> Here, childDIV is actually positioned 20px from the left and 20px from the top of parentDIV , NOT the overall document. This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout. So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build. However in general positioning (absolute or relative) versus default flow layout, my approach is as described above. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193/"
]
} |
186,062 | Can I create a Controller that simply returns an image asset? I would like to route this logic through a controller, whenever a URL such as the following is requested: www.mywebsite.com/resource/image/topbanner The controller will look up topbanner.png and send that image directly back to the client. I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller. Is this possible? | Use the base controllers File method. public ActionResult Image(string id){ var dir = Server.MapPath("/Images"); var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path. return base.File(path, "image/jpeg");} As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller ( http://localhost/MyController/Image/MyImage ) and through the direct URL ( http://localhost/Images/MyImage.jpg ) and the results were: MVC: 7.6 milliseconds per photo Direct: 6.7 milliseconds per photo Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/186062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23341/"
]
} |
186,084 | Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding. | That's very nice, however in order to simulate some time passing we need to run a command that takes some time and that's very clear in second example. However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that. We can see this modification in the code from the same book CLR Via C# Third Ed. using System;using System.Threading;public static class Program { private Timer _timer = null; public static void Main() { // Create a Timer object that knows to call our TimerCallback // method once every 2000 milliseconds. _timer = new Timer(TimerCallback, null, 0, 2000); // Wait for the user to hit <Enter> Console.ReadLine(); } private static void TimerCallback(Object o) { // Display the date/time when this method got called. Console.WriteLine("In TimerCallback: " + DateTime.Now); }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
]
} |
186,118 | I have been trying to change the background color of Eclipse's windows to black and customize the font colors. There doesn't seem to be a way to do this, at least not in an obvious way. I am using version 3.3. How do I do this or are there any plugin's that might be able to assist in doing this? | To change background colour Open menu *Windows → Preferences → General → Editors → Text Editors Browse Appearance color options Select background color options, uncheck default, change to black Select background color options, uncheck default, change to colour of choice To change text colours Open Java → Editor → Syntax Colouring Select element from Java Change colour List item To change Java editor font Open menu Windows → Preferences → General → Appearance → Colors and Fonts Select Java → Java Editor Text font from list Click on change and select font | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/186118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24390/"
]
} |
186,128 | A client wants me to do some maintenance work to a VB 6.0 application (migration to .NET is also in the pipeline), but he doesn't have the development tools because he received just the source code and running application from the original programmer, who is no longer available. Microsoft doesn't sell Visual Studio 6.0, as far as I know. How can I modify and compile the source code for a VB6 application without VB6? or Where do I get Visual Studio 6.0 if Microsoft is not selling it?. Even if I migrate everything to .NET without releasing a new VB6 version, I would like to be able to open the project and see it compile and run to better understand it. I have VS 2005 and VB 2008. But I understand that if I try to open the project the code will be converted to VB.NET and that's not what I would want before getting to know the project better. | From what I recall the Visual Studio 6.0 is available for MSDN Subscribers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
]
} |
186,202 | What is the most elegant way to solve this: open a file for reading, but only if it is not already opened for writing open a file for writing, but only if it is not already opened for reading or writing The built-in functions work like this >>> path = r"c:\scr.txt">>> file1 = open(path, "w")>>> print file1<open file 'c:\scr.txt', mode 'w' at 0x019F88D8>>>> file2 = open(path, "w")>>> print file2<open file 'c:\scr.txt', mode 'w' at 0x02332188>>>> file1.write("111")>>> file2.write("222")>>> file1.close() scr.txt now contains '111'. >>> file2.close() scr.txt was overwritten and now contains '222' (on Windows, Python 2.4). The solution should work inside the same process (like in the example above) as well as when another process has opened the file. It is preferred, if a crashing program will not keep the lock open. | I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module. Fortunately, there is a portable implementation ( portalocker ) using the platform appropriate method at the python cookbook. To use it, open the file, and then call: portalocker.lock(file, flags) where flags are portalocker.LOCK_EX for exclusive write access, or LOCK_SH for shared, read access. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19166/"
]
} |
186,237 | I've got a "Schroedinger's Cat" type of problem here -- my program (actually the test suite for my program, but a program nonetheless) is crashing, but only when built in release mode, and only when launched from the command line. Through caveman debugging (ie, nasty printf() messages all over the place), I have determined the test method where the code is crashing, though unfortunately the actual crash seems to happen in some destructor, since the last trace messages I see are in other destructors which execute cleanly. When I attempt to run this program inside of Visual Studio, it doesn't crash. Same goes when launching from WinDbg.exe. The crash only occurs when launching from the command line. This is happening under Windows Vista, btw, and unfortunately I don't have access to an XP machine right now to test on. It would be really nice if I could get Windows to print out a stack trace, or something other than simply terminating the program as if it had exited cleanly. Does anyone have any advice as to how I could get some more meaningful information here and hopefully fix this bug? Edit: The problem was indeed caused by an out-of-bounds array, which I describe more in this post . Thanks everybody for your help in finding this problem! | In 100% of the cases I've seen or heard of, where a C or C++ program runs fine in the debugger but fails when run outside, the cause has been writing past the end of a function local array. (The debugger puts more on the stack, so you're less likely to overwrite something important.) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
]
} |
186,244 | One of the major advantages with Javascript is said to be that it is a prototype based language. But what does it mean that Javascript is prototype based, and why is that an advantage? | Prototypal inheritance is a form of object-oriented code reuse . Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical. In classical inheritance , the programmer writes a class, which defines an object. Multiple objects can be instantiated from the same class, so you have code in one place which describes several objects in your program. Classes can then be organized into a hierarchy, furthering code reuse. More general code is stored in a higher-level class, from which lower level classes inherit. This means that an object is sharing code with other objects of the same class, as well as with its parent classes. In the prototypal inheritance form, objects inherit directly from other objects. All of the business about classes goes away. If you want an object, you just write an object. But code reuse is still a valuable thing, so objects are allowed to be linked together in a hierarchy. In javascript, every object has a secret link to the object which created it, forming a chain. When an object is asked for a property that it does not have, its parent object will be asked... continually up the chain until the property is found or until the root object is reached. Each function in JavaScript (which are objects themselves) actually has a member called "prototype", which is responsible for providing values when an object is asked for them. Having this member allows the constructor mechanism (by which objects are constructed from functions) to work. Adding a property to the prototype of a function object will make it available to the constructed object, as well as to all of the objects which inherit from it. Advantages There may not be a hard and fast rule as to why prototypal inheritance is an advantageous form of code-reuse. Code reuse itself is advantageous, and prototypal inheritance is a sensible way of going about it. You might argue that prototypal inheritance is a fairly simple model of code reuse, and that code can be heavily reused in direct ways . But classical languages are certainly able to accomplish this as well. Sidenote: @Andrew Hedges makes a good point, that there are actually many prototypal languages. It's worth noting that these others exist, but also worth noting that none of them are anything close to mainstream. NewtonScript seemed to have some traction for a while, but died with its platform. It's also possible to extend some modern languages in ways which add prototypal capabilities. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/186244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1918/"
]
} |
186,338 | Everything I read about better PHP coding practices keeps saying don't use require_once because of speed. Why is this? What is the proper/better way to do the same thing as require_once ? If it matters, I'm using PHP 5. | require_once and include_once both require that the system keeps a log of what's already been included/required. Every *_once call means checking that log. So there's definitely some extra work being done there but enough to detriment the speed of the whole app? ... I really doubt it... Not unless you're on really old hardware or doing it a lot . If you are doing thousands of *_once , you could do the work yourself in a lighter fashion. For simple apps, just making sure you've only included it once should suffice but if you're still getting redefine errors, you could something like this: if (!defined('MyIncludeName')) { require('MyIncludeName'); define('MyIncludeName', 1);} I'll personally stick with the *_once statements but on silly million-pass benchmark, you can see a difference between the two: php hhvmif defined 0.18587779998779 0.046600103378296require_once 1.2219581604004 3.2908599376678 10-100× slower with require_once and it's curious that require_once is seemingly slower in hhvm . Again, this is only relevant to your code if you're running *_once thousands of times. <?php // test.php$LIMIT = 1000000;$start = microtime(true);for ($i=0; $i<$LIMIT; $i++) if (!defined('include.php')) { require('include.php'); define('include.php', 1); }$mid = microtime(true);for ($i=0; $i<$LIMIT; $i++) require_once('include.php');$end = microtime(true);printf("if defined\t%s\nrequire_once\t%s\n", $mid-$start, $end-$mid); <?php // include.php// do nothing. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314/"
]
} |
186,392 | Many database systems don't allow comments or descriptions of tables and fields, so how do you go about documenting the purpose of a table/field apart from the obvious of having good naming conventions? (Let's assume for now that "excellent" table and field names are not enough to document the full meaning of every table, field and relationship in the database.) I know many people use UML diagrams to visualize the database, but I have rarely—if ever—seen a UML diagram including field comments. However, I have good experience with using comments inside .sql files. The downside to this approach is that it requires the .sql files to be manually kept up-to-date as the database structure changes over time—but if you do, you can also have it under version control. Some other techniques I have seen are separate document describing database structure and relationships and manually maintained comments inside ORM code or other database-mapping code. How have you solved this problem in the past? What methods exists and what are the various pros and cons associated with them? How you would you like this solved in "a perfect world"? Update As others have pointed out, most of the popular SQL engines do in fact allow comments, which is great. Oddly enough, people don't seem to be using these features much. At least not on the projects I have been involved with in the past. | MySQL allows comments on tables and rows. PostgreSQL does as well. From other answers, Oracle and MSSQL have comments too. For me, a combination of UML diagram for a quick refresher on field names, types, and constraints, and an external document (TeX, but could be any format) with extended description of everything database-related - special values, field comments, access notes, whatever - works best. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709/"
]
} |
186,403 | When you create a procedure (or a function) in Oracle PL/SQL, you cannot specify the maximum length of the varchar2 arguments, only the datatype. For example create or replace procedure testproc(arg1 in varchar2) isbegin null;end; Do you know the maximum length of a string that you can pass as the arg1 argument to this procedure in Oracle ? | In PL/SQL procedure it may be up to 32KB Futher information here: http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20037/"
]
} |
186,431 | Given a week number, e.g. date -u +%W , how do you calculate the days in that week starting from Monday? Example rfc-3339 output for week 40: 2008-10-062008-10-072008-10-082008-10-092008-10-102008-10-112008-10-12 | PHP $week_number = 40;$year = 2008;for($day=1; $day<=7; $day++){ echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n";} Below post was because I was an idiot who didn't read the question properly, but will get the dates in a week starting from Monday, given the date, not the week number.. In PHP , adapted from this post on the PHP date manual page : function week_from_monday($date) { // Assuming $date is in format DD-MM-YYYY list($day, $month, $year) = explode("-", $_REQUEST["date"]); // Get the weekday of the given date $wkday = date('l',mktime('0','0','0', $month, $day, $year)); switch($wkday) { case 'Monday': $numDaysToMon = 0; break; case 'Tuesday': $numDaysToMon = 1; break; case 'Wednesday': $numDaysToMon = 2; break; case 'Thursday': $numDaysToMon = 3; break; case 'Friday': $numDaysToMon = 4; break; case 'Saturday': $numDaysToMon = 5; break; case 'Sunday': $numDaysToMon = 6; break; } // Timestamp of the monday for that week $monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year); $seconds_in_a_day = 86400; // Get date for 7 days from Monday (inclusive) for($i=0; $i<7; $i++) { $dates[$i] = date('Y-m-d',$monday+($seconds_in_a_day*$i)); } return $dates;} Output from week_from_monday('07-10-2008') gives: Array( [0] => 2008-10-06 [1] => 2008-10-07 [2] => 2008-10-08 [3] => 2008-10-09 [4] => 2008-10-10 [5] => 2008-10-11 [6] => 2008-10-12) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/186431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4534/"
]
} |
186,475 | I would like to use databinding when displaying data in a TextBox. I'm basically doing like: public void ShowRandomObject(IRandomObject randomObject) { Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")}; txtName.SetBinding(TextBox.TextProperty, binding); } I can't seem to find a way to unset the binding. I will be calling this method with a lot of different objects but the TextBox will remain the same. Is there a way to remove the previous binding or is this done automatically when I set the new binding? | When available BindingOperations.ClearBinding(txtName, TextBox.TextProperty) For older SilverLight versions, but not reliable as stated in comments: txtName.SetBinding(TextBox.TextProperty, null); C# 6.0 features enabled this.btnFinish.ClearBinding(ButtonBase.CommandProperty); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/186475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
]
} |
186,477 | I have a function which parses one string into two strings. In C# I would declare it like this: void ParseQuery(string toParse, out string search, out string sort){ ...} and I'd call it like this: string searchOutput, sortOutput;ParseQuery(userInput, out searchOutput, out sortOutput); The current project has to be done in C++/CLI. I've tried using System::Runtime::InteropServices;...void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort){ ...} but if I call it like this: String ^ searchOutput, ^ sortOutput;ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput); I get a compiler error, and if I call it like this: String ^ searchOutput, ^ sortOutput;ParseQuery(userInput, searchOutput, sortOutput); then I get an error at runtime. How should I declare and call my function? | C++/CLI itself doesn't support a real 'out' argument, but you can mark a reference as an out argument to make other languages see it as a real out argument. You can do this for reference types as: void ReturnString([Out] String^% value){ value = "Returned via out parameter";}// Called asString^ result;ReturnString(result); And for value types as: void ReturnInt([Out] int% value){ value = 32;}// Called asint result;ReturnInt(result); The % makes it a 'ref' parameter and the OutAttribute marks that it is only used for output values. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
]
} |
186,493 | I'm trying to write a Mono C# daemon for linux. I'd like to do a starts and stops of it when its done processing instead of just killing the process. Does anyone have any examples of this? Edit: I figured out how to use start-stop-daemon --background in debian, so I think I'll just use that for now. Edit: I'm implementing this in java as well and they have this nice addShutdownHook that catches terminating the app. I need to spend a little more time sorting out the dependencies for mono service, or find a way to catch app termination. There is the SessionEnd event, but thats only available for services and not console apps Answer: using mono-service to wrap a windows service on linux | You should implement a service and use mono-service. Google for it and you'll find several examples. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253/"
]
} |
186,494 | I've seen second one in another's code and I suppose this length comparison have been done to increase code productivity. It was used in a parser for a script language with a specific dictionary: words are 4 to 24 letters long with the average of 7-8 lettets, alphabet includes 26 latin letters plus "@","$" and "_". Length comparison were used to escape == operator working with STL strings, which obviously takes more time then simple integer comparison. But in the same time first letter distribution in the given dictionary is simply wider than a distribution of words size, so two first letters of comparing strings will be generally more often different, than the sizes of that strings. That makes length comparison unnecessary. I've ran some tests and that is what I've found out: While testing two random strings comparison million times, second way is much faster, so length comparison seems to be helpful. But in a working project it works even slower in a debug mode and insufficiantly faster in a release mode. So, my question is: why length comparison can fasten the comparison and why can it slow it down? UPD: I don't like that second way either, but it had been done for a reason, I suppose, and I wonder, what is this reason. UPD2: Seriously, the question is not how to do best. I'm not even using STL strings in this case anymore. There's no wonder that length comparison is unnecessary and wrong etc. The wonder is - it really tends to work slightly better in one certain test. How is this possible? | If it mattered, assume that your library did it already. Don't mess up your code this way for micro-optimisations unless it really matters. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25459/"
]
} |
186,496 | Lets assume my classes are loaded from a compressed .war file or loaded elsewhere, how can I discover all the resources in a given package? Enumerating files will not really work, since this is a war file. Most likely this will involve using the current classloader? Is there a library out there that does something like that? Googling revealed only some hacks with listing files. | Yes. You can use ClassLoader.getResources("") ; Or you could use ferret API: https://www.ohloh.net/p/pureperfect-ferret This API allows you to scan the class path as well as arbitrary archives and directories using the Visitor pattern. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16542/"
]
} |
186,523 | Which other restrictions are there on names (beside the obvious uniqueness within a scope)? Where are those defined? | From the PDF of ECMA-335 , Partition II, section 22: Metadata preserves name strings, as created by a compiler or code generator, unchanged. Essentially, it treatseach string as an opaque blob. In particular, it preserves case. The CLI imposes no limit on the length of names stored in metadata and subsequently processed by the CLI If I've read this correctly and the context is correct then there's no actual limit to the length of an identifier in the CLR. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
]
} |
186,548 | I am using IIS6, I've written an HttpModule, and I get this error? After googling the web I find that this problem is caused by the .NET framework 3.5, so I put this on a machine where I didn't install .NET 3.5, but the problem is still there! | My attempt at psychic debugging: you're using a statement like: Response.Headers("X-Foo") = "bar" If this is indeed the case, changing this as shown below will work around the problem: Response.AddHeader("X-Foo", "bar") | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20142/"
]
} |
186,572 | Using SQL Server - which is the fastest or best practice method to use for date retrieval? Is there a difference? | CURRENT_TIMESTAMP is standard ANSI SQL, and so is theoretically one tiny little island of 'don't need to change' amongst your thousands of SQL Server-specific lines of SQL if you ever need to move databases.... | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
]
} |
186,581 | When I'm working on a project, sometimes I'll design the GUI first and then write the backend code to make it work, but other times I'll do the opposite and make the GUI once I have the system working. How do you choose which way round to code and are there any particular types of project or circumstances that would lean you either way? | You need to create something which would let your testers start immediately. Try to think from that prospective. If they are working on manual UI testing give them a shell of UI with stubs for all the functionality. If there is an interface to be tested make sure it works (even if it returns dummy data) so they could start working with it, etc. Most of the time it's the UI. You could show it to your users and get immediate feedback which is really useful. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
]
} |
186,588 | When you limit the number of rows to be returned by a SQL query, usually used in paging, there are two methods to determine the total number of records: Method 1 Include the SQL_CALC_FOUND_ROWS option in the original SELECT , and then get the total number of rows by running SELECT FOUND_ROWS() : SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE id > 100 LIMIT 10;SELECT FOUND_ROWS(); Method 2 Run the query normally, and then get the total number of rows by running SELECT COUNT(*) SELECT * FROM table WHERE id > 100 LIMIT 10;SELECT COUNT(*) FROM table WHERE id > 100; Which method is the best / fastest? | It depends. See the MySQL Performance Blog post on this subject: To SQL_CALC_FOUND_ROWS or not to SQL_CALC_FOUND_ROWS ? Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that SQL_CALC_FOUND_ROWS is almost always slower - sometimes up to 10x slower - than running two queries. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
]
} |
186,619 | I have a pseudo random number generator (PRNG) class that I want to unit test. There are two approaches: write a test case that takes a large amount of samples and test whether they are properly distributed. This approach may lead to a fairly long execution time for the test case; calculate a small series of samples 'by hand' and verify if the PRNG algorithm reproduces it. This approach may lead to a not random sequence being generated without being noticed; I would say that the first approach is not really unit testing because it does not perform a white box test of the generator, but on the other hand it properly tests the responsibility of the class. The second approach is more like a real unit test, focusing on the algorithm, but it does not provide as much evidence as to whether the class fulfills its responsibility. Which approach do you prefer, and why? | Get another implementation of the same PRNG algorithm, generate a smallish number of longish test cases based on known seeds, and verify that your implementation of the algorithm matches everyone else's implementations. The more data you test, the more chance it does. If you want to be serious, look into how FIPS validation is done for the algorithm. There's no need to test whether the output is random, since far more research has been done on the algorithm by others than you are capable of reproducing. If you have invented your own PRNG algorithm then you have a rather different problem, because quite aside from testing your code you also need to test your new algorithm. There are various things to do -- I think the most important are statistical testing on the output, and peer review by other cryptographers. Basically, though, if you were to design a PRNG algorithm without having enough knowledge in the field to know how to test it, then it will be rubbish. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
]
} |
186,631 | I have a WCF service and I want to expose it as both a RESTfull service and as a SOAP service. Anyone has done something like this before? | You can expose the service in two different endpoints.the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration <endpointBehaviors> <behavior name="jsonBehavior"> <enableWebScript/> </behavior></endpointBehaviors> An example of endpoint configuration in your scenario is <services> <service name="TestService"> <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/> <endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="ITestService"/> </service></services> so, the service will be available at http://www.example.com/soap http://www.example.com/json Apply [WebGet] to the operation contract to make it RESTful.e.g. public interface ITestService{ [OperationContract] [WebGet] string HelloWorld(string text)} Note, if the REST service is not in JSON, parameters of the operations can not contain complex type. Reply to the post for SOAP and RESTful POX(XML) For plain old XML as return format, this is an example that would work both for SOAP and XML. [ServiceContract(Namespace = "http://test")]public interface ITestService{ [OperationContract] [WebGet(UriTemplate = "accounts/{id}")] Account[] GetAccount(string id);} POX behavior for REST Plain Old XML <behavior name="poxBehavior"> <webHttp/></behavior> Endpoints <services> <service name="TestService"> <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/> <endpoint address="xml" binding="webHttpBinding" behaviorConfiguration="poxBehavior" contract="ITestService"/> </service></services> Service will be available at http://www.example.com/soap http://www.example.com/xml REST request try it in browser, http://www.example.com/xml/accounts/A123 SOAP request client endpoint configuration for SOAP service after adding the service reference, <client> <endpoint address="http://www.example.com/soap" binding="basicHttpBinding" contract="ITestService" name="BasicHttpBinding_ITestService" /> </client> in C# TestServiceClient client = new TestServiceClient();client.GetAccount("A123"); Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/186631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15314/"
]
} |
186,643 | We have several common libs. Ideally we want them all to use the latest version of a dll even if they have been compiled against an older different version (assume the latest version is backward compatible) e.g we have: Project dll Common controls dll Logging dll Database access dll Project and common controls reference v2 of database dll. Logging however references v1. If different versions are referenced in different components how does VS pick which one to use? Do we have to recompile v1 dll to use the latest database (v2) or can we get this to pick up automatically? Is it possible to force a particular version to be used? Thanks, Alex | By default, for versioned DLLs I believe VS will force an exact match. If you look in the properties of the reference, however, you'll find a property called "Specific Version". Set that to "false" and it will match later versions. I don't have the full version of VS with me to find an appropriate MSDN link, unfortunately. In addition, you can use the assemblyBinding element in app.config. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
]
} |
186,653 | Unless I am missing an obvious built-in method, what is the quickest way to get the n th occurrence of a string within a string? I realize that I could loop the IndexOf method by updating its start index on each iteration of the loop. But doing it this way seems wasteful to me. | That's basically what you need to do - or at least, it's the easiest solution. All you'd be "wasting" is the cost of n method invocations - you won't actually be checking any case twice, if you think about it. (IndexOf will return as soon as it finds the match, and you'll keep going from where it left off.) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/186653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
]
} |
186,656 | A while a go I had to developed a music site that allowed audio files to be uploaded to a site and then converted in to various formats using ffmpeg, people would then download the uploaded audio files after purchasing them and a tmp file would be created and placed at the download location and was only valid for each download instance and the tmp file would then get deleted. Now I am revisiting the project, I have to add pictures and video as upload content also. I want to find the best method for storing the files, option 1 : storing the files in a folder and reference them in the database option 2 : storing the actual file in the database(mysql) as blob. I am toying around with this idea to consider the security implications of each method, and other issues I might have not calculated for. | See this earlier StackOverflow question Storing images in a database, Yea or nay? . I know you mentioned images and video, however this question has relevance to all large binary content media files. The consensus seems to be that storing file paths to the images on the filesystem, rather then the actual images is the way to go. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16092/"
]
} |
186,657 | When I disable ViewState for the page. It does not allow any other control to use ViewState .. even if I set EnableViewState="true" for that particular control .. is it possible to enable ViewState for a control when ViewState is disabled for the page itself? if not how can disable viewstate for controls on page except for few without specifying EnableViewState="false" explicitly .. typing the same into so many controls is hectic .. | If you set turn page's ViewState off, then there is no way for you to enable ViewState for specific components. This is because ViewState is serialzed recursively, so when if the Page is not allowing ViewState, it will not serialize the ViewState for any of it's child controls. In answer to your question, if you don't want to explicitly turn ViewState off on individual controls, but want to keep some controls ViewState aware, the best way would be writing a small utility method which turns ViewState off for all controls (using recursion or otherwise). Then enable ViewState for the controls that you would like to enable ViewState for. Alternatively, a middle ground and less forceful way may possible if controls are groups inside other container controls (such as Panel). You can disable ViewState for all controls inside a Panel by disabling ViewState of the Panel. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25138/"
]
} |
186,737 | I want to delete a folder that contains thousands of files and folders. If I use Windows Explorer to delete the folder it can take 10-15 minutes (not always, but often). Is there a faster way in Windows to delete folders? Other details: I don't care about the recycle bin. It's an NTFS drive. | Using Windows Command Prompt: rmdir /s /q folder Using Powershell: powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse" Note that in more cases del and rmdir wil leave you with leftover files, where Powershell manages to delete the files. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/186737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11766/"
]
} |
186,756 | How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table? For example: nr12345 I would like to use only MySQL for this (not PHP or other languages). | If you need the records in a table and you want to avoid concurrency issues, here's how to do it. First you create a table in which to store your records CREATE TABLE `incr` ( `Id` int(11) NOT NULL auto_increment, PRIMARY KEY (`Id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8; Secondly create a stored procedure like this: DELIMITER ;;CREATE PROCEDURE dowhile()BEGIN DECLARE v1 INT DEFAULT 5; WHILE v1 > 0 DO INSERT incr VALUES (NULL); SET v1 = v1 - 1; END WHILE;END;;DELIMITER ; Lastly call the SP: CALL dowhile();SELECT * FROM incr; Result Id12345 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14635/"
]
} |
186,768 | Due to the lack of clientaccesspolicy.xml, there appears to be problems with using Amazon S3 via Flex. Are there any work arounds? Edit: Both of the below answers are great and work, I've upvoted both (I'm not going to assign an answer to the question as they both work): Can you use Amazon S3 via Flex? Can you use Amazon S3 via Flex? | You can CNAME a subdomain you control at Amazon S3 (to a bucket with the name of the subdomain), like so: http://s3.ceejayoz.com/ (goes to my 's3.ceejayoz.com' bucket) Uploading your own clientaccesspolicy.xml file to the root of that bucket (and setting the permissions to be globally viewable) should do the trick, if I'm understanding your question correctly, as it will be accessible at http://s3.ceejayoz.com/clientaccesspolicy.xml . More information in the S3 docs: http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?VirtualHosting.html edit: From looking at that, you could also use the "Example Virtual Hosted Style Method" without a CNAME: http://bucketname.s3.amazonaws.com/clientaccesspolicy.xml | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
]
} |
186,798 | The log levels WARN, ERROR and FATAL are pretty clear. But when is something DEBUG, and when INFO? I've seen some projects that are annoyingly verbose on the INFO level, but I've also seen code that favors the DEBUG level too much. In both cases, useful information is hidden in the noise. What are the criteria for determining log levels? | I don't think there are any hard-and-fast rules; using the log4j-type levels, my 'rules of thumb' are something like: FATAL : the app (or at the very least a thread) is about to die horribly. This is where the info explaining why that's happening goes. ERROR : something that the app's doing that it shouldn't. This isn't a user error ('invalid search query'); it's an assertion failure, network problem, etc etc., probably one that is going to abort the current operation WARN : something that's concerning but not causing the operation to abort; # of connections in the DB pool getting low, an unusual-but-expected timeout in an operation, etc. I often think of 'WARN' as something that's useful in aggregate; e.g. grep, group, and count them to get a picture of what's affecting the system health INFO : Normal logging that's part of the normal operation of the app; diagnostic stuff so you can go back and say 'how often did this broad-level operation happen?', or 'how did the user's data get into this state?' DEBUG : Off by default, able to be turned on for debugging specific unexpected problems. This is where you might log detailed information about key method parameters or other information that is useful for finding likely problems in specific 'problematic' areas of the code. TRACE : "Seriously, WTF is going on here?!?! I need to log every single statement I execute to find this @#$@ing memory corruption bug before I go insane" Not set in stone, but a rough idea of how I think of it. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6400/"
]
} |
186,799 | When using JDBC, I often come across constructs like ResultSet rs = ps.executeQuery();while (rs.next()) { int id = rs.getInt(1); // Some other actions} I asked myself (and authors of code too) why not to use labels for retrieving column values: int id = rs.getInt("CUSTOMER_ID"); The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion. So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)? | You should use string labels by default. Pros: Independence of column order Better readability/maintainability Cons: You have no control over the column names (access via stored procedures) Which would you prefer? ints? int i = 1; customerId = resultSet.getInt(i++); customerName = resultSet.getString(i++); customerAddress = resultSet.getString(i++); or Strings? customerId = resultSet.getInt("customer_id"); customerName = resultSet.getString("customer_name"); customerAddress = resultSet.getString("customer_address"); And what if there is a new column inserted at position 1? Which code would you prefer? Or if the order of the columns is changed, which code version would you need to change at all? That's why you should use string labels by default. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/186799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11732/"
]
} |
186,800 | I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration: <defaultProxy useDefaultCredentials="false"> <proxy usesystemdefault="true" proxyaddress="<proxy address>" bypassonlocal="true" /></defaultProxy> I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this. Is there any way to do this? MSDN isn't helping me much.. | Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though. Create an assembly called SomeAssembly.dll with this class : namespace SomeNameSpace{ public class MyProxy : IWebProxy { public ICredentials Credentials { get { return new NetworkCredential("user", "password"); } //or get { return new NetworkCredential("user", "password","domain"); } set { } } public Uri GetProxy(Uri destination) { return new Uri("http://my.proxy:8080"); } public bool IsBypassed(Uri host) { return false; } }} Add this to your config file : <defaultProxy enabled="true" useDefaultCredentials="false"> <module type = "SomeNameSpace.MyProxy, SomeAssembly" /></defaultProxy> This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application. This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection , or add some information in the AppSettings , which is far more easier. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5793/"
]
} |
186,822 | How do I invoke a console application from my .NET application and capture all the output generated in the console? (Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.) | This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application. Process compiler = new Process();compiler.StartInfo.FileName = "csc.exe";compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";compiler.StartInfo.UseShellExecute = false;compiler.StartInfo.RedirectStandardOutput = true;compiler.Start(); Console.WriteLine(compiler.StandardOutput.ReadToEnd());compiler.WaitForExit(); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17519/"
]
} |
186,829 | Conventional IPv4 dotted quad notation separates the address from the port with a colon, as in this example of a webserver on the loopback interface: 127.0.0.1:80 but with IPv6 notation the address itself can contain colons. For example, this is the short form of the loopback address: ::1 How are ports (or their functional equivalent) expressed in a textual representation of an IPv6 address/port endpoint? | They work almost the same as today. However, be sure you include [] around your IP. For example : http://[1fff:0:a88:85a3::ac1f]:8001/index.html Wikipedia has a pretty good article about IPv6: http://en.wikipedia.org/wiki/IPv6#Addressing | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/186829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715673/"
]
} |
186,854 | I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime? | First, you really should try not to have exceptions thrown - and not handled - in a background thread. If you control the way your delegate is run, encapsulate it in a try catch block and figure a way to pass the exception information back to your main thread (using EndInvoke if you explicitly called BeginInvoke, or by updating some shared state somewhere). Ignoring a unhandled exception can be dangerous. If you have a real un-handlable exception (OutOfMemoryException comes into mind), there's not much you can do anyway and your process is basically doomed. Back to .Net 1.1, an unhandled exception in a backgroundthread would just be thrown to nowhere and the main thread would gladly plough on. And that could have nasty repercussions. So in .Net 2.0 this behavior has changed. Now, an unhandled exception thrown in a thread which is not the main thread will terminate the process. You may be notified of this (by subscribing to the event on the AppDomain) but the process will die nonetheless. Since this can be inconvenient (when you don't know what will be run in the thread and you are not absolutely sure it's properly guarded, and your main thread must be resilient), there's a workaround. It's intended as a legacy settings (meaning, it's strongly suggested you make sure you don't have stray threads) but you can force the former behavior this way : Just add this setting to your service/application/whatever configuration file : <configuration> <runtime> <!-- the following setting prevents the host from closing when an unhandled exception is thrown --> <legacyUnhandledExceptionPolicy enabled="1" /> </runtime></configuration> It doesn't seem to work with ASP.NET, though. For more information (and a huge warning that this setting may not be supported in upcoming versions of the CLR) see http://msdn.microsoft.com/en-us/library/ms228965.aspx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5978/"
]
} |
186,857 | I have a string that looks like this: "Name1=Value1;Name2=Value2;Name3=Value3" Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this: dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3"} I have looked through the modules available but can't seem to find anything that matches. Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function. I'll do it myself then. | There's no builtin, but you can accomplish this fairly simply with a generator comprehension: s= "Name1=Value1;Name2=Value2;Name3=Value3"dict(item.split("=") for item in s.split(";")) [Edit] From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs): >>> s = "Name1='Value=2';Name2=Value2;Name3=Value3">>> dict(csv.reader([item], delimiter='=', quotechar="'").next() for item in csv.reader([s], delimiter=';', quotechar="'").next()){'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'} Depending on the exact structure of your format, you may need to write your own simple parser however. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
]
} |
186,867 | I need to stream a file to the Response for saving on the end user's machine. The file is plain text, so what content type can I use to prevent the text being displayed in the browser? | To be on the safe side and ensure consistent behavior in all browsers, it's usually better to use both: Content-Type: application/octet-streamContent-Disposition: attachment;filename=\"My Text File.txt\" | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
]
} |
186,891 | If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway? For example: class Program{ static void Main(string[] args) { TestRef t = new TestRef(); t.Something = "Foo"; DoSomething(t); Console.WriteLine(t.Something); } static public void DoSomething(TestRef t) { t.Something = "Bar"; }}public class TestRef{ public string Something { get; set; }} The output is "Bar" which means that the object was passed as a reference. | Pass a ref if you want to change what the object is: TestRef t = new TestRef();t.Something = "Foo";DoSomething(ref t);void DoSomething(ref TestRef t){ t = new TestRef(); t.Something = "Not just a changed t, but a completely different TestRef object";} After calling DoSomething, t does not refer to the original new TestRef , but refers to a completely different object. This may be useful too if you want to change the value of an immutable object, e.g. a string . You cannot change the value of a string once it has been created. But by using a ref , you could create a function that changes the string for another one that has a different value. It is not a good idea to use ref unless it is needed. Using ref gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility. Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int ), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns: int x = 1;Change(ref x);Debug.Assert(x == 5);WillNotChange(x);Debug.Assert(x == 5); // Note: x doesn't become 10void Change(ref int x){ x = 5;}void WillNotChange(int x){ x = 10;} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/186891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93743/"
]
} |
186,894 | I am looking for the best way to test if a website is alive from a C# application. Background My application consists of a Winforms UI , a backend WCF service and a website to publish content to the UI and other consumers. To prevent the situation where the UI starts up and fails to work properly because of a missing WCF service or website being down I have added an app startup check to ensure that all everything is alive. The application is being written in C#, .NET 3.5, Visual Studio 2008 Current Solution Currently I am making a web request to a test page on the website that will inturn test the web site and then display a result. WebRequest request = WebRequest.Create("http://localhost/myContentSite/test.aspx");WebResponse response = request.GetResponse(); I am assuming that if there are no exceptions thown during this call then all is well and the UI can start. Question Is this the simplest, right way or is there some other sneaky call that I don't know about in C# or a better way to do it. | HttpWebResponse response = (HttpWebResponse)request.GetResponse();if (response == null || response.StatusCode != HttpStatusCode.OK) As @Yanga mentioned, HttpClient is probably the more common way to do this now. HttpClient client = new HttpClient();var checkingResponse = await client.GetAsync(url);if (!checkingResponse.IsSuccessStatusCode){ return false;} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/186894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
]
} |
186,895 | Is there a way in Visual Studio (a hotkey) to automatically import a type (or choosing between known namespaces) like the Ctrl + O in Eclipse? | When the red caret appears at the end of your member, just hit Shift + Alt + F10 , then use arrows keys to choose the right option: | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/186895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68336/"
]
} |
186,916 | I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort. I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (& <> and so on...). Do you have any idea of what could be a good way of accomplishing this? Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code. | You have two decent options: Python standard config file formatusing ConfigParser YAML using a library like PyYAML The standard Python configuration files look like INI files with [sections] and key : value or key = value pairs. The advantages to this format are: No third-party libraries necessary Simple, familiar file format. YAML is different in that it is designed to be a human friendly data serialization format rather than specifically designed for configuration. It is very readable and gives you a couple different ways to represent the same data. For your problem, you could create a YAML file that looks like this: file .* does not exist : file not founduser .* not found : authorization error Or like this: { file .* does not exist: file not found, user .* not found: authorization error } Using PyYAML couldn't be simpler: import yamlerrors = yaml.load(open('my.yaml')) At this point errors is a Python dictionary with the expected format. YAML is capable of representing more than dictionaries: if you prefer a list of pairs, use this format: - - file .* does not exist - file not found- - user .* not found - authorization error Or [ [file .* does not exist, file not found], [user .* not found, authorization error]] Which will produce a list of lists when yaml.load is called. One advantage of YAML is that you could use it to export your existing, hard-coded data out to a file to create the initial version, rather than cut/paste plus a bunch of find/replace to get the data into the right format. The YAML format will take a little more time to get familiar with, but using PyYAML is even simpler than using ConfigParser with the advantage is that you have more options regarding how your data is represented using YAML. Either one sounds like it will fit your current needs, ConfigParser will be easier to start with while YAML gives you more flexibilty in the future, if your needs expand. Best of luck! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622/"
]
} |
186,917 | I'm trying to catch a ClassCastException when deserializing an object from xml. So, try { restoredItem = (T) decoder.readObject();} catch (ClassCastException e){ //don't need to crash at this point, //just let the user know that a wrong file has been passed.} And yet this won't as the exception doesn't get caught. What would you suggest? | The code in the question should give you an unchecked cast warning. Listen to -Xlint. All the compiler knows about T is its bounds, which it probably doesn't have (other than explicitly extending Object and a super of the null type). So effectively the cast at runtime is (Object) - not very useful. What you can do is pass in an instance of the Class of the parameterised type (assuming it isn't generic). class MyReader<T> { private final Class<T> clazz; MyReader(Class<T> clazz) { if (clazz == null) { throw new NullPointerException(); } this.clazz = clazz; } public T restore(String from) { ... try { restoredItem = clazz.cast(decoder.readObject()); ... return restoredItem; } catch (ClassCastException exc) { ... } }} Or as a generic method: public <T> T restore(Class<T> clazz, String from) { ... try { restoredItem = clazz.cast(decoder.readObject()); ... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
]
} |
186,918 | My master page contains a list as shown here. What I'd like to do though, is add the "class=active" attribute to the list li thats currently active but I have no idea how to do this. I know that the code goes in the aspx page's page_load event, but no idea how to access the li I need to add the attribute. Please enlighten me. Many thanks. <div id="menu"> <ul id="nav"> <li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li> <li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li> <li id="future"><a href="future.aspx" title="Future">Future</a></li> <li id="news"><a href="news.aspx" title="News">News</a></li> <li id="download"><a href="download.aspx" title="Download">Download</a></li> <li id="home"><a href="index.aspx" title="Home">Home</a></li> <li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li> </ul></div> | In order to access these controls from the server-side, you need to make them runat="server" <ul id="nav" runat="server"> <li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li> <li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li> <li id="future"><a href="future.aspx" title="Future">Future</a></li> <li id="news"><a href="news.aspx" title="News">News</a></li> <li id="download"><a href="download.aspx" title="Download">Download</a></li> <li id="home"><a href="index.aspx" title="Home">Home</a></li> <li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li></ul> in the code-behind: foreach(Control ctrl in nav.controls){ if(!ctrl is HtmlAnchor) { string url = ((HtmlAnchor)ctrl).Href; if(url == GetCurrentPage()) // <-- you'd need to write that ctrl.Parent.Attributes.Add("class", "active"); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/186918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
]
} |
186,970 | What ReSharper 4.0 templates for C# do you use? Let's share these in the following format: [Title] Optional description Shortcut: shortcut Available in: [AvailabilitySetting] // Resharper template code snippet// comes here Macros properties (if present): Macro1 - Value - EditableOccurence Macro2 - Value - EditableOccurence One macro per answer, please! Here are some samples for NUnit test fixture and Standalone NUnit test case that describe live templates in the suggested format. | Implement 'Dispose(bool)' Method Implement Joe Duffy's Dispose Pattern Shortcut: dispose Available in: C# 2.0+ files where type member declaration is allowed public void Dispose(){ Dispose(true); System.GC.SuppressFinalize(this);}protected virtual void Dispose(bool disposing){ if (!disposed) { if (disposing) { if ($MEMBER$ != null) { $MEMBER$.Dispose(); $MEMBER$ = null; } } disposed = true; }}~$CLASS$(){ Dispose(false);}private bool disposed; Macros properties : MEMBER - Suggest variable of System.IDisposable - Editable Occurence #1 CLASS - Containing type name | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/186970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47366/"
]
} |
187,001 | Is it possible to provide WCF with a custom proxy address and custom credentials? I've found this answer on stackoverflow: How to set proxy with credentials to generated WCF client? , but I've got a complication, the service I'm authenticating against uses its own authentication, so I've got to use two sets of credentials (one to get through the proxy, and the other to authenticate against the service) I'm using the technique described in the answers to the other question to provide the service credentials. e.g. client.ClientCredentials.UserName.UserName = username;client.ClientCredentials.UserName.Password = password; I can set the address of the proxy using something like this: (client.Endpoint.Binding as WSHttpBinding).ProxyAddress = ...; How do I set what is effectively two sets of credentials? (NB: The credentials for the proxy and the actual service are different!) Also note that the proxy details are not necessarily the default system proxy details. | If you set the WebRequest.DefaultWebProxy property to a new WebProxy with credentials, WCF will use it for all HTTP requests that it makes. (This will affect all HttpWebRequests used by the application unless explicitly overridden). // get this information from the user / config file / etc.Uri proxyAddress;string userName;string password;// set this before any web requests or WCF callsWebRequest.DefaultWebProxy = new WebProxy(proxyAddress){ Credentials = new NetworkCredential(userName, password),}; My blog post on proxy servers contains further details. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1313/"
]
} |
187,040 | I Have an old vbs script file being kicked off by an AutoSys job. Can I, and how do I, return an int return value to indicate success or failure? | Try: WScript.Quit n Where n is the ERRORLEVEL you want to return | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180142/"
]
} |
187,046 | Has anyone seen a tool that will integrate code coverage results with SCM/VCS to attribute untested lines of code to developers?For example, is there a tool that will take NCover's Coverage.Xml, combine it with SVN blame, and produce a report that tells me things like developer who commits most untested code? | Try: WScript.Quit n Where n is the ERRORLEVEL you want to return | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26479/"
]
} |
187,073 | I'm using the sortable function in jquery to sequence a faq list. Needless to say, i'm new to this concept. Anybody have any good examples of the backend for this. I have the front working fine, but updating the sequence in the database is another story. My backend is ColdFusion btw. Thanks in advance | Define the faq: <div id="faq"> <div id="q1">...</div> <div id="q2">...</div> (...) <div id="q100">..</div></div> Make faq sortable: <script type="text/javascript"> $("#faq").sortable();</script> Form submitted: <form action="..." id="faq_form"> <input type="hidden" name="faqs" id="faqs" /> ...</form> Add sorted sequence to form <script type="text/javascript> $("#faq_form").submit(function() { $("#faqs").val($("#faq").sortable('toArray')) })</script> When form is submitted, field "faqs" will contain comma separated id's from #faq like this:q1,q3,q10,q11,q2,q100... Just parse it and save to DB | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
]
} |
187,098 | I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data. Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers. Soundmanager2 comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well. Does anyone have any other libraries that might help? | You will have to include a plug-in like Real Audio or QuickTime to handle the .wav file, but this should work... //======================================================================var soundEmbed = null;//======================================================================function soundPlay(which) { if (!soundEmbed) { soundEmbed = document.createElement("embed"); soundEmbed.setAttribute("src", "/snd/"+which+".wav"); soundEmbed.setAttribute("hidden", true); soundEmbed.setAttribute("autostart", true); } else { document.body.removeChild(soundEmbed); soundEmbed.removed = true; soundEmbed = null; soundEmbed = document.createElement("embed"); soundEmbed.setAttribute("src", "/snd/"+which+".wav"); soundEmbed.setAttribute("hidden", true); soundEmbed.setAttribute("autostart", true); } soundEmbed.removed = false; document.body.appendChild(soundEmbed); }//====================================================================== | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22383/"
]
} |
187,146 | Why is the order of tables important when combining an outer & an inner join ?the following fails with postgres: SELECT grp.number AS number, tags.value AS tag FROM groups grp, insrel archiverel LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 AND archiverel.dnumber = grp.number with result: ERROR: invalid reference to FROM-clause entry for table "grp" LINE 5: LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.d... ^ HINT: There is an entry for table "grp", but it cannot be referenced from this part of the query. when the groups are reversed in the FROM it all works: SELECT grp.number AS number, tags.value AS tag FROM insrel archiverel, groups grpLEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 AND archiverel.dnumber = grp.number | I believe that you can think of this as an operator precedence issue. When you write this: FROM groups grp, insrel archiverel LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber I think it is interpreted by the parser like this: FROM groups grp,( ( insrel archiverel LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber )LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber) If so, then in the innermost join "grp" is unbound. When you reverse the lines with "groups" and "insrel", the innermost join applies to "groups" and "ownrel", so it works. Probably this would work as well: FROM groups grp JOIN insrel archiverel ON archiverel.dnumber = grp.number LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26486/"
]
} |
187,169 | Most developers and engineers that have experience writing software and deploying with the packaged Visual Studio Setup Project know about its many shortcomings. Usually in regards to installation customization, upgrade paths, etc. What are some good alternatives for software deployment? In particular I'm interested in features, .NET integration or scripting capabilities, easy of use, and price. | Windows Installer XML (Wix) NullSoft Installer | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/507/"
]
} |
187,216 | What is the best way for converting phone numbers into international format (E.164) using Java? Given a 'phone number' and a country id (let's say an ISO country code), I would like to convert it into a standard E.164 international format phone number. I am sure I can do it by hand quite easily - but I would not be sure it would work correctly in all situations. Which Java framework/library/utility would you recommend to accomplish this? P.S. The 'phone number' could be anything identifiable by the general public - such as * (510) 786-0404* 1-800-GOT-MILK* +44-(0)800-7310658 that last one is my favourite - it is how some people write their number in the UK and means that you should either use the +44 or you should use the 0. The E.164 format number should be all numeric, and use the full international country code (e.g.+44) | Google provides a library for working with phone numbers. The same one they use for Android http://code.google.com/p/libphonenumber/ String swissNumberStr = "044 668 18 00"PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();try { PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");} catch (NumberParseException e) { System.err.println("NumberParseException was thrown: " + e.toString());}// Produces "+41 44 668 18 00"System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));// Produces "044 668 18 00"System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));// Produces "+41446681800"System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164)); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
]
} |
187,273 | Building on How Do You Express Binary Literals in Python , I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance. def num_bin(N, places=8): def bit_at_p(N, p): ''' find the bit at place p for number n ''' two_p = 1 << p # 2 ^ p, using bitshift, will have exactly one # bit set, at place p x = N & two_p # binary composition, will be one where *both* numbers # have a 1 at that bit. this can only happen # at position p. will yield two_p if N has a 1 at # bit p return int(x > 0) bits = ( bit_at_p(N,x) for x in xrange(places)) return "".join( (str(x) for x in bits) ) # or, more consisely # return "".join([str(int((N & 1 << x)>0)) for x in xrange(places)]) | For best efficiency, you generally want to process more than a single bit at a time.You can use a simple method to get a fixed width binary representation. eg. def _bin(x, width): return ''.join(str((x>>i)&1) for i in xrange(width-1,-1,-1)) _bin(x, 8) will now give a zero padded representation of x's lower 8 bits. This can be used to build a lookup table, allowing your converter to process 8 bits at a time (or more if you want to devote the memory to it). _conv_table = [_bin(x,8) for x in range(256)] Then you can use this in your real function, stripping off leading zeroes when returning it. I've also added handling for signed numbers, as without it you will get an infinite loop (Negative integers conceptually have an infinite number of set sign bits.) def bin(x): if x == 0: return '0' #Special case: Don't strip leading zero if no other digits elif x < 0: sign='-' x*=-1 else: sign = '' l=[] while x: l.append(_conv_table[x & 0xff]) x >>= 8 return sign + ''.join(reversed(l)).lstrip("0") [Edit] Changed code to handle signed integers. [Edit2] Here are some timing figures of the various solutions. bin is the function above, constantin_bin is from Constantin's answer and num_bin is the original version. Out of curiosity, I also tried a 16 bit lookup table variant of the above (bin16 below), and tried out Python3's builtin bin() function. All timings were for 100000 runs using an 01010101 bit pattern. Num Bits: 8 16 32 64 128 256---------------------------------------------------------------------bin 0.544 0.586 0.744 1.942 1.854 3.357 bin16 0.542 0.494 0.592 0.773 1.150 1.886constantin_bin 2.238 3.803 7.794 17.869 34.636 94.799num_bin 3.712 5.693 12.086 32.566 67.523 128.565Python3's bin 0.079 0.045 0.062 0.069 0.212 0.201 As you can see, when processing long values using large chunks really pays off, but nothing beats the low-level C code of python3's builtin (which bizarrely seems consistently faster at 256 bits than 128!). Using a 16 bit lookup table improves things, but probably isn't worth it unless you really need it, as it uses up a large chunk of memory, and can introduce a small but noticalbe startup delay to precompute the table. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
]
} |
187,279 | I want to create a simple box with a header bar containing a title and some tool buttons. I have the following markup: <div style="float:left"> <div style="background-color:blue; padding: 1px; height: 20px;"> <div style="float: left; background-color:green;">title</div> <div style="float: right; background-color:yellow;">toolbar</div> </div> <div style="clear: both; width: 200px; background-color: red;">content</div></div> This renders fine in Firefox and Chrome: http://www.boplicity.nl/images/firefox.jpg However IE7 totally messes up and puts the right floated element to the right of the page: http://www.boplicity.nl/images/ie7.jpg Can this be fixed? | Specify width in outermost div. If that width in your content div means this is the total width of your box, simply add it to the outermost div, and (optionally) remove it from content, like this: <div style="float:left; width: 200px;"> <div style="background-color:blue; padding: 1px; height: 20px;"> <div style="float: left; background-color:green;">title</div> <div style="float: right; background-color:yellow;">toolbar</div> </div> <div style="clear: both; background-color: red;">content</div></div> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26496/"
]
} |
187,284 | I have log4net running on my AsP.NET site. I'm able to log messages to my DB Table, but it isn't logging the ThreadContext properties. For example: ThreadContext.Properties["Url"] = HttpContext.Current.Request.Url.ToString();ThreadContext.Properties["HttpReferer"] = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]; My log4net.config adds those values as parameters into my SQL DB table: <parameter> <parameterName value="@URL"/> <dbType value="String"/> <size value="512"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{log4net:Url}"/> </layout></parameter><parameter> <parameterName value="@HttpReferer"/> <dbType value="String"/> <size value="512"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{log4net:HttpReferer}"/> </layout></parameter> As I debug, I see that those ThreadContext properties are being set, but they aren't getting into the DB. How can I get that to work? | So, it turns out the config was to blame. It was slightly wrong: Original: <conversionPattern value="%property{log4net:HttpReferer}"/> Changed: <conversionPattern value="%property{HttpReferer}"/> I had to take out the "log4net:" inside of property. What's odd is that one property still required log4net:propertyName. I have absolutely no idea why it works this way, but that's the fix that worked! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1204/"
]
} |
187,289 | Code lines per file, methods per class, cyclomatic complexity and so on. Developers resist and workaround most if not all of them! There is a good Joel article on it (no time to find it now). What code metric(s) you recommend for use to automatically identify "crappy code"? What can convince most (you can't convince all of us to some crappy metric! :O) ) of developers that this code is "crap". Only metrics that can be automatically measured counts! | No metrics regarding coding-style are part of such a warning. For me it is about static analysis of the code , which can truly be 'on' all the time: cyclomatic complexity (detected by checkstyle) dependency cycle detection (through findbugs for instance) critical errors detected by, for instance findbugs. I would put coverage test in a second step, as such tests can take time. Do not forget that "crappy" code are not detected by metrics, but by the combination and evolution (as in " trend ) of metrics: see the What is the fascination with code metrics? question. That means you do not have just to recommend code metrics to "automatically identify "crappy code"", but you also have to recommend the right combination and trend analysis to go along those metrics. On a sidenote, I do share your frustration ;), and I do not share the point of view of tloach (in the comments of another answers) "Ask a vague question, get a vague answer" he says... your question deserve a specific answer. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23436/"
]
} |
187,380 | Ruby is becoming popular , largely from the influence Ruby on Rails, but it feels like it is currently struggling through its adolescence. There are a lot of similarities between Ruby and Smalltalk -- maglev is a testament to that. Despite having a more unusual syntax, Smalltalk has all (if not more) of the object-oriented beauty of Ruby. From what I have read, Smalltalk seems to have Ruby beat on: Maturity (developed in the 1970's) Stability Commercial support Distributed source control (understands structure of code, not just text diffing) Several implementations of the VM Cross-platform support The seaside web framework as a strong alternative to Rails It seems like Ruby is just reinventing the wheel. So, why don't Ruby developers use SmallTalk? What does Ruby have the Smalltalk doesn't? For the record: I'm a Ruby guy with little to no experience in Smalltalk, but I'm starting to wonder why. Edit: I think the ease-of-scripting issue has been addressed by GNU Smalltalk . As I understand it, this allows you to write smalltalk in regular old text files, and you no longer need to be in the Smalltalk IDE. You can then run your scripts with: gst smalltalk_file | I'm more of a Pythonista than a Ruby user, however the same things hold for Ruby for much the same reasons. The architecture of Smalltalk is somewhat insular whereas Python and Ruby were built from the ground up to facilitate integration. Smalltalk never really gained a body of hybrid application support in the way that Python and Ruby have, so the concept of 'smalltalk as embedded scripting language' never caught on. As an aside, Java was not the easiest thing to interface with other code bases (JNI is fairly clumsy), but that did not stop it from gaining mindshare. IMO the interfacing argument is significant - ease of embedding hasn't hurt Python - but this argument only holds moderate weight as not all applications require this capability. Also, later versions of Smalltalk did substantially address the insularity. The class library of most of the main smalltalk implementations (VisualWorks, VisualAge etc.) was large and had reputation for a fairly steep learning curve. Most key functionality in Smalltalk is hidden away somewhere in the class library, even basic stuff like streams and collections. The language paradigm is also something of a culture shock for someone not familiar with it, and the piecemeal view of the program presented by the browser is quite different to what most people were used to. The overall effect is that Smalltalk got a (somewhat deserved) reputation for being difficult to learn; it takes quite a bit of time and effort to become a really proficient Smalltalk programmer. Ruby and Python are much easier to learn and to bring new programmers up to speed with. Historically, mainstream Smalltalk implementations were quite expensive and needed exotic hardware to run, as can be seen this net.lang.st80 posting from 1983 . Windows 3.1, NT and '95 and OS/2 were the first mass market operating systems on mainstream hardware capable of supporting a Smalltalk implementation with decent native system integration. Previously, Mac or workstation hardware were the cheapest platforms capable of running Smalltalk effectively. Some implementations (particularly Digitalk) supported PC operating systems quite well and did succeed in gaining some traction. However, OS/2 was never that successful and Windows did not achieve mainstream acceptance until the mid 1990s. Unfortunately this coincided with the rise of the Web as a platform and a large marketing push behind Java. Java grabbed most of the mindshare in the latter part of the 1990s, rendering Smalltalk a bit of an also-ran. Ruby and Python work in a more conventional toolchain and are not tightly coupled to a specific development environment. While the Smalltalk IDEs I have used are nice enough I use PythonWin for Python development largely because it has a nice editor with syntax highlighting and doesn't get underfoot. However, Smalltalk is was designed to be used with an IDE (in fact, Smalltalk was the original graphical IDE) and still has some nice features not replicated by other systems. Testing code with highlight and 'Show it' is still a very nice feature that I have never seen in a Python IDE, although I can't speak for Ruby. Smalltalk was somewhat late coming to the web application party. Early efforts such as VisualWave were never terribly successful and it was not until Seaside came out that a decent web framework got acceptance in Smalltalk circles. In the meantime Java EE has had a complete acceptance lifecycle starting with raving fanboys promoting it and finally getting bored and moving onto Ruby ;-} Ironically, Seaside is starting to get a bit of mindshare among the cognoscenti so we may find that Smalltalk rides that cycle back into popularity. Having said that, Smalltalk is a very nice system once you've worked out how to drive it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23899/"
]
} |
187,406 | private string? typeOfContract{ get { return (string?)ViewState["typeOfContract"]; } set { ViewState["typeOfContract"] = value; }} Later in the code I use it like this: typeOfContract = Request.QueryString["type"]; I am getting the following error at the declaration of typeOfContract line stating: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>' Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action. | System.String is a reference type and already "nullable". Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/187406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4144/"
]
} |
187,414 | I don't really get lambda expressions. While they've been around since the days of ALGOL, I didn't start hearing about them until fairly recently, when Python and Ruby became very popular. Now that C# has the => syntax, people in my world (.NET) are talking about lamdba expressions more and more. I've read the Wikipedia article on the lambda calculus, but I'm not really a math guy. I don't really understand it from a practical perspective. When would I use lambda expressions? Why? How would I know that it's what I should be doing? Can you show examples of how you would solve problems with lambda expressions, in a before-and-after format? Any imperative language is fine, but C# would be easiest for me to understand. | Basically as far as C# is concerned, lambda expressions are an easy way to create a delegate (or an expression tree, but let's leave those aside for now). In C# 1 we could only create delegate instances from normal methods.In C# 2 we gained anonymous methods.In C# 3 we gained lambda expressions, which are like more concise anonymous methods. They're particularly concise when you want to express some logic which takes one value and returns a value. For instance, in the context of LINQ: // Only include children - a predicatevar query = dataSource.Where(person => person.Age < 18) // Transform to sequence of names - a projection .Select(person => person.Name); There's a fuller discussion of this - along with other aspects - in my article on closures . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
]
} |
187,438 | I have currently an installed pgsql instance that is running on port 1486 . I want to change this port to 5433 , how should I proceed for this? | There should be a line in your postgresql.conf file that says: port = 1486 Change that. The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/ On Windows it is C:\Program Files\PostgreSQL\9.3\data Don't forget to sudo service postgresql restart for changes to take effect. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/187438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22554/"
]
} |
187,453 | Would it suppose any difference regarding overhead to write an import loading all the types within one package ( import java.* ); than just a specific type (i.e. import java.lang.ClassLoader )? Would the second one be a more advisable way to use than the other one? | There is not a performance or overhead cost to doing import .* vs importing specific types. However, I consider it to be a best practice to never use import .* My primary reason for this is I just like to keep things straightward, clean and with as little ambiguity as possible, and I think with a .* import you lose that. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/187453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94303/"
]
} |
187,454 | I have the following problem using subversion: I'm currently working on the trunk of my project and plan to do some refactoring (which includes renaming files or moving files to different directories). At the same time someone else is working on the same project on a branch. At some time I want to merge the changes made on the branch back to the trunk. That includes changes made to files (on the branch) that have been renamed on the trunk. I did some tests and it seems that either subversion is not capable of following these changes or I'm missing someting (which is what I hope for). I tested this using the following script (should work in bash, assumes an svn repository at " http://myserver/svn/sandbox "): svn co http://myserver/svn/sandboxcd sandbox/mkdir -p MyProject/trunk MyProject/branches MyProject/tagscat - <<EOF >MyProject/trunk/FileOne.txtTest12EOFsvn add MyProjectsvn commit -m "init"# create a branchsvn copy http://myserver/svn/sandbox/MyProject/trunk http://myserver/svn/sandbox/MyProject/branches/Branch_1 svn copy http://myserver/svn/sandbox/MyProject/trunk http://myserver/svn/sandbox/MyProject/branches/Branch_1# rename the filesvn move MyProject/trunk/FileOne.txt MyProject/trunk/FileTwo.txtsvn commit -m "renamed file"svn update # change the content of FileOne in branchcat - <<EOF >MyProject/branches/Branch_1/FileOne.txtTest23EOFsvn commit -m "changed branch"# I now try to merge the changes in FileOne back to FileTwocd MyProject/trunk/svn merge -r1:HEAD http://myserver/svn/sandbox/MyProject/branches/Branch_1# but this yields the following message:# Skipped missing target: 'FileOne.txt' Any help is greatly appreciated. Edit: Perhaps the process suggested by mikegrb could by somewhat automated by first generating a map of renamed files (old->new) from the svn log command on the trunk: svn log -v------------------------------------------------------------------------r33 | sme | 2008-10-09 15:17:54 +0200 (Do, 09 Okt 2008) | 1 lineChanged paths: D /MyProject/trunk/FileOne.txt A /MyProject/trunk/FileTwo.txt (from /MyProject/trunk/FileOne.txt:31)resulting map: {FileOne.txt => FileTwo.txt} Now use this map to change filenames in the patch file generated on the branch. Original: Index: FileOne.txt===================================================================--- FileOne.txt (.../trunk) (revision 31)+++ FileOne.txt (.../branches/Branch_1) (revision 34)@@ -1,3 +1,3 @@ Test-1 2+3 modified: Index: FileTwo.txt===================================================================--- FileTwo.txt (.../trunk) (revision 31)+++ FileTwo.txt (.../branches/Branch_1) (revision 34)@@ -1,3 +1,3 @@ Test-1 2+3 Just an Idea, haven't done it yet. | I think this is an existing subversion bug - but don't hold your breath, its been open since 2002. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4497/"
]
} |
187,455 | How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string. | The method len() returns the number of elements in the list. Syntax: len(myArray) Eg: myArray = [1, 2, 3]len(myArray) Output: 3 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/187455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
187,474 | How is Oracle date implemented? Is it stored as milliseconds or something like that? | An Oracle DATE stores the date and time to the second. An Oracle TIMESTAMP stores the date and time to up to 9 digits of subsecond precision, depending on the available hardware. Both are implemented by storing the various components of the date and the time in a packed binary format. From the Oracle Concepts Guide section on dates Oracle uses its own internal format to store dates. Date data is stored in fixed-length fields of seven bytes each, corresponding to century, year, month, day, hour, minute, and second. You can use the DUMP() function to see the internal representation of any particular date (or any other value for that matter), but that's probably more than you need (or want) to know. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4235/"
]
} |
187,482 | I'd like to use the newer <button> tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button. The asp:Button control renders as <input type="button"> , is there any way to make a preexisting control render to <button> ? From what I've read there is an incompatibility with IE posting the button's markup instead of the value attribute when the button is located within a <form> , but in ASP.NET it will be using the onclick event to fire __doPostBack anyway, so I don't think that this would be a problem. Are there any reasons why I shouldn't use this? If not, how would you go about supporting it with asp:Button, or a new server control based on it? I would prefer to not write my own server control if that can be avoided. At first the <button runat="server"> solution worked, but I immediately ran into a situation where it needs to have a CommandName property, which the HtmlButton control doesn't have. It looks like I'm going to need to create a control inherited from Button after all. What do I need to do in order to override the render method and make it render what I want? UPDATE DanHerbert's reply has made me interested in finding a solution to this again, so I've spent some more time working on it. First, there's a far easier way of overloading the TagName: public ModernButton() : base(HtmlTextWriterTag.Button){} The problem with Dan's solution as it stands is the innerhtml of the tag is placed into the value property, which causes a validation error on postback. A related problem is, even if you render the value property correctly, IE's braindead implementation of the <button> tag posts the innerhtml instead of the value anyway. So, any implementation of this needs to override the AddAttributesToRender method in order to correctly render the value property, and also provide some sort of workaround for IE so it doesn't completely screw up the postback. The IE problem may be insurmountable if you want to take advantage of the CommandName/CommandArgument properties for a databound control. Hopefully someone can suggest a workaround for this. I have made progress on the rendering: ModernButton.cs This renders as a proper html <button> with the correct value, but it doesn't work with the ASP.Net PostBack system. I've written some of what I need to provide the Command event, but it doesn't fire. When inspecting this button side-by-side with a regular asp:Button, they look the same other than the differences I need. So I'm not sure how ASP.Net is wiring up the Command event in this case. An additional problem is, nested server controls aren't rendered (as you can see with the ParseChildren(false) attribute). It's pretty easy to inject literal html text into the control during render, but how do you allow support for nested server controls? | This is an old question, but for those of us unlucky enough still having to maintain ASP.NET Web Forms applications, I went through this myself while trying to include Bootstrap glyphs inside of built-in button controls. As per Bootstrap documentation, the desired markup is as follows: <button class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search</button> I needed this markup to be rendered by a server control, so I set out to find options. Button This would be the first logical step, but —as this question explains— Button renders an <input> element instead of <button> , so adding inner HTML is not possible. LinkButton (credit to Tsvetomir Tsonev's answer ) Source <asp:LinkButton runat="server" ID="uxSearch" CssClass="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search</asp:LinkButton> Output <a id="uxSearch" class="btn btn-default" href="javascript:__doPostBack('uxSearch','')"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search</a> Pros Looks OK Command event; CommandName and CommandArgument properties Cons Renders <a> instead of <button> Renders and relies on obtrusive JavaScript HtmlButton (credit to Philippe's answer ) Source <button runat="server" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search</button> Result <button onclick="__doPostBack('uxSearch','')" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search</button> Pros Looks OK Renders proper <button> element Cons No Command event; no CommandName or CommandArgument properties Renders and relies on obtrusive JavaScript to handle its ServerClick event At this point it is clear that none of the built-in controls seem suitable, so the next logical step is try and modify them to achieve the desired functionality. Custom control (credit to Dan Herbert's answer ) NOTE: This is based on Dan's code, so all credit goes to him. using System.Web.UI;using System.Web.UI.WebControls;namespace ModernControls{ [ParseChildren] public class ModernButton : Button { public new string Text { get { return (string)ViewState["NewText"] ?? ""; } set { ViewState["NewText"] = value; } } public string Value { get { return base.Text; } set { base.Text = value; } } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Button; } } protected override void AddParsedSubObject(object obj) { var literal = obj as LiteralControl; if (literal == null) return; Text = literal.Text; } protected override void RenderContents(HtmlTextWriter writer) { writer.Write(Text); } }} I have stripped the class down to the bare minimum, and refactored it to achieve the same functionality with as little code as possible. I also added a couple of improvements. Namely: Remove PersistChildren attribute (seems unnecessary) Remove TagName override (seems unnecessary) Remove HTML decoding from Text (base class already handles this) Leave OnPreRender intact; override AddParsedSubObject instead (simpler) Simplify RenderContents override Add a Value property (see below) Add a namespace (to include a sample of @ Register directive) Add necessary using directives The Value property simply accesses the old Text property. This is because the native Button control renders a value attribute anyway (with Text as its value). Since value is a valid attribute of the <button> element, I decided to include a property for it. Source <%@ Register TagPrefix="mc" Namespace="ModernControls" %><mc:ModernButton runat="server" ID="uxSearch" Value="Foo" CssClass="btn btn-default" > <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search</mc:ModernButton> Output <button type="submit" name="uxSearch" value="Foo" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search</button> Pros Looks OK Renders a proper <button> element Command event; CommandName and CommandArgument properties Does not render or rely on obtrusive JavaScript Cons None (other than not being a built-in control) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1249/"
]
} |
187,495 | In my program, how can I read the properties set in AssemblyInfo.cs: [assembly: AssemblyTitle("My Product")][assembly: AssemblyDescription("...")][assembly: AssemblyConfiguration("")][assembly: AssemblyCompany("Radeldudel inc.")][assembly: AssemblyProduct("My Product")][assembly: AssemblyCopyright("Copyright @ me 2008")][assembly: AssemblyTrademark("")][assembly: AssemblyCulture("")] I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using. | This is reasonably easy. You have to use reflection. You need an instance of Assembly that represents the assembly with the attributes you want to read. An easy way of getting this is to do: typeof(MyTypeInAssembly).Assembly Then you can do this, for example: object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);AssemblyProductAttribute attribute = null;if (attributes.Length > 0){ attribute = attributes[0] as AssemblyProductAttribute;} Referencing attribute.Product will now give you the value you passed to the attribute in your AssemblyInfo.cs. Of course, if the attribute you look for can occur more than once, you may get multiple instances in the array returned by GetCustomAttributes, but this is not usually an issue for assembly level attributes like the ones you hope to retrieve. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
]
} |
187,505 | I have few different applications among which I'd like to share a C# enum. I can't quite figure out how to share an enum declaration between a regular application and a WCF service. Here's the situation. I have 2 lightweight C# destop apps and a WCF webservice that all need to share enum values. Client 1 has Method1( MyEnum e, string sUserId ); Client 2 has Method2( MyEnum e, string sUserId ); Webservice has ServiceMethod1( MyEnum e, string sUserId, string sSomeData); My initial though was to create a library called Common.dll to encapsulate the enum and then just reference that library in all of the projects where the enum is needed. However, WCF makes things difficult because you need to markup the enum for it to be an integral part of the service. Like this: [ServiceContract][ServiceKnownType(typeof(MyEnum))]public interface IMyService{ [OperationContract] ServiceMethod1( MyEnum e, string sUserId, string sSomeData);}[DataContract]public enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue }; So .... Is there a way to share an enum among a WCF service and other applictions? | Using the Common library should be fine. Enumerations are serializable and the DataContract attributes are not needed. See: http://msdn.microsoft.com/en-us/library/ms731923.aspx Enumeration types. Enumerations, including flag enumerations, are serializable. Optionally, enumeration types can be marked with the DataContractAttribute attribute, in which case every member that participates in serialization must be marked with the EnumMemberAttribute attribute EDIT: Even so, there should be no issue with having the enum marked as a DataContract and having client libraries using it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5208/"
]
} |
187,506 | I'm involved with updating an Access solution. It has a good amount of VBA, a number of queries, a small amount of tables, and a few forms for data entry & report generation. It's an ideal candidate for Access. I want to make changes to the table design, the VBA, the queries, and the forms. How can I track my changes with version control? (we use Subversion, but this goes for any flavor) I can stick the entire mdb in subversion, but that will be storing a binary file, and I won't be able to tell that I just changed one line of VBA code. I thought about copying the VBA code to separate files, and saving those, but I could see those quickly getting out of sync with what's in the database. | We wrote our own script in VBScript, that uses the undocumented Application.SaveAsText() in Access to export all code, form, macro and report modules. Here it is, it should give you some pointers. (Beware: some of the messages are in german, but you can easily change that.) EDIT:To summarize various comments below: Our Project assumes an .adp-file. In order to get this work with .mdb/.accdb, you have to change OpenAccessProject() to OpenCurrentDatabase() . (Updated to use OpenAccessProject() if it sees a .adp extension, else use OpenCurrentDatabase() .) decompose.vbs: ' Usage:' CScript decompose.vbs <input file> <path>' Converts all modules, classes, forms and macros from an Access Project file (.adp) <input file> to' text and saves the results in separate files to <path>. Requires Microsoft Access.'Option Explicitconst acForm = 2const acModule = 5const acMacro = 4const acReport = 3' BEGIN CODEDim fsoSet fso = CreateObject("Scripting.FileSystemObject")dim sADPFilenameIf (WScript.Arguments.Count = 0) then MsgBox "Bitte den Dateinamen angeben!", vbExclamation, "Error" Wscript.Quit()End ifsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))Dim sExportpathIf (WScript.Arguments.Count = 1) then sExportpath = ""else sExportpath = WScript.Arguments(1)End IfexportModulesTxt sADPFilename, sExportpathIf (Err <> 0) and (Err.Description <> NULL) Then MsgBox Err.Description, vbExclamation, "Error" Err.ClearEnd IfFunction exportModulesTxt(sADPFilename, sExportpath) Dim myComponent Dim sModuleType Dim sTempname Dim sOutstring dim myType, myName, myPath, sStubADPFilename myType = fso.GetExtensionName(sADPFilename) myName = fso.GetBaseName(sADPFilename) myPath = fso.GetParentFolderName(sADPFilename) If (sExportpath = "") then sExportpath = myPath & "\Source\" End If sStubADPFilename = sExportpath & myName & "_stub." & myType WScript.Echo "copy stub to " & sStubADPFilename & "..." On Error Resume Next fso.CreateFolder(sExportpath) On Error Goto 0 fso.CopyFile sADPFilename, sStubADPFilename WScript.Echo "starting Access..." Dim oApplication Set oApplication = CreateObject("Access.Application") WScript.Echo "opening " & sStubADPFilename & " ..." If (Right(sStubADPFilename,4) = ".adp") Then oApplication.OpenAccessProject sStubADPFilename Else oApplication.OpenCurrentDatabase sStubADPFilename End If oApplication.Visible = false dim dctDelete Set dctDelete = CreateObject("Scripting.Dictionary") WScript.Echo "exporting..." Dim myObj For Each myObj In oApplication.CurrentProject.AllForms WScript.Echo " " & myObj.fullname oApplication.SaveAsText acForm, myObj.fullname, sExportpath & "\" & myObj.fullname & ".form" oApplication.DoCmd.Close acForm, myObj.fullname dctDelete.Add "FO" & myObj.fullname, acForm Next For Each myObj In oApplication.CurrentProject.AllModules WScript.Echo " " & myObj.fullname oApplication.SaveAsText acModule, myObj.fullname, sExportpath & "\" & myObj.fullname & ".bas" dctDelete.Add "MO" & myObj.fullname, acModule Next For Each myObj In oApplication.CurrentProject.AllMacros WScript.Echo " " & myObj.fullname oApplication.SaveAsText acMacro, myObj.fullname, sExportpath & "\" & myObj.fullname & ".mac" dctDelete.Add "MA" & myObj.fullname, acMacro Next For Each myObj In oApplication.CurrentProject.AllReports WScript.Echo " " & myObj.fullname oApplication.SaveAsText acReport, myObj.fullname, sExportpath & "\" & myObj.fullname & ".report" dctDelete.Add "RE" & myObj.fullname, acReport Next WScript.Echo "deleting..." dim sObjectname For Each sObjectname In dctDelete WScript.Echo " " & Mid(sObjectname, 3) oApplication.DoCmd.DeleteObject dctDelete(sObjectname), Mid(sObjectname, 3) Next oApplication.CloseCurrentDatabase oApplication.CompactRepair sStubADPFilename, sStubADPFilename & "_" oApplication.Quit fso.CopyFile sStubADPFilename & "_", sStubADPFilename fso.DeleteFile sStubADPFilename & "_"End FunctionPublic Function getErr() Dim strError strError = vbCrLf & "----------------------------------------------------------------------------------------------------------------------------------------" & vbCrLf & _ "From " & Err.source & ":" & vbCrLf & _ " Description: " & Err.Description & vbCrLf & _ " Code: " & Err.Number & vbCrLf getErr = strErrorEnd Function If you need a clickable Command, instead of using the command line, create a file named "decompose.cmd" with cscript decompose.vbs youraccessapplication.adp By default, all exported files go into a "Scripts" subfolder of your Access-application. The .adp/mdb file is also copied to this location (with a "stub" suffix) and stripped of all the exported modules, making it really small. You MUST checkin this stub with the source-files, because most access settings and custom menu-bars cannot be exported any other way. Just be sure to commit changes to this file only, if you really changed some setting or menu. Note: If you have any Autoexec-Makros defined in your Application, you may have to hold the Shift-key when you invoke the decompose to prevent it from executing and interfering with the export! Of course, there is also the reverse script, to build the Application from the "Source"-Directory: compose.vbs: ' Usage:' WScript compose.vbs <file> <path>' Converts all modules, classes, forms and macros in a directory created by "decompose.vbs"' and composes then into an Access Project file (.adp). This overwrites any existing Modules with the' same names without warning!!!' Requires Microsoft Access.Option Explicitconst acForm = 2const acModule = 5const acMacro = 4const acReport = 3Const acCmdCompileAndSaveAllModules = &H7E' BEGIN CODEDim fsoSet fso = CreateObject("Scripting.FileSystemObject")dim sADPFilenameIf (WScript.Arguments.Count = 0) then MsgBox "Please enter the file name!", vbExclamation, "Error" Wscript.Quit()End ifsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))Dim sPathIf (WScript.Arguments.Count = 1) then sPath = ""else sPath = WScript.Arguments(1)End IfimportModulesTxt sADPFilename, sPathIf (Err <> 0) and (Err.Description <> NULL) Then MsgBox Err.Description, vbExclamation, "Error" Err.ClearEnd IfFunction importModulesTxt(sADPFilename, sImportpath) Dim myComponent Dim sModuleType Dim sTempname Dim sOutstring ' Build file and pathnames dim myType, myName, myPath, sStubADPFilename myType = fso.GetExtensionName(sADPFilename) myName = fso.GetBaseName(sADPFilename) myPath = fso.GetParentFolderName(sADPFilename) ' if no path was given as argument, use a relative directory If (sImportpath = "") then sImportpath = myPath & "\Source\" End If sStubADPFilename = sImportpath & myName & "_stub." & myType ' check for existing file and ask to overwrite with the stub if (fso.FileExists(sADPFilename)) Then WScript.StdOut.Write sADPFilename & " exists. Overwrite? (y/n) " dim sInput sInput = WScript.StdIn.Read(1) if (sInput <> "y") Then WScript.Quit end if fso.CopyFile sADPFilename, sADPFilename & ".bak" end if fso.CopyFile sStubADPFilename, sADPFilename ' launch MSAccess WScript.Echo "starting Access..." Dim oApplication Set oApplication = CreateObject("Access.Application") WScript.Echo "opening " & sADPFilename & " ..." If (Right(sStubADPFilename,4) = ".adp") Then oApplication.OpenAccessProject sADPFilename Else oApplication.OpenCurrentDatabase sADPFilename End If oApplication.Visible = false Dim folder Set folder = fso.GetFolder(sImportpath) ' load each file from the import path into the stub Dim myFile, objectname, objecttype for each myFile in folder.Files objecttype = fso.GetExtensionName(myFile.Name) objectname = fso.GetBaseName(myFile.Name) WScript.Echo " " & objectname & " (" & objecttype & ")" if (objecttype = "form") then oApplication.LoadFromText acForm, objectname, myFile.Path elseif (objecttype = "bas") then oApplication.LoadFromText acModule, objectname, myFile.Path elseif (objecttype = "mac") then oApplication.LoadFromText acMacro, objectname, myFile.Path elseif (objecttype = "report") then oApplication.LoadFromText acReport, objectname, myFile.Path end if next oApplication.RunCommand acCmdCompileAndSaveAllModules oApplication.QuitEnd FunctionPublic Function getErr() Dim strError strError = vbCrLf & "----------------------------------------------------------------------------------------------------------------------------------------" & vbCrLf & _ "From " & Err.source & ":" & vbCrLf & _ " Description: " & Err.Description & vbCrLf & _ " Code: " & Err.Number & vbCrLf getErr = strErrorEnd Function Again, this goes with a companion "compose.cmd" containing: cscript compose.vbs youraccessapplication.adp It asks you to confirm overwriting your current application and first creates a backup, if you do. It then collects all source-files in the Source-Directory and re-inserts them into the stub. Have Fun! | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/187506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753/"
]
} |
187,531 | I have a package that I just made and I have an "old-mode" that basically makes it work like it worked before: importing everything into the current namespace. One of the nice things about having this as a package is that we no longer have to do that. Anyway, what I would like to do is have it so that whenever anyone does: use Foo qw(:oldmode); I throw a warning that this is deprecated and that they should either import only what they need or just access functions with Foo->fun(); Any ideas on how to do this? | Well, as you specifically state that you want to alarm in the cases of use Mod qw<:oldmode>; This works better: package Foo;use base qw<Exporter>;use Carp qw<carp>;...sub import { #if ( grep { $_ eq ':oldmode' } @_ ) { # Perl 5.8 if ( @_ ~~ ':oldmode' ) { # Perl 5.10 carp( 'import called with :oldmode!' ); } goto &{Exporter->can( 'import' )};} Thanks to Frew, for mentioning the Perl 5.10 smart match syntax. I'm learning all the ways to work Perl 5.10 into my code. Note: the standard way to use exporter in an import sub is to either manipulate $Exporter::ExportLevel or to call Foo->export_to_level( 1, @_ ); But I like the way above. It's quicker and, I think, simpler. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
]
} |
187,537 | Is there a case insensitive version of the :contains jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string? | What I ended up doing for jQuery 1.2 is : jQuery.extend( jQuery.expr[':'], { Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0" }); This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged. Edit: For jQuery 1.3 (thanks @user95227) and later you need jQuery.expr[':'].Contains = function(a,i,m){ return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;}; Edit: Apparently accessing the DOM directly by using (a.textContent || a.innerText || "") instead of jQuery(a).text() In the previous expression speeds it up considerably so try at your own risk if speed is an issue. (see @John 's question ) Latest edit: For jQuery 1.8 it should be: jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) { return function( elem ) { return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; };}); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/187537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
]
} |
187,552 | What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python? Thus far I've tried target = open(target_path, "w")conn = urllib.urlopen(stream_url)while True: target.write(conn.read(buf_size)) This gives me data but its garbled or wont play in mp3 players. | If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening target in binary mode: target = open(target_path, "wb") | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2906/"
]
} |
187,587 | I'm looking for the equivalent of the Unix 'tail' command that will allow me to watch the output of a log file while it is being written to. | If you use PowerShell then this works: Get-Content filenamehere -Wait -Tail 30 Posting Stefan's comment from below, so people don't miss it PowerShell 3 introduces a -Tail parameter to include only the last x lines | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/187587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445016/"
]
} |
187,594 | I'm doing some PHP work recently, and in all the code I've seen, people tend to use few methods. (They also tend to use few variables, but that's another issue.) I was wondering why this is, and I found this note "A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations" here . Is this true, even when the PHP page has been compiled and cached? Should I avoid using methods as much as possible for efficiency? I like to write well-organized, human-readable code with methods wherever a code block would be repeated. If it is necessary to write flat code without methods, are there any programs that will "inline" method bodies? That way I could write nice code and then ugly it up before deployment. By the way, the code I've been looking at is from the Joomla 1.5 core and several WordPress plugins, so I assume they are people who know what they're doing. Note: I'm pleased that everyone has jumped on this question to talk about optimization in general , but in fact we're talking about optimization in interpreted languages. At least some hint of the fact that we're talking about PHP would be nice. | I think Joomla and Wordpress are not the greatest examples of good PHP code, with no offense. I have nothing personal against the people working on it and it's great how they enable people to have a website/blog and I know that a lot of people spend all their free time on either of those projects but the code quality is rather poor (with no offense). Review security announcements over the past year if you don't believe me; also assuming you are looking for performance from either of the two, their code does not excel there either. So it's by no means good code, but Wordpress and Joomla both excel on the frontend - pretty easy to use, people get a website and can do stuff . And that's why they are so successful, people don't select them based on code quality but on what they enabled them to do. To answer your performance question, yes, it's true that all the good stuff (functions, classes, etc.) slow your application down. So I guess if your application/script is all in one file, so be it. Feel free to write bad PHP code then. As soon as you expand and start to duplicate code, you should consider the trade off (in speed) which writing maintainable code brings along. :-) IMHO this trade off is rather small because of two things: CPU is cheap. Developers are not cheap. When you need to go back into your code in six months from now, think if those nano seconds saved running it, still add up when you need to fix a nasty bug (three or four times, because of duplicated code). You can do all sorts of things to make PHP run faster. Generally people recommend a cache, such as APC . APC is really awesome. It runs all sorts of optimizations in the background for you, e.g. caching the bytecode of a PHP file and also provides you with functions in userland to save data. So for example if you parse a configuration file each time you run that script disk i/o is really critical. With a simple apc_store() and apc_fetch() you can store the parsed configuration file either in a file-based or a memory-based (RAM) cache and retrieve it from there until the cache expired or is deleted. APC is not the only cache, of course. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8047/"
]
} |
187,619 | I have headers in <h1> through <h6> tags. Is there a way that I can use JavaScript to generate a table of contents for the contents that serves as anchor tags as well? I would like the output to be something like: <ol> <li>Header 1</li> <li>Header 1</li> <li>Header 2</li> <li>Header 3</li></ol> I am not currently using a JavaScript framework, but I don't see why I couldn't use one. I am also looking for something done, since I'm guessing this is a common problem, but if not, a starting point to roll my own would be good. | I couldn't resist putting together a quick implementation. Add the following script anywhere on your page: window.onload = function () { var toc = ""; var level = 0; document.getElementById("contents").innerHTML = document.getElementById("contents").innerHTML.replace( /<h([\d])>([^<]+)<\/h([\d])>/gi, function (str, openLevel, titleText, closeLevel) { if (openLevel != closeLevel) { return str; } if (openLevel > level) { toc += (new Array(openLevel - level + 1)).join("<ul>"); } else if (openLevel < level) { toc += (new Array(level - openLevel + 1)).join("</ul>"); } level = parseInt(openLevel); var anchor = titleText.replace(/ /g, "_"); toc += "<li><a href=\"#" + anchor + "\">" + titleText + "</a></li>"; return "<h" + openLevel + "><a name=\"" + anchor + "\">" + titleText + "</a></h" + closeLevel + ">"; } ); if (level) { toc += (new Array(level + 1)).join("</ul>"); } document.getElementById("toc").innerHTML += toc;}; Your page should be structured something like this: <body> <div id="toc"> <h3>Table of Contents</h3> </div> <hr/> <div id="contents"> <h1>Fruits</h1> <h2>Red Fruits</h2> <h3>Apple</h3> <h3>Raspberry</h3> <h2>Orange Fruits</h2> <h3>Orange</h3> <h3>Tangerine</h3> <h1>Vegetables</h1> <h2>Vegetables Which Are Actually Fruits</h2> <h3>Tomato</h3> <h3>Eggplant</h3> </div></body> You can see it in action at https://codepen.io/scheinercc/pen/KEowRK (old link: http://magnetiq.com/exports/toc.htm (Works in IE, FF, Safari, Opera)) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
187,620 | Can a WinForms app compiled for "Any CPU" be configured to run as "x86" on a 64-bit server without recompiling the app? Specifically, I'm looking for an app.config setting or Control Panel applet to accomplish this end. All the customer's clients are x86, but the server is x64, and we like to install the WinForms app on the server for administrators to configure and monitor the system. We would much rather not recompile just for the server. | From http://www.request-response.com/blog/PermaLink,guid,34966ef8-3142-46b2-84e0-372b5c36ddcc.aspx You can, however, control and override this default behaviour even after your code has been compiled. There's a handy tool called corflags.exe present in the SDK that allows you to force 'anycpu' compiled code to use 32-bit process in 64-bit world. The usage of this utility is found here http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/187620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470/"
]
} |
187,621 | I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). Google shows many hits for explanations on how to do this. Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python. My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key). I do not need it to work on windows or mac, just linux. | Use Python's readline bindings. For example, import readlinedef completer(text, state): options = [i for i in commands if i.startswith(text)] if state < len(options): return options[state] else: return Nonereadline.parse_and_bind("tab: complete")readline.set_completer(completer) The official module docs aren't much more detailed, see the readline docs for more info. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045/"
]
} |
187,629 | I'm looking at maybe moving from an older AMD64 to a new Intel dual-core which is 32 bit. Installation isn't a problem but can I transfer all the installed apps? I haven't beenable to find anything so far on Google except where the migration is to a similar platform and file-system. I won't change the filesystem but the platform will be different. Is there something on the lines of the "World" file in Gentoo? | You can save your list of packages easily: see "man dpkg" and search for --set-selections and --get-selections. The basic of it, though is that to save the list of packages: dpkg --get-selections > package_list To restore that list on another system: cat package_list | sudo dpkg --set-selections && sudo apt-get dselect-upgrade Moving across architectures means that there will be some packages unavailable. They will be ignored; for example, ia32-libs will not be installable on a 32-bit system. That selection will be ignored if you're moving from x86-64 to x86. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5549/"
]
} |
187,640 | Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example: // Use this...class foo {private: std::string name_; unsigned int age_;public: foo(const std::string& name = "", const unsigned int age = 0) : name_(name), age_(age) { ... }};// Or this?class foo {private: std::string name_; unsigned int age_;public: foo() : name_(""), age_(0){}foo(const std::string& name, const unsigned int age) : name_(name), age_(age) { ... }}; Either version seems to work, e.g.: foo f1;foo f2("Name", 30); Which style do you prefer or recommend and why? | Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor. One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out this thread for more info. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/187640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
} |
187,655 | When sending data over HTTPS, I know the content is encrypted, however I hear mixed answers about whether the headers are encrypted, or how much of the header is encrypted. How much of HTTPS headers are encrypted? Including GET/POST request URLs, Cookies, etc. | All the HTTP headers are encrypted † .That's why SSL on vhosts doesn't work too well - you need a dedicated IP address because the Host header is encrypted. † The Server Name Identification (SNI) standard means that the hostname may not be encrypted if you're using TLS. Also, whether you're using SNI or not, the TCP and IP headers are never encrypted. (If they were, your packets would not be routable.) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/187655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
187,676 | I know this is a bit of a newbie question, but are there equivalents to C#'s string operations in Java? Specifically, I'm talking about String.Format and String.Join . | The Java String object has a format method (as of 1.5), but no join method. To get a bunch of useful String utility methods not already included you could use org.apache.commons.lang.StringUtils . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/187676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
]
} |
187,713 | In C++, what's the generic way to convert any floating point value (float) to fixed point (int, 16:16 or 24:8)? EDIT: For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type. Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts. I hope that clears things up. | Here you go: // A signed fixed-point 16:16 classclass FixedPoint_16_16{ short intPart; unsigned short fracPart;public: FixedPoint_16_16(double d) { *this = d; // calls operator= } FixedPoint_16_16& operator=(double d) { intPart = static_cast<short>(d); fracPart = static_cast<unsigned short> (numeric_limits<unsigned short> + 1.0)*d); return *this; } // Other operators can be defined here}; EDIT: Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out): template <class BaseType, size_t FracDigits>class fixed_point{ const static BaseType factor = 1 << FracDigits; BaseType data;public: fixed_point(double d) { *this = d; // calls operator= } fixed_point& operator=(double d) { data = static_cast<BaseType>(d*factor); return *this; } BaseType raw_data() const { return data; } // Other operators can be defined here};fixed_point<int, 8> fp1; // Will be signed 24:8 (if int is 32-bits)fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
]
} |
187,736 | I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument. That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP? Bonus points for doing it in pure PHP (no system('stty') ) and replacing the characters with * . EDIT: The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that. Also, for the record, the stty way of doing it is: echo "Password: ";system('stty -echo');$password = trim(fgets(STDIN));system('stty echo');// add a new line since the users CR didn't echoecho "\n"; I'd prefer to not have the system() calls in there. | Found on sitepoint . function prompt_silent($prompt = "Enter Password:") { if (preg_match('/^win/i', PHP_OS)) { $vbscript = sys_get_temp_dir() . 'prompt_password.vbs'; file_put_contents( $vbscript, 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))'); $command = "cscript //nologo " . escapeshellarg($vbscript); $password = rtrim(shell_exec($command)); unlink($vbscript); return $password; } else { $command = "/usr/bin/env bash -c 'echo OK'"; if (rtrim(shell_exec($command)) !== 'OK') { trigger_error("Can't invoke bash"); return; } $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'"; $password = rtrim(shell_exec($command)); echo "\n"; return $password; }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506/"
]
} |
187,761 | POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won't deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also support recursive mutexes, but if they want to be POSIX conform, they have to . Other APIs (more high level APIs) also usually offer mutexes, often called Locks. Some systems/languages (e.g. Cocoa Objective-C) offer both, recursive and non recursive mutexes. Some languages also only offer one or the other one. E.g. in Java mutexes are always recursive (the same thread may twice "synchronize" on the same object). Depending on what other thread functionality they offer, not having recursive mutexes might be no problem, as they can easily be written yourself (I already implemented recursive mutexes myself on the basis of more simple mutex/condition operations). What I don't really understand: What are non-recursive mutexes good for? Why would I want to have a thread deadlock if it locks the same mutex twice? Even high level languages that could avoid that (e.g. testing if this will deadlock and throwing an exception if it does) usually don't do that. They will let the thread deadlock instead. Is this only for cases, where I accidentally lock it twice and only unlock it once and in case of a recursive mutex, it would be harder to find the problem, so instead I have it deadlock immediately to see where the incorrect lock appears? But couldn't I do the same with having a lock counter returned when unlocking and in a situation, where I'm sure I released the last lock and the counter is not zero, I can throw an exception or log the problem? Or is there any other, more useful use-case of non recursive mutexes that I fail to see? Or is it maybe just performance, as a non-recursive mutex can be slightly faster than a recursive one? However, I tested this and the difference is really not that big. | The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it. However , there are other considerations at play here too. Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads. Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership). If you refer to classic VxWorks RTOS kernel, they define three mechanisms: mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner. binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads. counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero. Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/187761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15809/"
]
} |
187,768 | I've created a copy utility in c# (.NET 2.0 Framework) that copies files, directories and recursive sub directories etc. The program has a GUI that shows the current file being copied, the current file number (sequence), the total number of files to be copied and the percentage completed for the copy operations. There is also a progress bar, that is based on current file / total files. My problem is related to copying large files. I've been unable to find a way to indicate the total copy progress of a large file (using my current class structure that utilitzes FileInfo.CopyTo method). As a workaround I've separated the file copy operations and GUI display to their own threads and set up a visual cue to show that work is being done. At least the user is aware that the program isn't frozen and is still copying files. It would be nicer to be able to show the progress based on the total number of bytes or have some type of event that fires from the FileInfo.CopyTo method that indicates the total number of bytes copied from the current file. I'm aware of the FileInfo.Length property, so I'm sure there is a way MacGuyver my own event that is based on this and have a handler on the GUI side of things reading the updates (maybe based on checking the FileInfo.Length property of the destination object using some type of timer?). Does anyone know of a way to do this that I'm overlooking. If I can avoid it, I'd rather not rewrite my class to copy bytes through a stream and track it that way (though I'm thinking I might be stuck with going that route). PS - I'm stuck with the .NET 2.0 framework for now, so any solution that requires features available in >= 3.0 only are not an option for me. PPS - I'm open to solutions in any .NET language variety, not only c#. | The FileInfo.CopyTo is basically a wrapper around the Win32 API call "CopyFile" in the kernel32.dll. This method does not support progress callback. However, the CopyFileEx method does, and you can write your own .NET wrapper around it in a few minutes, like it is described here: http://www.pinvoke.net/default.aspx/kernel32.CopyFileEx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9732/"
]
} |
187,770 | I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this? | On SQL Server? and on the same database server? Use three part naming. INSERT INTO bar..tblFoobar( *fieldlist* )SELECT *fieldlist* FROM foo..tblFoobar This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/187770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
]
} |
187,777 | How can I get the BSSID / MAC (Media Access Control) address of the wireless access point my system is connected to using C#? Note that I'm interested in the BSSID of the WAP. This is different from the MAC address of the networking portion of the WAP. | The following needs to be executed programmatically: netsh wlan show networks mode=Bssid | findstr "BSSID" The above shows the access point's wireless MAC addresses which is different from: arp -a | findstr 192.168.1.254 This is because the access point has 2 MAC addresses. One for the wireless device and one for the networking device. I want the wireless MAC but get the networking MAC using arp . Using the Managed Wifi API : var wlanClient = new WlanClient();foreach (WlanClient.WlanInterface wlanInterface in wlanClient.Interfaces){ Wlan.WlanBssEntry[] wlanBssEntries = wlanInterface.GetNetworkBssList(); foreach (Wlan.WlanBssEntry wlanBssEntry in wlanBssEntries) { byte[] macAddr = wlanBssEntry.dot11Bssid; var macAddrLen = (uint) macAddr.Length; var str = new string[(int) macAddrLen]; for (int i = 0; i < macAddrLen; i++) { str[i] = macAddr[i].ToString("x2"); } string mac = string.Join("", str); Console.WriteLine(mac); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5993/"
]
} |
187,779 | Is it possible to update IIS on Windows XP from 5.1 to 6? If so how? Thanks. | No, it is not possible. The version of IIS is tied to a specific version of Windows. XP = IIS 5.12003 = IIS 62008 = IIS 7 More information available at http://support.microsoft.com/kb/224609 . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12148/"
]
} |
187,827 | So for this one project, we have a bunch of queries that are executed on a regular basis (every minute or so. I used the "Analyze Query in Database Engine " to check on them. They are pretty simple:select * from tablex where processed='0' There is an index on processed, and each query should return <1000 rows on a table with 1MM records. The Analyzer recommended creating some STATISTICS on this.... So my question is: What are those statistics ? do they really help performance ? how costly are they for a table like above ? Please bear in mind that by no means I would call myself a SQL Server experienced user ... And this is the first time using this Analyzer. | Statistics are what SQL Server uses to determine the viability of how to get data. Let's say, for instance, that you have a table that only has a clustered index on the primary key. When you execute SELECT * FROM tablename WHERE col1=value , SQL Server only has one option, to scan every row in the table to find the matching rows. Now we add an index on col1 so you assume that SQL Server will use the index to find the matching rows, but that's not always true. Let's say that the table has 200,000 rows and col1 only has 2 values: 1 and 0. When SQL Server uses an index to find data, the index contains pointers back to the clustered index position. Given there's only two values in the indexed column, SQL Server decides it makes more sense to just scan the table because using the index would be more work. Now we'll add another 800,000 rows of data to the table, but this time the values in col1 are widely varied. Now it's a useful index because SQL Server can viably use the index to limit what it needs to pull out of the table. Will SQL Server use the index? It depends. And what it depends on are the Statistics. At some point in time, with AUTO UPDATE STATISTICS set on, the server will update the statistics for the index and know it's a very good and valid index to use. Until that point, however, it will ignore the index as being irrelevant. That's one use of statistics. But there is another use and that isn't related to indices. SQL Server keeps basic statistics about all of the columns in a table. If there's enough different data to make it worthwhile, SQL Server will actually create a temporary index on a column and use that to filter. While this takes more time than using an existing index, it takes less time than a full table scan. Sometimes you will get recommendations to create specific statistics on columns that would be useful for that. These aren't indices, but the do keep track of the statistical sampling of data in the column so SQL Server can determine whether it makes sense to create a temporary index to return data. HTH | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23238/"
]
} |
187,836 | Sometimes while debugging, I need to restart a service on a remote machine. Currently, I'm doing this via Remote Desktop. How can it be done from the command line on my local machine? | You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu. If you wish to use the command line only, you can use sc \\machine stop <service> | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/187836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
]
} |
187,886 | I need to grant select permission for all tables owned by a specific user to another user. Can I do this with a single command along the lines of: Grant Select on OwningUser.* to ReceivingUser Or do I have to generate the sql for each table with something along the lines of: Select 'GRANT SELECT ON OwningUser.'||Table_Name||'TO ReceivingUser' From All_Tables Where Owner='OWNINGUSER' | Well, it's not a single statement, but it's about as close as you can get with oracle: BEGIN FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser'; END LOOP;END; | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/187886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
]
} |
187,894 | From C#, I want to do the equivalent of the following: arp -a |findstr 192.168.1.254 Alternatively, the answer could call the SendARP function and get the results. This will allow my application to do some other processing that requires the MAC address. | SendARP P/Invoke goes like this: [DllImport("iphlpapi.dll", ExactSpelling=true)]public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen ); PInvoke.NET has this example: IPAddress dst = IPAddress.Parse("192.168.2.1"); // the destination IP addressbyte[] macAddr = new byte[6];uint macAddrLen = (uint)macAddr.Length;if (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0) throw new InvalidOperationException("SendARP failed.");string[] str = new string[(int)macAddrLen];for (int i=0; i<macAddrLen; i++) str[i] = macAddr[i].ToString("x2");Console.WriteLine(string.Join(":", str)); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/187894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5993/"
]
} |
187,913 | What I'd like to avoid: ManagementClass m = new ManagementClass("Win32_LogicalDisk");ManagementObjectCollection managementObjects = m.GetInstances();List<ManagementObject> managementList = new List<ManagementObject>();foreach(ManagementObject m in managementObjects){ managementList.Add(m);} Isn't there a way to get that collection into a List that looks something like: List<ManagementObject> managementList = new List<ManagementObjec>(collection_array); | What version of the framework? With 3.5 you could presumably use: List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList(); (edited to remove simpler version; I checked and ManagementObjectCollection only implements the non-generic IEnumerable form) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/187913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.