source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
183,780 | What would you consider best practice for organizing JUnit tests in a project, and why? For example, do you keep your tests next to the classes they test? Do you put them in a separate but parallel package structure? Do you use a different organization strategy entirely? | I use a separate but parallel package structure for several reasons. It keeps tests organized the same way as the application code. I can easily build just the application files for distribution. Test code still has access to my application code. It's not as cluttered as having test code mixed with application code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/183780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4287/"
]
} |
183,788 | I've worked on many projects where I've been given code by others to update. More often than not I compile it and get about 1,000+ compiler warnings. When I see compiler warnings they make me feel dirty, so my first task is to clean up the code and remove them all. Typically I find about a dozen problems like uninitialized variables such. I don't understand why people leave them in and don't have perfectly clean compiles with no warnings. Am I missing something? Is there any valid reason to just leave them? Any horror stories to share? | I would clean up any warning. Even the ones that you know are harmless (if such a thing exists) will give a bad impression of you to whoever will compile the code. It one of the "smelly" signs I would look for if I had to work on someone else code. If not real errors or potential future issues, it would be a sign of sloppiness | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/183788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
]
} |
183,791 | I have two collections which have property Email in both collections. I need to get a list of the items in the first list where Email does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done? So far I have a join, like... var matches = from item1 in list1join item2 in list2 on item1.Email equals item2.Emailselect new { Email = list1.Email }; But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet. | I don't know if this will help you but.. NorthwindDataContext dc = new NorthwindDataContext(); dc.Log = Console.Out;var query = from c in dc.Customers where !(from o in dc.Orders select o.CustomerID) .Contains(c.CustomerID) select c;foreach (var c in query) Console.WriteLine( c ); from The NOT IN clause in LINQ to SQL by Marco Russo | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/183791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
]
} |
183,831 | JPEG, GIF and PNG can be displayed with the img tag and will work in all browsers, the object element can be use for displaying images specifying its MIME type, but what other graphic formats are supported by img or object tag in most browsers without installing plugins? (TIF, SVG, PCX, PICT, etc..) | There's an excellent chart on wikipedia that lists common image types and their support by browser. The file types you listed (jpg, gif and png) seem to be the main formats supported by nearly every browser, albeit with certain caveats: Internet Explorer supports PNG images but is unable to correctly display images with gamma correction or color correction. Versions of Internet Explorer prior to version 7 are unable to correctly display images with alpha channel (for transparency) without additional coding | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/183831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25578/"
]
} |
183,853 | Is there a benefit to using one over the other? In Python 2, they both seem to return the same results: >>> 6/32>>> 6//32 | In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2 . The former is floating point division, and the latter is floor division , sometimes also called integer division . In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division , which causes Python 2.x to adopt the 3.x behavior. Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation. You can find a detailed description at PEP 238: Changing the Division Operator . | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/183853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
183,859 | Our base Masterpage has something like the following <head runat="server"> <title></title> <script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/actions.js")%>"></script> <script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></script> <asp:contentplaceholder id="cph_htmlhead" runat="server"> </asp:contentplaceholder> </head> If this Masterpage is the Masterpage for an ASPX page things work fine. If this Masterpage is the Masterpage for a child Masterpage and then a new ASPX page uses the child Masterpage as it's MasterPage we see: Server Error in '' Application. The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>). What is the preferred way to include global resources (Javascript/CSS) in a base Masterpage preserving tilde(~) style relative pathing? | Use the ScriptManager server control: <asp:ScriptManager ID="myScriptManager" runat="server"> <Scripts> <asp:ScriptReference Path = "~/javascript/actions.js" /> <asp:ScriptReference Path = "~/javascript/jquery/jquery-1.2.6.min.js" /> </Scripts> </asp:ScriptManager> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/183859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439/"
]
} |
183,881 | I'm working on a home project that involves comparing images to a database of images (using a quadrant - or so - histogram approach). I wanted to know what my options are in regards to web cams or other image capture devices that: Are easy to work with with theWindows SDK (particularly DirectShow , which I plan to usewith C#) Have drivers for both64-bit and 32-bit Windows Vista (andServer 2008) I'm asking primarily so I can avoid pitfalls that other people may have experienced with web cams and to see if there are other image capture devices (or C# usable APIs) available that I should look at. I suspect that any old web cam will do but I'd rather be safe than sorry. | Use the ScriptManager server control: <asp:ScriptManager ID="myScriptManager" runat="server"> <Scripts> <asp:ScriptReference Path = "~/javascript/actions.js" /> <asp:ScriptReference Path = "~/javascript/jquery/jquery-1.2.6.min.js" /> </Scripts> </asp:ScriptManager> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/183881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645/"
]
} |
183,898 | How do I do forward referencing / declaration in C++ to avoid circular header file references? I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how. | You predeclare the class without including it. For example: //#include "Foo.h" // including Foo.h causes circular referenceclass Foo;class Bar{...}; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/183898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
]
} |
183,901 | Is there a way to start PowerShell in a specific folder from Windows Explorer, e.g. to right-click in a folder and have an option like "Open PowerShell in this Folder"? It's really annoying to have to change directories to my project folder the first time I run MSBuild every day. | In Windows Explorer, just go to the Address Bar at the top (keyboard shortcuts: Alt + D or Ctrl + L ) and type powershell or powershell_ise and press Enter . A PowerShell command window opens with the current directory. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/183901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
]
} |
183,907 | Say you've loaded a text file into a string, and you'd like to convert all Unicode escapes into actual Unicode characters inside of the string. Example: "The following is the top half of an integral character in Unicode '\u2320', and this is the lower half '\U2321'." | The answer is simple and works well with strings up to at least several thousand characters. Example 1: Regex rx = new Regex( @"\\[uU]([0-9A-F]{4})" );result = rx.Replace( result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString() ); Example 2: Regex rx = new Regex( @"\\[uU]([0-9A-F]{4})" );result = rx.Replace( result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); } ); The first example shows the replacement being made using a lambda expression (C# 3.0) and the second uses a delegate which should work with C# 2.0. To break down what's going on here, first we create a regular expression: new Regex( @"\\[uU]([0-9A-F]{4})" ); Then we call Replace() with the string 'result' and an anonymous method (lambda expression in the first example and the delegate in the second - the delegate could also be a regular method) that converts each regular expression that is found in the string. The Unicode escape is processed like this: ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); }); Get the string representing the number part of the escape (skip the first two characters). match.Value.Substring(2) Parse that string using Int32.Parse() which takes the string and the number format that the Parse() function should expect which in this case is a hex number. NumberStyles.HexNumber Then we cast the resulting number to a Unicode character: (char) And finally we call ToString() on the Unicode character which gives us its string representation which is the value passed back to Replace(): .ToString() Note: Instead of grabbing the text to be converted with a Substring call you could use the match parameter's GroupCollection, and a subexpressions in the regular expression to capture just the number ('2320'), but that's more complicated and less readable. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/183907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2415/"
]
} |
183,914 | echo $_POST["name"]; //returns the value a user typed into the "name" field I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this? | Check out the array_keys() function assuming this is PHP. http://us2.php.net/array_keys | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/183914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
]
} |
183,928 | How do I create subdomain like http://user.mywebsite.example ? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language? To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access? | You're looking to create a custom A record . I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this: *.mywebsite.example IN A 127.0.0.1 127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host. Then you need to configure your web-server to serve all subdomains. Nginx: server_name .mywebsite.example Apache: ServerAlias *.mywebsite.example Regarding .htaccess, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like $username = strtok($_SERVER['HTTP_HOST'], "."); If you don't have access to DNS/web-server config, doing it like http://mywebsite.example/user would be a lot easier to set up if it's an option. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/183928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
]
} |
183,950 | I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code. protected override void CreateChildControls(){ if (ScriptManager.GetCurrent(Page) == null) { ScriptManager sMgr = new ScriptManager(); // Ensure the ScriptManager is the first control. Page.Form.Controls.AddAt(0, sMgr); }} However, when this code is executed, I get the following error message: "The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases." Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart? | I was able to get this to work by using the Page's Init event: protected override void OnInit(EventArgs e){ Page.Init += delegate(object sender, EventArgs e_Init) { if (ScriptManager.GetCurrent(Page) == null) { ScriptManager sMgr = new ScriptManager(); Page.Form.Controls.AddAt(0, sMgr); } }; base.OnInit(e);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/183950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21461/"
]
} |
183,953 | I'm trying to determine how to open/edit existing SQL Server Reporting Services (SSRS) 2005 report projects (.rptproj) and reports (.rdl) with Visual Studio 2008, without having to install SQL Business Intelligence Development Studio (BIDS) 2005. | You cannot. Check this forum posting which has a reponse from Microsoft. Yes, it was an active decision that the 2008 design evironments would not support continuous backwards compatability but would rather be a one way upgrade. This was not a casual decision and it is understood how it can be an impact. You can read the entire posting for more details on why you are unable to use VS2008 for SSRS 2005 projects. Very annoying, but I guess I can understand why they had to make that decision. Just about the only reason I have VS2005 on my dev machine now is for Reporting Services projects since our company is not going to be upgrading to SQL Server 2008 anytime soon. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/183953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5487/"
]
} |
184,002 | In the following piece of code (taken from the Groovy Semantics Manual page ), why prefix the assignment with the keyword def ? def x = 0def y = 5while ( y-- > 0 ) { println "" + x + " " + y x++}assert x == 5 The def keyword can be removed, and this snippet would produce the same results. So what's the effect of the keyword def ? | It's syntactic sugar for basic scripts. Omitting the "def" keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable: x = 1assert x == 1assert this.binding.getVariable("x") == 1 Using the def keyword instead does not put the variable in the scripts bindings: def y = 2assert y == 2try { this.binding.getVariable("y") } catch (groovy.lang.MissingPropertyException e) { println "error caught"} Prints: "error caught" Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation. If you define a method in your script, it won't have access to the variables that are created with "def" in the body of the main script as they aren't in scope: x = 1 def y = 2public bar() { assert x == 1 try { assert y == 2 } catch (groovy.lang.MissingPropertyException e) { println "error caught" }}bar() prints "error caught" The "y" variable isn't in scope inside the function. "x" is in scope as groovy will check the bindings of the current script for the variable. As I said earlier, this is simply syntactic sugar to make quick and dirty scripts quicker to type out (often one liners). Good practice in larger scripts is to always use the "def" keyword so you don't run into strange scoping issues or interfere with variables you don't intend to. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/184002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
]
} |
184,060 | I'm not looking for java-web-start, I'm looking for a thick-client application installation toolkit. I've got a stand-alone application that consists of several files (jar files, data files, etc) and would need to do some pretty standard installation tasks, like asking the user for target directories, have them locate some parts of their system - choose some of the per-machine or per-user configuration options and possibly try to detect some of the machine settings for them. I'm looking for something which is like the MSI or other wizard driven installation applications. What's a good installer for Java? It would be ideal if it were cross-platform capable (Linux, Mac OSX and Windows). | Not an MSI-Installer but crossplatform: izPack It's xml-file based with it's own GUI or ant task (whtaever you prefer) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
} |
184,071 | Some people claim that code's worst enemy is its size, and I tend to agree. Yet every day you keep hearing things like I write blah lines of code in a day. I own x lines of code. Windows is x million lines of code. Question: When is "#lines of code" useful? ps: Note that when such statements are made, the tone is "more is better". | I'd say it's when you're removing code to make the project run better. Saying you removed "X number of lines" is impressive. And far more helpful than you added lines of code. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15071/"
]
} |
184,084 | Possible Duplicate: What is the correct way to create a single instance application? How to force C# .net app to run only one instance in Windows? | I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded using System.Threading;[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)]static extern bool SetForegroundWindow(IntPtr hWnd);/// <summary>/// The main entry point for the application./// </summary>[STAThread]static void Main(){ bool createdNew = true; using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316/"
]
} |
184,112 | Any salt at all will obviously help when salting and hashing a user's password. Are there any best practices for how long the salt should be? I'll be storing the salt in my user table, so I would like the best tradeoff between storage size and security. Is a random 10 character salt enough? Or do I need something longer? | Most of these answers are a bit misguided and demonstrate a confusion between salts and cryptographic keys. The purpose of including salts is to modify the function used to hash each user's password so that each stored password hash will have to be attacked individually. The only security requirement is that they are unique per user, there is no benefit in them being unpredictable or difficult to guess. Salts only need to be long enough so that each user's salt will be unique. Random 64-bit salts are very unlikely to ever repeat even with a billion registered users, so this should be fine. A singly repeated salt is a relatively minor security concern, it allows an attacker to search two accounts at once but in the aggregate won't speed up the search much on the whole database. Even 32-bit salts are acceptable for most purposes, it will in the worst case speed an attacker's search by about 58%. The cost of increasing salts beyond 64 bits isn't high but there is no security reason to do so. There is some benefit to also using a site-wide salt on top of the per-user salt, this will prevent possible collisions with password hashes stored at other sites, and prevent the use of general-purpose rainbow tables, although even 32 bits of salt is enough to make rainbow tables an impractical attack. Even simpler-and developers always overlook this-if you have unique user IDs or login names, those serve perfectly fine as a salt. If you do this, you should add a site-wide salt to ensure you don't overlap with users of another system who had the same bright idea. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351/"
]
} |
184,147 | Is there any advantage of using java.util.concurrent.CountdownLatch instead of java.util.concurrent.Semaphore ? As far as I can tell the following fragments are almost equivalent: 1. Semaphore final Semaphore sem = new Semaphore(0);for (int i = 0; i < num_threads; ++ i){ Thread t = new Thread() { public void run() { try { doStuff(); } finally { sem.release(); } } }; t.start();}sem.acquire(num_threads); 2: CountDownLatch final CountDownLatch latch = new CountDownLatch(num_threads);for (int i = 0; i < num_threads; ++ i){ Thread t = new Thread() { public void run() { try { doStuff(); } finally { latch.countDown(); } } }; t.start();}latch.await(); Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.) So in what situation might the latch be preferable? | CountDownLatch is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on await() that would all start simultaneously when the countown reached zero. final CountDownLatch countdown = new CountDownLatch(1);for (int i = 0; i < 10; ++ i) { Thread racecar = new Thread() { public void run() { countdown.await(); //all threads waiting System.out.println("Vroom!"); } }; racecar.start();}System.out.println("Go");countdown.countDown(); //all threads start now! You could also use this as an MPI-style "barrier" that causes all threads to wait for other threads to catch up to a certain point before proceeding. final CountDownLatch countdown = new CountDownLatch(num_thread);for (int i = 0; i < num_thread; ++ i) { Thread t= new Thread() { public void run() { doSomething(); countdown.countDown(); System.out.printf("Waiting on %d other threads.",countdown.getCount()); countdown.await(); //waits until everyone reaches this point finish(); } }; t.start();} That all said, the CountDownLatch can safely be used in the manner you've shown in your example. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/184147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12048/"
]
} |
184,178 | I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field. Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it. Net::HTTP doesn't look like the best idea. curb is looking good. | I like RestClient . It encapsulates net/http with cool features like multipart form data: require 'rest_client'RestClient.post('http://localhost:3000/foo', :name_of_file_param => File.new('/path/to/file')) It also supports streaming. gem install rest-client will get you started. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/184178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
]
} |
184,187 | I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. | Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms: http://www.perforce.com/perforce/loadsupp.html#api You will find their documentation of the scripting API to be helpful: http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf Use of the Python API is quite similar to the command-line client: PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.>>> import P4>>> p4 = P4.P4()>>> p4.connect() # connect to the default server, with the default clientspec>>> desc = {"Description": "My new changelist description",... "Change": "new"... }>>> p4.input = desc>>> p4.run("changelist", "-i")['Change 2579505 created.']>>> I'll verify it from the command line: P:\>p4 changelist -o 2579505# A Perforce Change Specification.## Change: The change number. 'new' on a new changelist.# Date: The date this specification was last modified.# Client: The client on which the changelist was created. Read-only.# User: The user who created the changelist.# Status: Either 'pending' or 'submitted'. Read-only.# Description: Comments about the changelist. Required.# Jobs: What opened jobs are to be closed by this changelist.# You may delete jobs from this list. (New changelists only.)# Files: What opened files from the default changelist are to be added# to this changelist. You may delete files from this list.# (New changelists only.)Change: 2579505Date: 2008/10/08 13:57:02Client: MYCOMPUTER-DTUser: myusernameStatus: pendingDescription: My new changelist description | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852/"
]
} |
184,272 | What exactly does the word patch mean when referring to 'submitting a patch'? I've seen this used a lot, especially in the open source world. What what does it mean and what exactly is involved in submitting a patch? | It's a file with a list of differences between the code files that have changed. It's usually in the format generated by doing a diff -u on the two files. Most version control systems allow the easy creation of patches but it's generally in that same format. This allows the code change to be easily applied to someone else's copy of the source code using the patch command. For example: Let's say I have the following code: <?php $foo = 0;?> and I change it to this: <?php $bar = 0;?> The patch file might look like this: Index: test.php===================================================================--- test.php (revision 40)+++ test.php (working copy)@@ -3,7 +3,7 @@ <?php- $foo = 0;+ $bar= 0; ?> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
]
} |
184,309 | I know there are libraries out there for working with ZIP files . And, you can alternatively use the functionality built into Windows for working ZIP files . But, I'm wondering if anyone has worked out how to use the tools built into the System.IO.Compression namespace within .NET for reading/writing ZIP files? Or, is it not possible using only this namespace? UPDATED: I've seem someone comment that the System.IO.Packaging namespace might be usefull with this also. Does anyone know exactly how to do it? | MSDN has a complete example http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx using the ZipPackage class. Requires .NET 3.5. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
]
} |
184,312 | I am building Java web applications, and I hate the traditional "code-compile-deploy-test" cycle. I want to type in one tiny change, then see the result INSTANTLY, without having to compile and deploy. Fortunately, Jetty is great for this. It is a pure-java web server. It comes with a really nice maven plugin which lets you launch Jetty reading directly from your build tree -- no need to package a war file or deploy. It even has a scanInterval setting: put this to a non-zero value and it will watch your java files and various config files for changes and automatically re-deploy a few seconds after you make a change. There's just one thing keeping me from nirvana. I have javascript and css files in my src/main/webapp directory which just get served up by Jetty. I would like to be able to edit these and have the changes show up when I refresh the page in the browser. Unfortunately, Jetty holds these files open so I can't (on Windows) modify them while it is running. Does anyone know how to make Jetty let go of these files so I can edit them, then serve up the edited files for subsequent requests? | Jetty uses memory-mapped files to buffer static content, which causes the file-locking in Windows. Try setting useFileMappedBuffer for DefaultServlet to false . Troubleshooting Locked files on Windows (from the Jetty wiki) has instructions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570/"
]
} |
184,328 | What is the difference between Obfuscation, Hashing, and Encryption? Here is my understanding: Hashing is a one-way algorithm; cannot be reversed Obfuscation is similar to encryption but doesn't require any "secret" to understand (ROT13 is one example) Encryption is reversible but a "secret" is required to do so | Hashing is a technique of creating semi-unique keys based on larger pieces of data. In a given hash you will eventually have "collisions" (e.g. two different pieces of data calculating to the same hash value) and when you do, you typically create a larger hash key size. obfuscation generally involves trying to remove helpful clues (i.e. meaningful variable/function names), removing whitespace to make things hard to read, and generally doing things in convoluted ways to make following what's going on difficult. It provides no serious level of security like "true" encryption would. Encryption can follow several models, one of which is the "secret" method, called private key encryption where both parties have a secret key. Public key encryption uses a shared one-way key to encrypt and a private recipient key to decrypt. With public key, only the recipient needs to have the secret. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6375/"
]
} |
184,409 | The documentation for +[NSThread detachNewThreadSelector:toTarget:withObject:] says: For non garbage-collected applications, the method aSelector is responsible for setting up an autorelease pool for the newly detached thread and freeing that pool before it exits. My question is, do I need to create my own NSAutoreleasePool in my override of the -[NSOperation main] method, or is the creation of the NSAutoreleasePool handled by NSOperation ? | Yes, you do. You're defining a self-contained piece of work which the NSOperationQueue will execute on "some" thread, so you're responsible for managing memory in that work piece. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23028/"
]
} |
184,414 | I have one action I want to perform when a TSpeedButton is pressed and another I want to perform when the same button is "unpressed". I know there's no onunpress event, but is there any easy way for me to get an action to execute when a different button is pressed? procedure ActionName.ActionNameExecute(Sender: TObject);begin PreviousActionName.execute(Sender); //end; Seems too clunky. | Yes, you do. You're defining a self-contained piece of work which the NSOperationQueue will execute on "some" thread, so you're responsible for managing memory in that work piece. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
]
} |
184,431 | I'm trying to convert an XML file into the markup used by dokuwiki, using XSLT. This actually works to some degree, but the indentation in the XSL file is getting inserted into the results. At the moment, I have two choices: abandon this XSLT thing entirely, and find another way to convert from XML to dokuwiki markup, or delete about 95% of the whitespace from the XSL file, making it nigh-unreadable and a maintenance nightmare. Is there some way to keep the indentation in the XSL file without passing all that whitespace on to the final document? Background: I'm migrating an autodoc tool from static HTML pages over to dokuwiki, so the API developed by the server team can be further documented by the applications team whenever the apps team runs into poorly-documented code. The logic is to have a section of each page set aside for the autodoc tool, and to allow comments anywhere outside this block. I'm using XSLT because we already have the XSL file to convert from XML to XHTML, and I'm assuming it will be faster to rewrite the XSL than to roll my own solution from scratch. Edit: Ah, right, foolish me, I neglected the indent attribute. (Other background note: I am new to XSLT.) On the other hand, I still have to deal with newlines. Dokuwiki uses pipes to differentiate between table columns, which means that all of the data in a table line must be on one line. Is there a way to suppress newlines being outputted (just occasionally), so I can do some fairly complex logic for each table cell in a somewhat readable fasion? | There are three reasons for getting unwanted whitespace in the result of an XSLT transformation: whitespace that comes from between nodes in the source document whitespace that comes from within nodes in the source document whitespace that comes from the stylesheet I'm going to talk about all three because it can be hard to tell where whitespace comes from so you might need to use several strategies. To address the whitespace that is between nodes in your source document, you should use <xsl:strip-space> to strip out any whitespace that appears between two nodes, and then use <xsl:preserve-space> to preserve the significant whitespace that might appear within mixed content. For example, if your source document looks like: <ul> <li>This is an <strong>important</strong> <em>point</em></li></ul> then you will want to ignore the whitespace between the <ul> and the <li> and between the </li> and the </ul> , which is not significant, but preserve the whitespace between the <strong> and <em> elements, which is significant (otherwise you'd get "This is an **important***point*"). To do this use <xsl:strip-space elements="*" /><xsl:preserve-space elements="li" /> The elements attribute on <xsl:preserve-space> should basically list all the elements in your document that have mixed content. Aside: using <xsl:strip-space> also reduces the size of the source tree in memory, and makes your stylesheet more efficient, so it's worth doing even if you don't have whitespace problems of this sort. To address the whitespace that appears within nodes in your source document, you should use normalize-space() . For example, if you have: <dt> a definition</dt> and you can be sure that the <dt> element won't hold any elements that you want to do something with, then you can do: <xsl:template match="dt"> ... <xsl:value-of select="normalize-space(.)" /> ...</xsl:template> The leading and trailing whitespace will be stripped from the value of the <dt> element and you will just get the string "a definition" . To address whitespace coming from the stylesheet, which is perhaps the one you're experiencing, is when you have text within a template like this: <xsl:template match="name"> Name: <xsl:value-of select="." /></xsl:template> XSLT stylesheets are parsed in the same way as the source documents that they process, so the above XSLT is interpreted as a tree that holds an <xsl:template> element with a match attribute whose first child is a text node and whose second child is a <xsl:value-of> element with a select attribute. The text node has leading and trailing whitespace (including line breaks); since it's literal text in the stylesheet, it gets literally copied over into the result, with all the leading and trailing whitespace. But some whitespace in XSLT stylesheets get stripped automatically, namely those between nodes. You don't get a line break in your result because there's a line break between the <xsl:value-of> and the close of the <xsl:template> . To get only the text you want in the result, use the <xsl:text> element like this: <xsl:template match="name"> <xsl:text>Name: </xsl:text> <xsl:value-of select="." /></xsl:template> The XSLT processor will ignore the line breaks and indentation that appear between nodes, and only output the text within the <xsl:text> element. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26257/"
]
} |
184,456 | Converting a couple stored procedures from MySQL to Microsoft SQL server. Everything is going well, except one procedure used the MySQL SHA1() function. I cannot seem to find an equivalent to this in MS-SQL. Does anyone know a valid equivalent for SHA1() on MS-SQL? | SQL Server 2005 and later has the HashBytes() function. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5640/"
]
} |
184,476 | I have been pushing into the .NET framework in PowerShell, and I have hit something that I don't understand. This works fine: $foo = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"$foo.Add("FOO", "BAR")$fooKey Value--- -----FOO BAR This however does not: $bar = New-Object "System.Collections.Generic.SortedDictionary``2[System.String,System.String]"New-Object : Cannot find type [System.Collections.Generic.SortedDictionary`2[System.String,System.String]]: make sure the assembly containing this type is loaded.At line:1 char:18+ $bar = New-Object <<<< "System.Collections.Generic.SortedDictionary``2[System.String,System.String]" They are both in the same assembly, so what am I missing? As was pointed out in the answers, this is pretty much only an issue with PowerShell v1. | In PowerShell 2.0 the new way to create a Dictionary is: $object = New-Object 'system.collections.generic.dictionary[string,int]' | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358/"
]
} |
184,502 | In this particular case I'm trying to discover if a mylib.a file is 32 or 64 bit compatible. I'm familiar with ldd for shared objects (mylib.so) but how do I inspect a regular .a archive? | "nm" and "ar" will give you some information about the library archive. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26261/"
]
} |
184,537 | I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (e.g. Calling free() on something that was created with the new operator), but I'm not clear on when I should use malloc / free and when I should use new / delete in my real world programs. If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard. | Unless you are forced to use C, you should never use malloc . Always use new . If you need a big chunk of data just do something like: char *pBuffer = new char[1024]; Be careful though this is not correct: //This is incorrect - may delete only one element, may corrupt the heap, or worse...delete pBuffer; Instead you should do this when deleting an array of data: //This deletes all items in the arraydelete[] pBuffer; The new keyword is the C++ way of doing it, and it will ensure that your type will have its constructor called . The new keyword is also more type-safe whereas malloc is not type-safe at all. The only way I could think that would be beneficial to use malloc would be if you needed to change the size of your buffer of data. The new keyword does not have an analogous way like realloc . The realloc function might be able to extend the size of a chunk of memory for you more efficiently. It is worth mentioning that you cannot mix new / free and malloc / delete . Note: Some answers in this question are invalid. int* p_scalar = new int(5); // Does not create 5 elements, but initializes to 5int* p_array = new int[5]; // Creates 5 elements | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/184537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
184,560 | I downloaded a VM image of a web application that uses MySQL. How can I monitor its space consumption and know when additional space must be added? | I have some great big queries to share: Run this to get the Total MySQL Data and Index Usage By Storage Engine SELECT IFNULL(B.engine,'Total') "Storage Engine",CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Data Size", CONCAT(LPAD(REPLACE(FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Index Size", CONCAT(LPAD(REPLACE(FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Table Size" FROM(SELECT engine,SUM(data_length) DSize,SUM(index_length) ISize,SUM(data_length+index_length) TSize FROMinformation_schema.tables WHERE table_schema NOT IN('mysql','information_schema','performance_schema') ANDengine IS NOT NULL GROUP BY engine WITH ROLLUP) B,(SELECT 3 pw) A ORDER BY TSize; Run this to get the Total MySQL Data and Index Usage By Database SELECT DBName,CONCAT(LPAD(FORMAT(SDSize/POWER(1024,pw),3),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Data Size",CONCAT(LPAD(FORMAT(SXSize/POWER(1024,pw),3),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Index Size",CONCAT(LPAD(FORMAT(STSize/POWER(1024,pw),3),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Total Size" FROM(SELECT IFNULL(DB,'All Databases') DBName,SUM(DSize) SDSize,SUM(XSize) SXSize,SUM(TSize) STSize FROM (SELECT table_schema DB,data_length DSize,index_length XSize,data_length+index_length TSize FROM information_schema.tablesWHERE table_schema NOT IN ('mysql','information_schema','performance_schema')) AAAGROUP BY DB WITH ROLLUP) AA,(SELECT 3 pw) BB ORDER BY (SDSize+SXSize); Run this to get the Total MySQL Data and Index Usage By Database and Storage Engine SELECT Statistic,DataSize "Data Size",IndexSize "Index Size",TableSize "Table Size"FROM (SELECT IF(ISNULL(table_schema)=1,10,0) schema_score,IF(ISNULL(engine)=1,10,0) engine_score,IF(ISNULL(table_schema)=1,'ZZZZZZZZZZZZZZZZ',table_schema) schemaname,IF(ISNULL(B.table_schema)+ISNULL(B.engine)=2,"Storage for All Databases",IF(ISNULL(B.table_schema)+ISNULL(B.engine)=1,CONCAT("Storage for ",B.table_schema),CONCAT(B.engine," Tables for ",B.table_schema))) Statistic,CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') DataSize,CONCAT(LPAD(REPLACE(FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') IndexSize,CONCAT(LPAD(REPLACE(FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') TableSize FROM (SELECT table_schema,engine,SUM(data_length) DSize,SUM(index_length) ISize,SUM(data_length+index_length) TSize FROM information_schema.tablesWHERE table_schema NOT IN ('mysql','information_schema','performance_schema')AND engine IS NOT NULL GROUP BY table_schema,engine WITH ROLLUP) B,(SELECT 3 pw) A) AA ORDER BY schemaname,schema_score,engine_score; CAVEAT In each query, you will see (SELECT 3 pw) . The pw stands for the Power Of 1024 to display the results. (SELECT 0 pw) will Display the Report in Bytes (SELECT 1 pw) will Display the Report in KiloBytes (SELECT 2 pw) will Display the Report in MegaBytes (SELECT 3 pw) will Display the Report in GigaBytes (SELECT 4 pw) will Display the Report in TeraBytes (SELECT 5 pw) will Display the Report in PetaBytes (please contact me if you run this one) Here is a report query with a little less formatting: SELECT IFNULL(db,'Total') "Database",datsum / power(1024,pw) "Data Size",ndxsum / power(1024,pw) "Index Size",totsum / power(1024,pw) "Total"FROM (SELECT db,SUM(dat) datsum,SUM(ndx) ndxsum,SUM(dat+ndx) totsumFROM (SELECT table_schema db,data_length dat,index_length ndxFROM information_schema.tables WHERE engine IS NOT NULLAND table_schema NOT IN ('information_schema','mysql')) AAGROUP BY db WITH ROLLUP) A,(SELECT 1 pw) B; Trust me, I made these queries over 4 years ago and still use them today. UPDATE 2013-06-24 15:53 EDT I have something new. I have changed the queries so that you do not have to set the pw parameter for different unit displays. Each unit display is calculated for you. Report By Storage Engine SELECT IFNULL(ENGINE,'Total') "Storage Engine", LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ', SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size", LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ', SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size", LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ', SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"FROM( SELECT ENGINE,DAT,NDX,TBL, IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3 FROM (SELECT *, FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px, FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py, FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz FROM (SELECT ENGINE, SUM(data_length) DAT, SUM(index_length) NDX, SUM(data_length+index_length) TBL FROM ( SELECT engine,data_length,index_length FROM information_schema.tables WHERE table_schema NOT IN ('information_schema','performance_schema','mysql') AND ENGINE IS NOT NULL ) AAA GROUP BY ENGINE WITH ROLLUP) AAA ) AA) A,(SELECT ' BKBMBGBTB' units) B; Report By Database SELECT IFNULL(DB,'Total') "Database", LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ', SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size", LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ', SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size", LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ', SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"FROM( SELECT DB,DAT,NDX,TBL, IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3 FROM (SELECT *, FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px, FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py, FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz FROM (SELECT DB, SUM(data_length) DAT, SUM(index_length) NDX, SUM(data_length+index_length) TBL FROM ( SELECT table_schema DB,data_length,index_length FROM information_schema.tables WHERE table_schema NOT IN ('information_schema','performance_schema','mysql') AND ENGINE IS NOT NULL ) AAA GROUP BY DB WITH ROLLUP) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B; Report By Database / Storage Engine SELECT IF(ISNULL(DB)+ISNULL(ENGINE)=2,'Database Total', CONCAT(DB,' ',IFNULL(ENGINE,'Total'))) "Reported Statistic", LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ', SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size", LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ', SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size", LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ', SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"FROM( SELECT DB,ENGINE,DAT,NDX,TBL, IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3 FROM (SELECT *, FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px, FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py, FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz FROM (SELECT DB,ENGINE, SUM(data_length) DAT, SUM(index_length) NDX, SUM(data_length+index_length) TBL FROM ( SELECT table_schema DB,ENGINE,data_length,index_length FROM information_schema.tables WHERE table_schema NOT IN ('information_schema','performance_schema','mysql') AND ENGINE IS NOT NULL ) AAA GROUP BY DB,ENGINE WITH ROLLUP) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
]
} |
184,563 | We are introducing static analysis tools into the build system for our Java product. We are using Maven2 so Checkstyle and PMD integration come for free. However it looks like there is a large overlap in functionality between these two tools, in terms of enforcing basic style rules. Is there a benefit from utilizing both of these? I don't want to maintain 2 tools if one will work. If we choose one, which one should we use and why? We are also planning on using FindBugs. Are there other static analysis tools we should look at? Update: Consensus seems to be that PMD is preferred over CheckStyle. I don't see a solid reason to use both, and I don't want to maintain 2 sets of rule files, so we will probably aim for PMD exclusively. We'll also be bringing in FindBugs, and perhaps, eventually, Macker to enforce architectural rules. | You should definitely use FindBugs . In my experience, the false-positive rate is very low, and even the least-critical warnings it reports are worth addressing to some extent. As for Checkstyle vs. PMD, I would not use Checkstyle since it is pretty much only concerned with style. In my experience, Checkstyle will report on a ton of things that are completely irrelevant. PMD on the other hand is also able to point out questionable coding practices and its output is generally more relevant and useful. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5874/"
]
} |
184,590 | Is there a way to do this in one line? $x =~ s/^\s+//;$x =~ s/\s+$//; In other words, remove all leading and trailing whitespace from a string. | $x =~ s/^\s+|\s+$//g; or s/^\s+//, s/\s+$// for $x; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
} |
184,618 | What is the best comment in source code you have ever encountered? | I am particularly guilty of this, embedding non-constructive comments, code poetry and little jokes into most of my projects (although I usually have enough sense to remove anything directly offensive before releasing the code). Here's one I'm particulary fond of, placed far, far down a poorly-designed 'God Object': /*** For the brave souls who get this far: You are the chosen ones,* the valiant knights of programming who toil away, without rest,* fixing our most awful code. To you, true saviors, kings of men,* I say this: never gonna give you up, never gonna let you down,* never gonna run around and desert you. Never gonna make you cry,* never gonna say goodbye. Never gonna tell a lie and hurt you.*/ I'M SORRY!!!! I just couldn't help myself.....! And another, which I'll admit I haven't actually released into the wild, even though I am very tempted to do so in one of my less intuitive classes: // // Dear maintainer:// // Once you are done trying to 'optimize' this routine,// and have realized what a terrible mistake that was,// please increment the following counter as a warning// to the next guy:// // total_hours_wasted_here = 42// | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/184618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
]
} |
184,643 | What is the best way to copy a list? I know the following ways, which one is better? Or is there another way? lst = ['one', 2, 3]lst1 = list(lst)lst2 = lst[:]import copylst3 = copy.copy(lst) | If you want a shallow copy (elements aren't copied) use: lst2=lst1[:] If you want to make a deep copy then use the copy module: import copylst2=copy.deepcopy(lst1) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/184643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915/"
]
} |
184,653 | We are looking to store transactional data in SharePoint lists. The lists will easily grow to 100,000+ items. How would the query performance be compared with queries on a database table with these columns? Queries:Select by IdSelect Where ColumnValue = XGroup By OrderIdGroup By Date The SP List will be 6 columns wide: Id, Date, OrderId (Lookup), Quanity, ItemName, Title | Don't do it.SharePoint is not good at handling transactional data and will perform badly. Any abilities you might have to improve performance at the database level (like adding indexes) may have detrimental effects on the SharePoint installation (although columns in lists can be "indexed" through SharePoint. Essentially SharePoint is designed for a specific purpose (content/documents) and trying to get it to do something out of the ordinary means you have to fight the application tooth and nail. Fortunately SharePoint has several means of integrating transactional data into it. First off (if you have the more expensive Enterprise licence) you have the Business Data Catalog that allows you to import database values that will appear similar to list items. If you do not have the Enterprise licence, I can recommend either custom controls/webparts or the Data View Web Part to allow that data to be "shown" on the relevant pages within SharePoint. In summary:You will be setting yourself up for a lot of uneccesary work by storing transactional data within SharePoint compared to other application designs hosting the data in traditional database applications and integrating to SharePoint. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21586/"
]
} |
184,666 | I've read (and re-read) Martin Fowler's Mocks Aren't Stubs . In it, he defines two different approaches to TDD: "Classical" and "Mockist" . He attempts to answer the question " So should I be a classicist or a mockist? ", but he admits that he has never tried mockist TDD on "anything more than toys." So I thought I'd ask the question here. Good answers may repeat Fowler's arguments (but hopefully more clearly) or add arguments that he didn't think of or that others have come up with since Fowler last updated the essay back in January 2007. | I don't think you need to choose one over the other. Both have their advantages and disadvantages and both are tools for your toolbox."Mockist" tdd makes you a bit more flexible in what you can test while classical TDD makes your tests a bit less brittle because they tend to look more at the input/vs output instead of looking at the actual implementation. When doing mockist unit testing I seem to have more tests break when changing the implementation. I try to use classical tdd whenever possible (although i often use a mocking framework to set up the stubs quickly). Sometimes I notice I start testing too much at one time or i need too many objects to set up a test. That's when mockist testing can often help you set up smaller tests. This is all quite abstract so I hope i make sense | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
]
} |
184,681 | Which of these pieces of code is faster? if (obj is ClassA) {}if (obj.GetType() == typeof(ClassA)) {} Edit:I'm aware that they don't do the same thing. | This should answer that question, and then some. The second line, if (obj.GetType() == typeof(ClassA)) {} , is faster, for those that don't want to read the article. (Be aware that they don't do the same thing) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/184681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
]
} |
184,683 | Is there a way in C# to play audio (for example, MP3) direcly from a System.IO.Stream that for instance was returend from a WebRequest without saving the data temporarily to the disk? Solution with NAudio With the help of NAudio 1.3 it is possible to: Load an MP3 file from a URL into a MemoryStream Convert MP3 data into wave data after it was completely loaded Playback the wave data using NAudio 's WaveOut class It would have been nice to be able to even play a half loaded MP3 file, but this seems to be impossible due to the NAudio library design. And this is the function that will do the work: public static void PlayMp3FromUrl(string url) { using (Stream ms = new MemoryStream()) { using (Stream stream = WebRequest.Create(url) .GetResponse().GetResponseStream()) { byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } } ms.Position = 0; using (WaveStream blockAlignedStream = new BlockAlignReductionStream( WaveFormatConversionStream.CreatePcmStream( new Mp3FileReader(ms)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing ) { System.Threading.Thread.Sleep(100); } } } } } | Edit: Answer updated to reflect changes in recent versions of NAudio It's possible using the NAudio open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the MP3Frame and AcmMp3FrameDecompressor classes in NAudio to decompress streamed MP3 on the fly. I have posted an article on my blog explaining how to play back an MP3 stream using NAudio . Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a BufferedWaveProvider . Another thread then plays back using the BufferedWaveProvider as an input. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25782/"
]
} |
184,704 | In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block. Is there a more elegant way of doing this? Perhaps an API call that will reveal this? Here's some rough code of what I'm talking about: Throwable t = null; try { stream.write(buffer); } catch(IOException e) { t = e; //Need to save this exception for finally throw e;} finally { try { stream.close(); //may throw exception } catch(IOException e) { //Is there something better than saving the exception from the exception block? if(t!=null) { //propagate the read exception as the "cause"--not great, but you see what I mean. throw new IOException("Could not close in finally block: " + e.getMessage(),t); } else { throw e; //just pass it up } }//end close} Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant. Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages? This question actually spawned from comments in another question that raised an interesting question. | Your idea about setting a variable outside the scope of the try/catch/finally is correct. There cannot be more than one exception propagating at once. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17871/"
]
} |
184,710 | What is the difference between a deep copy and a shallow copy? | Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/184710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447/"
]
} |
184,782 | I'm a doing some blackbox testing of a ASP.Net website and I need to test different session timeout scenarios. I'm not sure they fully encapsulated session timeouts. Other then leaving a page open for 20 minutes is there an easier way to force a session timeout? | Decrease the timeout The easiest and most non-intrusive way to test this is probably to just decrease the timeout to a fairly small number, such as 3 or 5 minutes. This way you can pause for a few minutes to simulate a longer pause without worrying about application restarts or special reset code having any affect on your test results. You can modify the session state timeout in a few locations - globally (in the web.config located in the config folder for the applicable .NET framework version), or just for your application. To modify the timeout just for your application, you can add the following to your application's web.config: <system.web> <sessionState timeout="60" /> ... Alternatively, you can also modify this same setting for your application through an IIS configuration dialog (I believe you still need to have a web.config defined for your application though, otherwise Edit Configuration will be disabled). To access this, right-click on your web application in IIS, and navigate to Properties | ASP.NET tab | Edit Configuration | State Management tab | Session timeout (minutes). Note that you can also manipulate this setting through code - if this is already being done, than the setting in the web.config file will effectively be ignored and you will need to use another technique. Call Session.Abandon() A slightly more intrusive technique than setting a low timeout would be to call Session.Abandon(). Be sure to call this from a page separate from your application though, as the session isn't actually ended until all script commands on the current page are processed. My understanding is that this would be a fairly clean way to test session timeouts without actually waiting for them. Force an application restart In a default configuration of session state, you can simulate a session timeout by blowing away the sessions entirely by causing the application to restart. This can be done several ways, a few of which are listed below: Recycle the app pool through the IIS MMC snap-in the command-line (iisapp /a AppPoolID /r) modifying web.config, global.asax, or a dll in the bin directory Restart IIS through the IIS MMC snap-in services.msc and restarting the IIS Admin service the command-line (iisreset) When I mention "default configuration", I mean a web application that is configured to use "InProc" session state mode. There are others modes that can actually maintain session state even if the web application is restarted (StateServer, SQLServer, Custom). Tamper with the state tracking mechanism Assuming your web application isn't configured with a "cookie-less" mode (by default, cookies will be used), you could remove the cookie containing the session ID from the client browser. However, my understanding is that this isn't really simulating a time-out, as the server will still be aware of the session, it just won't see anyone using it. The request without a session ID will simply be treated as an unseen request in need of a new session, which may or may not be what you want to test. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
]
} |
184,813 | I have a (Wordpress powered) website, and Google is indexing some of the sub-directories. How can I stop Apache from showing users the directory listing? I know I can edit .htaccess to password-protect a directory, but I would prefer a 403 / custom redirect if possible. | You need this entry in your .htaccess file: Options -Indexes | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4812/"
]
} |
184,814 | There's a cots (commercial off-the-shelf) application that I work on customizing, where a couple of pages take an extremely long time to load for certain distributions of data. (I'm talking approximately 3 minutes for a page to load in this instance... and the time is growing exponentially). Clearly this is unacceptable but are there studies out there where I can point what acceptable response time is? I'd like some good studies possibly that discuss response time. | Jakob Nielsen's research has answered this for any application (web apps aren't special in this regard): 0.1 second : Limit for users feeling that they are directly manipulating objects in the UI. 1 second : Limit for users feeling that they are freely navigating the command space without having to unduly wait for the computer. 10 seconds : Limit for users keeping their attention on the task. So for web apps you should keep your page response times at 500 ms maximum on average near the servers, to have a web app that is a pleasure to use even with a network latency of 200-300 ms. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/184814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5885/"
]
} |
184,858 | I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this: <a href="#" onclick="foo()">Click</a> But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't good for what I'm doing. | Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. Example... Let's say you have the following search link: <a href="search.php" id="searchLink">Search</a> You can always do the following: var link = document.getElementById('searchLink');link.onclick = function() { try { // Do Stuff Here } finally { return false; }}; That way, people with javascript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality. Edit: As nickf pointed out in comment #2, a try and catch will prevent the link to follow if there is an error in your handler. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915/"
]
} |
184,863 | To save some typing and clarify my code, is there a standard version of the following method? public static boolean bothNullOrEqual(Object x, Object y) { return ( x == null ? y == null : x.equals(y) );} | With Java 7 you can now directly do a null safe equals: Objects.equals(x, y) (The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/184863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
]
} |
184,869 | I'm working on a database in SQL Server 2000 that uses a GUID for each user that uses the app it's tied to. Somehow, two users ended up with the same GUID. I know that microsoft uses an algorithm to generate a random GUID that has an extremely low chance of causing collisons, but is a collision still possible? | Basically, no. I think someone went mucking with your database. Depending on the version GUID you're using the value is either unique (for things like version 1 GUIDs), or both unique and unpredictable (for things like version 4 GUIDs). SQL Server's implementation for their NEWID() function appears to use a 128-bit random number, so you're not going to get a collision. For a 1% chance of collision, you'd need to generate about 2,600,000,000,000,000,000 GUIDs. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/184869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
184,878 | Intro: I successfully implemented a WCF Service hosted in a Windows Service a few days ago. The community here at StackOverflow helped me with the WSDL exposure here . I thank you once again. However recently I found out that there is another potential client for this service this time located on the same machine as the service and this lead me to think I should add another endpoint with the namedPipesBinding. Named pipes seem to be the best solution for intra-machine communication as far as I am concerned. Please correct me if this is wrong. Problem: I need to expose another endpoint for the same service/contract but this time using a netNamedPipeBinding. However I really don't understand how do I can then add a service reference from a client. Foolishly after adding <endpoint address="net.pipe://localhost/OfficeService" binding="netNamedPipeBinding" contract="netBridge.Development.OfficeService.IWordService" bindingConfiguration="localBinding" /> I have tried to add a service reference in a Windows Forms Application located on the same machine typing the net.pipe://.... url. It didn't work. I must mention I have removed the mex (MetaData Exchange) endpoint earlier because I considered it not necessary. Is this mex endpoint necessary for named pipes endpoint binding discovery? How should I add a service reference in the client app to the named pipe endpoint? | Your endpoint looks fine, although I'm curious about what's in localBinding... Sounds like the easiest option is to just change the endpoint configuration on the named pipes client to match your service endpoint. The client shouldn't care as long as it's the only endpoint in the clients config file. Otherwise you'll have to add names to your endpoints and have the client pick a specific one when you new-up the proxy object. Good luck! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/184878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796/"
]
} |
184,970 | I am using partial classes to split some functionality between 2 files, but I am getting an error. What am I doing wrong? A1.cs: private partial class A{ private string SomeProperty { get { return "SomeGeneratedString"; } } } A2.cs: private partial class A{ void SomeFunction() { //trying to access this.SomeProperty produces the following compiler error, at least with C# 2.0 //error CS0117: 'A' does not contain a definition for 'SomeProperty' }} | Are the two partial classes in the same namespace? That could be an explanation. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
]
} |
184,983 | I need to take a BufferedImage and convert it to YCbCr format so that I can do a more efficient Brightness/contrast manipulation on it, but I can't figure out how to do this. I've tried ColorConvertOp but there doesn't seem to be an appropriate ColorSpace for YCbCr (though there is a type for it?). I could do the conversion manually (the conversion is not difficult) but this would immediately kick my image out of the 'fast-path'. Does anyone know a solution? | Are the two partial classes in the same namespace? That could be an explanation. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25920/"
]
} |
184,985 | I seem to be having an issue with iPhone SDK 2.1 in as far as beingable to establish a relationship between a ViewController and a Viewwindow. In as far as a Cocoa Touch Class, I went forward and added a UIViewController subclass. I made sure that the target is part of theexisting project. Right afterwards I added a User Interfaces -> ViewXIB. Within the UIViewController I have some straight forward code Iliterally copy/pasted from sample code elsewhere: EditViewController.h: @interface EditorViewController : UIViewController <UITextFieldDelegate> { UITextField *field;}@property(nonatomic, retain) IBOutlet UITextField *field;@end EditViewController.m #import "EditorViewController.h"@implementation EditorViewController- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait);}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning];}- (void)dealloc { [super dealloc];}@end As you can tell, it doesn't do much. Now when I click my new xib, andreference a class identity with EditorViewController , no auto completehappens, which to me implies that it has no such awareness of a EditorViewClass . When I attempt to control+click from the view toFile's Owners, I get nada. What are some of the possible idiosyncrasies in this process that I'moverlooking that's not allowing me to outlet my view to a controller? How would I also ensure that my User Interface View XIB is associated with the project besides seeing the project name checked off as a Target? | Are the two partial classes in the same namespace? That could be an explanation. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/184985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
185,034 | Is there a way to test the type of an element in JavaScript? The answer may or may not require the prototype library, however the following setup does make use of the library. function(event) { var element = event.element(); // if the element is an anchor ... // if the element is a td ...} | You can use typeof(N) to get the actual object type, but what you want to do is check the tag, not the type of the DOM element. In that case, use the elem.tagName or elem.nodeName property. if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/185034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682/"
]
} |
185,114 | I have a module in the parent directory of my script and I would like to 'use' it. If I do use '../Foo.pm'; I get syntax errors. I tried to do: push @INC, '..';use EPMS; and .. apparently doesn't show up in @INC I'm going crazy! What's wrong here? | use takes place at compile-time, so this would work: BEGIN {push @INC, '..'}use EPMS; But the better solution is to use lib , which is a nicer way of writing the above: use lib '..';use EPMS; In case you are running from a different directory, though, the use of FindBin is recommended: use FindBin; # locate this scriptuse lib "$FindBin::RealBin/.."; # use the parent directoryuse EPMS; | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/185114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
]
} |
185,124 | Say if I have a dropdown in a form and I have another nested class inside of this class .Now what's the best way to access this dropdown from the nested class? | Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : C# nested classes are like C++ nested classes, not Java inner classes . Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference. // C#class OuterClass { string s; // ... class InnerClass { OuterClass o_; public InnerClass(OuterClass o) { o_ = o; } public string GetOuterString() { return o_.s; } } void SomeFunction() { InnerClass i = new InnerClass(this); i.GetOuterString(); }} Note that the InnerClass can access the " s " of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the " string s; " is private because no other access permission was specified. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/185124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
185,208 | How can I get Environnment variables and if something is missing, set the value? | Use the System.Environment class. The methods var value = System.Environment.GetEnvironmentVariable(variable [, Target]) and System.Environment.SetEnvironmentVariable(variable, value [, Target]) will do the job for you. The optional parameter Target is an enum of type EnvironmentVariableTarget and it can be one of: Machine , Process , or User . If you omit it, the default target is the current process. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
]
} |
185,235 | I've previously used jquery-ui tabs extension to load page fragments via ajax , and to conceal or reveal hidden div s within a page. Both of these methods are well documented, and I've had no problems there. Now, however, I want to do something different with tabs. When the user selects a tab, it should reload the page entirely - the reason for this is that the contents of each tabbed section are somewhat expensive to render, so I don't want to just send them all at once and use the normal method of toggling 'display:none' to reveal them. My plan is to intercept the tabs' select event, and have that function reload the page with by manipulating document.location. How, in the select handler, can I get the newly selected tab index and the html LI object it corresponds to? $('#edit_tabs').tabs( { selected: 2, // which tab to start on when page loads select: function(e, ui) { var t = $(e.target); // alert("data is " + t.data('load.tabs')); // undef // alert("data is " + ui.data('load.tabs')); // undef // This gives a numeric index... alert( "selected is " + t.data('selected.tabs') ) // ... but it's the index of the PREVIOUSLY selected tab, not the // one the user is now choosing. return true; // eventual goal is: // ... document.location= extract-url-from(something); return false; }}); Is there an attribute of the event or ui object that I can read that will give the index, id, or object of the newly selected tab or the anchor tag within it? Or is there a better way altogether to use tabs to reload the entire page? | I would take a look at the events for Tabs. The following is taken from the jQuery docs: $('.ui-tabs-nav').bind('tabsselect', function(event, ui) { ui.options // options used to intialize this widget ui.tab // anchor element of the selected (clicked) tab ui.panel // element, that contains the contents of the selected (clicked) tab ui.index // zero-based index of the selected (clicked) tab }); Looks like ui.tab is the way to go. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2554901/"
]
} |
185,236 | I'm programming something that allows users to store documents and pictures on a webserver, to be stored and retrieved later. When users upload files to my server, PHP tells me what filetype it is based on the extension. However, I'm afraid that users could rename a zip file as somezipfile.png and store it, thus keeping a zip file on my server. Is there any reasonable way to open an uploaded file and "check" to see if it truly is of the said filetype? | Magic number . If you can read first few bytes of a binary file you can know what kind of file it is. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
]
} |
185,254 | I'm currently passing the pid on the command line to the child, but is there a way to do this in the Win32 API? Alternatively, can someone alleviate my fear that the pid I'm passing might belong to another process after some time if the parent has died? | Just in case anyone else runs across this question and is looking for a code sample, I had to do this recently for a Python library project I'm working on. Here's the test/sample code I came up with: #include <stdio.h>#include <windows.h>#include <tlhelp32.h>int main(int argc, char *argv[]) { int pid = -1; HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe = { 0 }; pe.dwSize = sizeof(PROCESSENTRY32); //assume first arg is the PID to get the PPID for, or use own PID if (argc > 1) { pid = atoi(argv[1]); } else { pid = GetCurrentProcessId(); } if( Process32First(h, &pe)) { do { if (pe.th32ProcessID == pid) { printf("PID: %i; PPID: %i\n", pid, pe.th32ParentProcessID); } } while( Process32Next(h, &pe)); } CloseHandle(h);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23524/"
]
} |
185,314 | I have a C# app which uses a System.Diagnostics.Process to run another exe. I ran into some example code where the process is started in a try block and closed in a finally block. I also saw example code where the process is not closed. What happens when the process is not closed? Are the resources used by the process reclaimed when the console app that created the process is closed? Is it bad to open lots of processes and not close any of them in a console app that's open for long periods of time? Cheers! | When the other process exits , all of its resources are freed up, but you will still be holding onto a process handle (which is a pointer to a block of information about the process) unless you call Close() on your Process reference. I doubt there would be much of an issue, but you may as well . Process implements IDisposable so you can use C#'s using(...) statement, which will automatically call Dispose (and therefore Close() ) for you : using (Process p = Process.Start(...)){ ...} As a rule of thumb: if something implements IDisposable , You really should call Dispose / Close or use using(...) on it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
]
} |
185,349 | In XAML I can declare a DataTemplate so that the template is used whenever a specific type is displayed. For example, this DataTemplate will use a TextBlock to display the name of a customer: <DataTemplate DataType="{x:Type my:Customer}"> <TextBlock Text="{Binding Name}" /></DataTemplate> I'm wondering if it's possible to define a DataTemplate that will be used any time an IList<Customer> is displayed. So if a ContentControl's Content is, say, an ObservableCollection<Customer> it would use that template. Is it possible to declare a generic type like IList in XAML using the {x:Type} Markup Extension? | Not out of the box, no; but there are enterprising developers out there who have done so. Mike Hillberg at Microsoft played with it in this post , for example. Google has others of course. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
]
} |
185,378 | What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'? The regular expression should match any of the following: RunFoo.pyRunBar.pyRun42.py It should not match: myRunFoo.pyRunBar.py1Run42.txt The SQL equivalent of what I am looking for is ... LIKE 'Run%.py' ... . | For a regular expression, you would use: re.match(r'Run.*\.py$') A quick explanation: . means match any character. * means match any repetition of the previous character (hence .* means any sequence of chars) \ is an escape to escape the explicit dot $ indicates "end of the string", so we don't match "Run_foo.py.txt" However, for this task, you're probably better off using simple string methods. ie. filename.startswith("Run") and filename.endswith(".py") Note: if you want case insensitivity (ie. matching "run.PY" as well as "Run.py", use the re.I option to the regular expression, or convert to a specific case (eg filename.lower()) before using string methods. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/185378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
185,381 | I have some System.Diagnotics.Processes to run. I'd like to call the close method on them automatically. Apparently the "using" keyword does this for me. Is this the way to use the using keyword? foreach(string command in S) // command is something like "c:\a.exe"{ try { using(p = Process.Start(command)) { // I literally put nothing in here. } } catch (Exception e) { // notify of process failure }} I'd like to start multiple processes to run concurrently. | using(p = Process.Start(command)) This will compile, as the Process class implements IDisposable , however you actually want to call the Close method. Logic would have it that the Dispose method would call Close for you, and by digging into the CLR using reflector, we can see that it does in fact do this for us. So far so good. Again using reflector, I looked at what the Close method does - it releases the underlying native win32 process handle, and clears some member variables. This (releasing external resources) is exactly what the IDisposable pattern is supposed to do. However I'm not sure if this is what you want to achieve here. Releasing the underlying handles simply says to windows 'I am no longer interested in tracking this other process'. At no point does it actually cause the other process to quit, or cause your process to wait. If you want to force them quit, you'll need to use the p.Kill() method on the processes - however be advised it is never a good idea to kill processes as they can't clean up after themselves, and may leave behind corrupt files, and so on. If you want to wait for them to quit on their own, you could use p.WaitForExit() - however this will only work if you're waiting for one process at a time. If you want to wait for them all concurrently, it gets tricky. Normally you'd use WaitHandle.WaitAll for this, but as there's no way to get a WaitHandle object out of a System.Diagnostics.Process , you can't do this (seriously, wtf were microsoft thinking?). You could spin up a thread for each process, and call `WaitForExit in those threads, but this is also the wrong way to do it. You instead have to use p/invoke to access the native win32 WaitForMultipleObjects function. Here's a sample (which I've tested, and actually works) [System.Runtime.InteropServices.DllImport( "kernel32.dll" )]static extern uint WaitForMultipleObjects( uint nCount, IntPtr[] lpHandles, bool bWaitAll, uint dwMilliseconds );static void Main( string[] args ){ var procs = new Process[] { Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 2'" ), Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 3'" ), Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 4'" ) }; // all started asynchronously in the background var handles = procs.Select( p => p.Handle ).ToArray(); WaitForMultipleObjects( (uint)handles.Length, handles, true, uint.MaxValue ); // uint.maxvalue waits forever} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
]
} |
185,384 | While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this: static private List<int> a = new List<int>() { 0 };static private List<int> b = new List<int>() { a[0] }; Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this? Edit: (re: Panos) In a file lexical order seems to be king? what about across files? In looking I tried a cyclical dependency like this: static private List<int> a = new List<int>() { b[0] };static private List<int> b = new List<int>() { a[0] }; and the program didn't run the same (the test suit failed across the board and I didn't look further). | It seems to depend on the sequence of lines. This code works: static private List<int> a = new List<int>() { 1 };static private List<int> b = new List<int>() { a[0] }; while this code does not work (it throws a NullReferenceException ) static private List<int> a = new List<int>() { b[0] };static private List<int> b = new List<int>() { 1 }; So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain... EDIT - What's happening "across files"? If we declare these two classes: public class A { public static List<int> a = new List<int>() { B.b[0] };}public class B { public static List<int> b = new List<int>() { A.a[0] };} and try to access them with this code: try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); } we are getting this output: The type initializer for 'A' threw an exception.Object reference not set to an instance of an object.The type initializer for 'A' threw an exception. So the initialization of B causes an exception in static constructor A and lefts field a with the default value (null). Since a is null , b can not also be initialized properly. If we do not have cyclical dependencies, everything works fine. EDIT: Just in case you didn't read the comments, Jon Skeet provides a very interesting reading: The differences between static constructors and type initializers . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
]
} |
185,423 | I'm working on an application that is implemented as an HTA. I have a series of links that I would like to have open in the system's default web browser. Using <a href="url" target="_blank"> opens the link in IE regardless of the default browser. Is there a way to use the default browser? Using JavaScript is an option. | Create a shell and attempt to run a URL. This works for me (save as whatever.hta and execute it) on my system. Clicking on the button opens Google in Firefox: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"><head> <title>HTA Test</title> <hta:application applicationname="HTA Test" scroll="yes" singleinstance="yes"> <script type="text/javascript"> function openURL() { var shell = new ActiveXObject("WScript.Shell"); shell.run("http://www.google.com"); } </script></head><body><input type="button" onclick="openURL()" value="Open Google"></body></html> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7441/"
]
} |
185,429 | I know how to use JSON to create objects, but there doesn't seem to be away to use JSON to create an object that is of a specific object type. Here's an example of an Object and creating an instance of it: Person = function() { };Person.prototype = { FirstName: null, GetFirstName: function() { return this.FirstName; }};//Create an instance of the Person Objectvar me = new Person();me.FirstName = "Chris";alert(me.GetFirstName()); //alert the FirstName property Now, I would like to use JSON to create a new Person object so that the GetFirstName function works on it. Here's something like that I'm looking to do (but this code doesn't work): var you = new Person() { FirstName: "Mike" };// ORvar you = new Person{ FirstName: "Mike" }; Is there anyway to use JSON to create an object that is of a specific type? UPDATE: My sample with the Person object is just to simplify the question. In fact, I am unable to modify the constructors of the actual objects that I need to create instances of. The objects are part of a third-party library. UPDATE: Using some of the suggestions below, I was able to figure out a way to create an object that inherits from the original, and accept JSON in it's constructor. This is neat! personWrapper = function(obj){ for(var o in obj){ this[o] = obj[o]; }};personWrapper.prototype = new Person();var you = new personWrapper({FirstName: "Chris"});alert(you.GetFirstName());alert(you instanceof Person); // returns True - we are successfully inheriting from Person! | I don't imagine so. I'd create a function on the Person class to initialise from a JSON object if I were you. function Person() { this.loadFromJSON = function(json) { this.FirstName = json.FirstName; };} If you didn't know what class the JSON object was representing beforehand, perhaps add an extra variable into your JSON. { _className : "Person", FirstName : "Mike" } And then have a 'builder' function which interprets it. function buildFromJSON(json) { var myObj = new json["_className"](); myObj.loadFromJSON(json); return myObj;} Update: since you say the class is part of a third-party library which you can't change, you could either extend the class with prototyping, or write a function which just populates the class externally. eg: Person.prototype.loadFromJSON = function(json) { // as above...}; or function populateObject(obj, json) { for (var i in json) { // you might want to put in a check here to test // that obj actually has an attribute named i obj[i] = json[i]; }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
]
} |
185,444 | There's a lot of interest these days in Erlang as a language for writing parallel programs on multicore. I've heard people argue that Erlang's message-passing model is easier to program than the dominant shared-memory models such as threads. Conversely, in the high-performance computing community the dominant parallel programming model has been MPI, which also implements a message-passing model. But in the HPC world, this message-passing model is generally considered very difficult to program in, and people argue that shared memory models such as OpenMP or UPC are easier to program in. Does anybody know why there is such a difference in the perception of message-passing vs. shared memory in the IT and HPC worlds? Is it due to some fundamental difference in how Erlang and MPI implement message passing that makes Erlang-style message-passing much easier than MPI? Or is there some other reason? | I agree with all previous answers, but I think a key point that is not made totally clear is that one reason that MPI might be considered hard and Erlang easy is the match of model to the domain. Erlang is based on a concept of local memory, asynchronous message passing, and shared state solved by using some form of global database that all threads can get to. It is designed for applications that do not move a whole lot of data around, and that is not supposed to explode out to a 100k separate nodes that need coordination. MPI is based on local memory and message passing, and is intended for problems where moving data around is a key part of the domain. High-performance computing is very much about taking the dataset for a problem, and splitting it up among a host of compute resources. And that is pretty hard work in a message-passing system as data has to be explicitly distributed with balancing in mind. Essentially, MPI can be viewed as a grudging admittance that shared memory does not scale. And it is targeting high-performance computation spread across 100k processors or more. Erlang is not trying to achieve the highest possible performance, rather to decompose a naturally parallel problem into its natural threads. It was designed with a totally different type of programming tasks in mind compared to MPI. So Erlang is best compared to pthreads and other rather local heterogeneous thread solutions, rather than MPI which is really aimed at a very different (and to some extent inherently harder) problem set. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
]
} |
185,451 | What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time? | Use flock(1) to make an exclusive scoped lock a on file descriptor. This way you can even synchronize different parts of the script. #!/bin/bash( # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds flock -x -w 10 200 || exit 1 # Do stuff) 200>/var/lock/.myscript.exclusivelock This ensures that code between ( and ) is run only by one process at a time and that the process doesn’t wait too long for a lock. Caveat: this particular command is a part of util-linux . If you run an operating system other than Linux, it may or may not be available. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/185451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
} |
185,474 | I have a connection string being passed to a function, and I need to create a DbConnection based object (i.e. SQLConnection, OracleConnection, OLEDbConnection etc) based on this string. Is there any inbuilt functionality to do this, or any 3rd party libraries to assist. We are not necessarily building this connection string, so we cannot rely on a format the string is written in to determine its type, and I would prefer not to have to code up all combinations and permutations of possible connection strings | DbConnection GetConnection(string connStr){ string providerName = null; var csb = new DbConnectionStringBuilder { ConnectionString = connStr }; if (csb.ContainsKey("provider")) { providerName = csb["provider"].ToString(); } else { var css = ConfigurationManager .ConnectionStrings .Cast<ConnectionStringSettings>() .FirstOrDefault(x => x.ConnectionString == connStr); if (css != null) providerName = css.ProviderName; } if (providerName != null) { var providerExists = DbProviderFactories .GetFactoryClasses() .Rows.Cast<DataRow>() .Any(r => r[2].Equals(providerName)); if (providerExists) { var factory = DbProviderFactories.GetFactory(providerName); var dbConnection = factory.CreateConnection(); dbConnection.ConnectionString = connStr; return dbConnection; } } return null;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
]
} |
185,483 | How do I prevent my users from accessing directly pages meant for ajax calls only? Passing a key during ajax call seems like a solution, whereas access without the key will not be processed. But it is also easy to fabricate the key, no? Curse of View Source... p/s: Using Apache as webserver. EDIT: To answer why, I have jQuery ui-tabs in my index.php, and inside those tabs are forms with scripts, which won't work if they're accessed directly. Why a user would want to do that, I don't know, I just figure I'd be more user friendly by preventing direct access to forms without validation scripts. | As others have said, Ajax request can be emulated be creating the proper headers.If you want to have a basic check to see if the request is an Ajax request you can use: if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { //Request identified as ajax request } However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15345/"
]
} |
185,486 | Subclipse , Subversive , or something else ? There's a bit of debate around the topic, can we come to some conclusion here? EDIT: It's been a couple months now, and I ended up deciding the plugin slowed Eclipse down too much, and was a hassle to use every time I changed a file from outside Eclipse.I ditched the plugin all together and just went with TortiseSVN. | This depends. Subclipse has superior support for checking out projects as maven projects - this is the sole reason we use Subclipse. Other than that, I have noticed subclipse bugs with syncing with SVN. Subversive is much better at detecting new files to add to version control, and is also far superior with merging code from a branch, or even syncing with SVN (fewer bugs, etc.). So really, you should ask yourself what value you want. If you're not using maven, I would definitely go for Subversive. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/185486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14966/"
]
} |
185,510 | Is it possible to do something like this? var pattern = /some regex segment/ + /* comment here */ /another segment/; Or do I have to use new RegExp() syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise. | Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object: var segment_part = "some bit of the regexp";var pattern = new RegExp("some regex segment" + /*comment here */ segment_part + /* that was defined just now */ "another segment"); If you have two regular expression literals, you can in fact concatenate them using this technique: var regex1 = /foo/g;var regex2 = /bar/y;var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");var regex3 = new RegExp(expression_one.source + expression_two.source, flags);// regex3 is now /foobar/gy It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17964/"
]
} |
185,520 | I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible. | A little hacky but should work: SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime))) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/185520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
]
} |
185,533 | I've been looking at the DropBox Mac client and I'm currently researching implementing a similar interface for a different service. How exactly do they interface with finder like this? I highly doubt these objects represented in the folder are actual documents downloaded on every load? They must dynamically download as they are needed. So how can you display these items in finder without having actual file system objects? Does anyone know how this is achieved in Mac OS X? Or any pointer's to Apple API's or other open source projects that have a similar integration with finder? | Dropbox is not powered by either MacFUSE or WebDAV, although those might be perfectly fine solutions for what you're trying to accomplish. If it were powered by those things, it wouldn't work when you weren't connected, as both of those rely on the server to store the actual information and Dropbox does not. If I quit Dropbox (done via the menu item) and disconnect from the net, I can still use the files. That's because the files are actually stored here on my hard drive. It also means that the files don't need to be "downloaded on every load," since they are actually stored on my machine here. Instead, only the deltas are sent over the wire, and the Dropbox application (running in the background) patches the files appropriately. Going the other way, the Dropbox application watches for the files in the Dropbox folder, and when they change, it sends the appropriate deltas to the server, which propagates them to any other clients. This setup has some decided advantages: it works when offline, it is an order of magnitude faster, and it is transparent to other apps, since they just see files on the disk. However, I have no idea how it deals with merge conflicts (which could easily arise with one or more clients offline), which are not an issue if the server is the only copy and every edit changes that central copy. Where Dropbox really shines is that they have an additional trick that badges the items in the Dropbox folder with their current sync status. But that's not what you're asking about here. As far as the question at hand, you should definitely look into MacFUSE and WebDAV, which might be perfect solutions to your problem. But the Dropbox way of doing things, with a background application changing actual files on the disk, might be a better tradeoff. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
]
} |
185,536 | By default it seems that objects are drawn front to back. I am drawing a 2-D UI object and would like to create it back to front. For example I could create a white square first then create a slightly smaller black square on top of it thus creating a black pane with a white border. This post had some discussion on it and described this order as the "Painter's Algorithm" but ultimately the example they gave simply rendered the objects in reverse order to get the desired effect. I figure back to front (first objects go in back, subsequent objects get draw on top) rendering can be achieved via some transformation (gOrtho?) ? I will also mention that I am not interested in a solution using a wrapper library such as GLUT. I have also found that the default behavior on the Mac using the Cocoa NSOpenGLView appears to draw back to front, where as in windows I cannot get this behavior. The setup code in windows I am using is this: glViewport (0, 0, wd, ht);glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho (0.0f, wd, ht, 0.0f, -1.0f, 1.0f);glMatrixMode(GL_MODELVIEW); glLoadIdentity(); | The following call will turn off depth testing causing objects to be drawn in the order created. This will in effect cause objects to draw back to front. glDepthFunc(GL_NEVER); // Ignore depth values (Z) to cause drawing bottom to top Be sure you do not call this: glEnable (GL_DEPTH_TEST); // Enables Depth Testing | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8761/"
]
} |
185,542 | In java world you have log4j and a a pretty decent logging framework, is there anything like that for C#/.NET? | log4net would be the obvious answer. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13469/"
]
} |
185,559 | I would like to remove the domain/computer information from a login id in C#. So, I would like to make either "Domain\me" or "Domain\me" just "me". I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact. Worse case scenario: int startIndex = 0;int indexOfSlashesSingle = ResourceLoginName.IndexOf("\");int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\");if (indexOfSlashesSingle != -1) startIndex = indexOfSlashesSingle;else startIndex = indexOfSlashesDouble;string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1); | when all you have is a hammer, everything looks like a nail..... use a razor blade ---- using System;using System.Text.RegularExpressions;public class MyClass{ public static void Main() { string domainUser = Regex.Replace("domain\\user",".*\\\\(.*)", "$1",RegexOptions.None); Console.WriteLine(domainUser); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18449/"
]
} |
185,573 | I couldn't really find this in Rails documentation but it seems like 'mattr_accessor' is the Module corollary for 'attr_accessor' (getter & setter) in a normal Ruby class . Eg. in a class class User attr_accessor :name def set_fullname @name = "#{self.first_name} #{self.last_name}" endend Eg. in a module module Authentication mattr_accessor :current_user def login @current_user = session[:user_id] || nil endend This helper method is provided by ActiveSupport . | Rails extends Ruby with both mattr_accessor (Module accessor) and cattr_accessor (as well as _ reader / _writer versions). As Ruby's attr_accessor generates getter/setter methods for instances , cattr/mattr_accessor provide getter/setter methods at the class or module level. Thus: module Config mattr_accessor :hostname mattr_accessor :admin_emailend is short for: module Config def self.hostname @hostname end def self.hostname=(hostname) @hostname = hostname end def self.admin_email @admin_email end def self.admin_email=(admin_email) @admin_email = admin_email endend Both versions allow you to access the module-level variables like so: >> Config.hostname = "example.com">> Config.admin_email = "[email protected]">> Config.hostname # => "example.com">> Config.admin_email # => "[email protected]" | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6048/"
]
} |
185,575 | In bash the ampersand (&) can be used to run a command in the background and return interactive control to the user before the command has finished running. Is there an equivalent method of doing this in Powershell? Example of usage in bash: sleep 30 & | As long as the command is an executable or a file that has an associated executable, use Start-Process (available from v2): Start-Process -NoNewWindow ping google.com You can also add this as a function in your profile: function bg() {Start-Process -NoNewWindow @args} and then the invocation becomes: bg ping google.com In my opinion, Start-Job is an overkill for the simple use case of running a process in the background: Start-Job does not have access to your existing scope (because it runs in a separate session). You cannot do "Start-Job {notepad $myfile}" Start-Job does not preserve the current directory (because it runs in a separate session). You cannot do "Start-Job {notepad myfile.txt}" where myfile.txt is in the current directory. The output is not displayed automatically. You need to run Receive-Job with the ID of the job as parameter. NOTE: Regarding your initial example, "bg sleep 30" would not work because sleep is a Powershell commandlet. Start-Process only works when you actually fork a process. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/185575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5769/"
]
} |
185,606 | I wonder if this would be doable ? To insert an array into one field in the database. For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website. It feels a bit unnecessary to make another table to have their global ids and then another table with the actual titles linked to the table with the global id. I just want to have something like this ID TITLE1 Array("english title", "nederlandse titel"); I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages. Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million) | it's doable: $title = serialize($array); and then to decode: $title = unserialize($mysql_data); but as mentioned it really lessens the benefits of a database in the first place. i'd definitely suggest looking into a multi-table or multi-column option instead, depending on the amount of languages you want to support and if that number will change in the future. edit: a good point mentioned by dcousineau (see comments) Sometimes the serialized output, even after escaping, throws characters into the query that screws things up. You may want to wrap your serialize() in base64_encode() calls and then use base64_decode() before you unserialize. adjusted code for those situations: $title = base64_encode(serialize($array) );$title = unserialize(base64_decode($mysql_data) ); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
]
} |
185,624 | I have a function that is declared and defined in a header file. This is a problem all by itself. When that function is not inlined, every translation unit that uses that header gets a copy of the function, and when they are linked together there are duplicated. I "fixed" that by making the function inline, but I'm afraid that this is a fragile solution because as far as I know, the compiler doesn't guarantee inlining, even when you specify the "inline" keyword. If this is not true, please correct me. Anyways, the real question is, what happens to static variables inside this function? How many copies do I end up with? | I guess you're missing something, here. static function? Declaring a function static will make it "hidden" in its compilation unit. A name having namespace scope (3.3.6) has internal linkage if it is the name of — a variable, function or function template that is explicitly declared static; 3.5/3 - C++14 (n3797) When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit. 3.5/2 - C++14 (n3797) If you declare this static function in a header, then all the compilation units including this header will have their own copy of the function. The thing is, if there are static variables inside that function, each compilation unit including this header will also have their own, personal version. inline function? Declaring it inline makes it a candidate for inlining (it does not mean a lot nowadays in C++, as the compiler will inline or not, sometimes ignoring the fact the keyword inline is present or absent): A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected. 7.1.2/2 - C++14 (n3797) In a header, its has an interesting side effect: The inlined function can be defined multiple times in the same module, and the linker will simply join "them" into one (if they were not inlined for compiler's reason). For static variables declared inside, the standard specifically says there one, and only one of them: A static local variable in an extern inline function always refers to the same object. 7.1.2/4 - C++98/C++14 (n3797) (functions are by default extern, so, unless you specifically mark your function as static, this applies to that function) This has the advantage of "static" (i.e. it can be defined in a header) without its flaws (it exists at most once if it is not inlined) static local variable? Static local variables have no linkage (they can't be referred to by name outside their scope), but has static storage duration (i.e. it is global, but its construction and destruction obey to specific rules). static + inline? Mixing inline and static will then have the consequences you described (even if the function is inlined, the static variable inside won't be, and you'll end with as much static variables as you have compilation units including the definition of your static functions). Answer to author's additional question Since I wrote the question I tried it out with Visual Studio 2008. I tried to turn on all the options that make VS act in compliance with standards, but it's possible that I missed some. These are the results: When the function is merely "inline", there is only one copy of the static variable. When the function is "static inline", there are as many copies as there are translation units. The real question is now whether things are supposed to be this way, or if this is an idiosyncrasy of the Microsoft C++ compiler. So I suppose you have something like that: void doSomething(){ static int value ;} You must realise that the static variable inside the function, simply put, a global variable hidden to all but the function's scope, meaning that only the function it is declared inside can reach it. Inlining the function won't change anything: inline void doSomething(){ static int value ;} There will be only one hidden global variable. The fact the compiler will try to inline the code won't change the fact there is only one global hidden variable. Now, if your function is declared static: static void doSomething(){ static int value ;} Then it is "private" for each compilation unit, meaning that every CPP file including the header where the static function is declared will have its own private copy of the function, including its own private copy of global hidden variable, thus as much variables as there are compilation units including the header. Adding "inline" to a "static" function with a "static" variable inside: inline static void doSomething(){ static int value ;} has the same result than not adding this "inline" keyword, as far as the static variable inside is concerned. So the behaviour of VC++ is correct, and you are mistaking the real meaning of "inline" and "static". | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/185624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13562/"
]
} |
185,652 | I have a UIImageView and the objective is to scale it down proportionally by giving it either a height or width. UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; //Add image view[self.view addSubview:imageView]; //set contentMode to scale aspect to fitimageView.contentMode = UIViewContentModeScaleAspectFit;//change width of frameCGRect frame = imageView.frame;frame.size.width = 100;imageView.frame = frame; The image did get resized but the position is not at the top left. What is the best approach to scaling image/imageView and how do I correct the position? | Fixed easily, once I found the documentation! imageView.contentMode = .scaleAspectFit | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
]
} |
185,693 | I am trying to install an svn client on a friend's work windows laptop without much success. It seems that everyone is using TortoiseSVN nowadays, which unfortunately doesn't install without administrator access. Is there any way around it or another client I can try? I don't need anything fancy - just basic http/https, but a GUI is very much preferred over a command line client. Thanks! I just verified that both SmartSVN and RapidSVN mentioned previously require administrator access to insatll on Windows, just like TortoiseSVN. :( | Ok, I finally found out the (I think) correct answer to this question. The zipped binaries are available in the win32svn project here: http://sourceforge.net/projects/win32svn/files/ . In the subdirectory of your favorite version, just download the file that has a name like svn-win32-1.6.16.zip and unpack to your home dir, local hd or (in my case) usb stick. Hope this helps someone! I was very surprised to find all links I found pointed to installers which you may not be able to run when you don't have adminstrator rights. EDIT: this is, of course, the CLI version; I guess this answer is more for people who, like me, are looking for it and arrived at this question :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
185,697 | Input: A positive integer K and a big text. The text can actually be viewed as word sequence. So we don't have to worry about how to break down it into word sequence. Output: The most frequent K words in the text. My thinking is like this. use a Hash table to record all words' frequency while traverse the whole word sequence. In this phase, the key is "word" and the value is "word-frequency". This takes O(n) time. sort the (word, word-frequency) pair; and the key is "word-frequency". This takes O(n*lg(n)) time with normal sorting algorithm. After sorting, we just take the first K words. This takes O(K) time. To summarize, the total time is O(n+n lg(n)+K), Since K is surely smaller than N, so it is actually O(n lg(n)). We can improve this. Actually, we just want top K words. Other words' frequency is not concern for us. So, we can use "partial Heap sorting". For step 2) and 3), we don't just do sorting. Instead, we change it to be 2') build a heap of (word, word-frequency) pair with "word-frequency" as key. It takes O(n) time to build a heap; 3') extract top K words from the heap. Each extraction is O(lg(n)). So, total time is O(k*lg(n)). To summarize, this solution cost time O(n+k*lg(n)). This is just my thought. I haven't find out way to improve step 1). I Hope some Information Retrieval experts can shed more light on this question. | This can be done in O(n) time Solution 1: Steps: Count words and hash it, which will end up in the structure like this var hash = { "I" : 13, "like" : 3, "meow" : 3, "geek" : 3, "burger" : 2, "cat" : 1, "foo" : 100, ... ... Traverse through the hash and find the most frequently used word (in this case "foo" 100), then create the array of that size Then we can traverse the hash again and use the number of occurrences of words as array index, if there is nothing in the index, create an array else append it in the array. Then we end up with an array like: 0 1 2 3 100[[ ],[cat],[burger],[like, meow, geek],[]...[foo]] Then just traverse the array from the end, and collect the k words. Solution 2: Steps: Same as above Use min heap and keep the size of min heap to k, and for each word in the hash we compare the occurrences of words with the min, 1) if it's greater than the min value, remove the min (if the size of the min heap is equal to k) and insert the number in the min heap. 2) rest simple conditions. After traversing through the array, we just convert the min heap to array and return the array. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
]
} |
185,747 | I am trying to convert an int into three bytes representing that int (big endian). I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it. For example: int myInt;// some codebyte b1, b2 , b3; // b1 is most significant, then b2 then b3. *Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing. | To get the least significant byte: b3 = myInt & 0xFF; The 2nd least significant byte: b2 = (myInt >> 8) & 0xFF; And the 3rd least significant byte: b1 = (myInt >> 16) & 0xFF; Explanation: Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (bits 0 to 7) in that number. Shifting the number to the right 8 times puts bits 8 to 15 into bit positions 0 to 7 so ANDing with 0xFF will return the second byte. Similarly, shifting the number to the right 16 times puts bits 16 to 23 into bit positions 0 to 7 so ANDing with 0xFF returns the 3rd byte. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
} |
185,780 | I'm adding repeating events to a Cocoa app I'm working on. I have repeat every day and week fine because I can define these mathematically (3600*24*7 = 1 week). I use the following code to modify the date: [NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))] I know how many months have passed since the event was repeated but I can't figure out how to make an NSDate object that represents 1 month/3 months/6 months/9 months into the future. Ideally I want the user to say repeat monthly starting Oct. 14 and it will repeat the 14th of every month. | (Almost the same as this question .) From the documentation : Use of NSCalendarDate strongly discouraged. It is not deprecated yet, however it may be in the next major OS release after Mac OS X v10.5. For calendrical calculations, you should use suitable combinations of NSCalendar, NSDate, and NSDateComponents, as described in Calendars in Dates and Times Programming Topics for Cocoa . Following that advice: NSDate *today = [NSDate date];NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];NSDateComponents *components = [[NSDateComponents alloc] init];components.month = 1;NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];[components release];NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];nextMonthComponents.day = todayDayComponents.day;NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];[gregorian release]; There may be a more direct or efficient implementation, but this should be accurate and should point in the right direction. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13069/"
]
} |
185,781 | I read an interesting DailyWTF post today, "Out of All The Possible Answers..." and it interested me enough to dig up the original forum post where it was submitted. This got me thinking how I would solve this interesting problem - the original question is posed on Project Euler as: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest number that is evenly divisible by all of the numbers from 1 to 20? To reform this as a programming question, how would you create a function that can find the Least Common Multiple for an arbitrary list of numbers? I'm incredibly bad with pure math, despite my interest in programming, but I was able to solve this after a little Googling and some experimenting. I'm curious what other approaches SO users might take. If you're so inclined, post some code below, hopefully along with an explanation. Note that while I'm sure libraries exist to compute the GCD and LCM in various languages, I'm more interested in something that displays the logic more directly than calling a library function :-) I'm most familiar with Python, C, C++, and Perl, but any language you prefer is welcome. Bonus points for explaining the logic for other mathematically-challenged folks out there like myself. EDIT : After submitting I did find this similar question Least common multiple for 3 or more numbers but it was answered with the same basic code I already figured out and there's no real explanation, so I felt this was different enough to leave open. | This problem is interesting because it doesn't require you to find the LCM of an arbitrary set of numbers, you're given a consecutive range. You can use a variation of the Sieve of Eratosthenes to find the answer. def RangeLCM(first, last): factors = range(first, last+1) for i in range(0, len(factors)): if factors[i] != 1: n = first + i for j in range(2*n, last+1, n): factors[j-first] = factors[j-first] / factors[i] return reduce(lambda a,b: a*b, factors, 1) Edit: A recent upvote made me re-examine this answer which is over 3 years old. My first observation is that I would have written it a little differently today, using enumerate for example. A couple of small changes were necessary to make it compatible with Python 3. The second observation is that this algorithm only works if the start of the range is 2 or less, because it doesn't try to sieve out the common factors below the start of the range. For example, RangeLCM(10, 12) returns 1320 instead of the correct 660. The third observation is that nobody attempted to time this answer against any other answers. My gut said that this would improve over a brute force LCM solution as the range got larger. Testing proved my gut correct, at least this once. Since the algorithm doesn't work for arbitrary ranges, I rewrote it to assume that the range starts at 1. I removed the call to reduce at the end, as it was easier to compute the result as the factors were generated. I believe the new version of the function is both more correct and easier to understand. def RangeLCM2(last): factors = list(range(last+1)) result = 1 for n in range(last+1): if factors[n] > 1: result *= factors[n] for j in range(2*n, last+1, n): factors[j] //= factors[n] return result Here are some timing comparisons against the original and the solution proposed by Joe Bebel which is called RangeEuclid in my tests. >>> t=timeit.timeit>>> t('RangeLCM.RangeLCM(1, 20)', 'import RangeLCM')17.999292996735676>>> t('RangeLCM.RangeEuclid(1, 20)', 'import RangeLCM')11.199833288867922>>> t('RangeLCM.RangeLCM2(20)', 'import RangeLCM')14.256165588084514>>> t('RangeLCM.RangeLCM(1, 100)', 'import RangeLCM')93.34979585394194>>> t('RangeLCM.RangeEuclid(1, 100)', 'import RangeLCM')109.25695507389901>>> t('RangeLCM.RangeLCM2(100)', 'import RangeLCM')66.09684505991709 For the range of 1 to 20 given in the question, Euclid's algorithm beats out both my old and new answers. For the range of 1 to 100 you can see the sieve-based algorithm pull ahead, especially the optimized version. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/185781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20840/"
]
} |
185,804 | I created an app for a small business. Some of the employees in the office can not see the form correctly. The reason is they have their DPI setting set to above 96dpi. Does anybody know of a way to control this? For all of you who have experience with winforms apps, how do you control your form layout so that DPI does not affect the look of the application? | Assuming you do not try to honor the user's UI font choice (SystemFonts.IconTitleFont), and hard-code your forms for one font size only (e.g. Tahoma 8pt, Microsoft Sans Serif 8.25pt), you can set your form's AutoScaleMode to ScaleMode.Dpi . This will scale the size of the form and most of it child controls by the factor CurrentDpiSetting / 96 by calling Form.Scale() , which in turns calls the protected ScaleControl() method recursivly on itself and all child controls. ScaleControl will increase a control's position, size, font, etc as needed for the new scaling factor. Warning: Not all controls properly scale themselves. The columns of a listview, for example, will not get wider as the font gets larger. In order to handle that you'll have to manually perform additional scaling as required. i do this by overriding the protected ScaleControl() method, and scaling the listview columns manually: public class MyForm : Form{ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { base.ScaleControl(factor, specified); Toolkit.ScaleListViewColumns(listView1, factor); }}public class Toolkit { /// <summary> /// Scale the columns of a listview by the Width scale factor specified in factor /// </summary> /// <param name="listview"></param> /// <param name="factor"></param> /// <example>/* /// protected override void ScaleControl(SizeF factor, BoundsSpecified specified) /// { /// base.ScaleControl(factor, specified); /// /// //ListView columns are not automatically scaled with the ListView, so we /// //must do it manually /// Toolkit.ScaleListViewColumns(lvPermissions, factor); /// } ///</example> public static void ScaleListViewColumns(ListView listview, SizeF factor) { foreach (ColumnHeader column in listview.Columns) { column.Width = (int)Math.Round(column.Width * factor.Width); } }} This is all well and good if you're just using controls. But if you ever use any hard-coded pixel sizes, you'll need to scale your pixel widths and lengths by the current scale factor of the form. Some examples of situations that could have hard-coded pixel sizes: drawing a 25px high rectangle drawing an image at location (11,56) on the form stretch drawing an icon to 48x48 drawing text using Microsoft Sans Serif 8.25pt getting the 32x32 format of an icon and stuffing it into a PictureBox If this is the case, you'll need to scale those hard-coded values by the " current scaling factor ". Unfortunatly the "current" scale factor is not provided, we need to record it ourselves. The solution is to assume that initially the scaling factor is 1.0 and each time ScaleControl() is called, modify the running scale factor by the new factor. public class MyForm : Form{ private SizeF currentScaleFactor = new SizeF(1f, 1f); protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { base.ScaleControl(factor, specified); //Record the running scale factor used this.currentScaleFactor = new SizeF( this.currentScaleFactor.Width * factor.Width, this.currentScaleFactor.Height * factor.Height); Toolkit.ScaleListViewColumns(listView1, factor); }} Initially the scaling factor is 1.0 . If form is then scaled by 1.25 , the scaling factor then becomes: 1.00 * 1.25 = 1.25 //scaling current factor by 125% If the form is then scaled by 0.95 , the new scaling factor becomes 1.25 * 0.95 = 1.1875 //scaling current factor by 95% The reason a SizeF is used (rather than a single floating point value) is that scaling amounts can be different in the x and y directions. If a form is set to ScaleMode.Font , the form is scaled to the new font size. Fonts can have different aspect ratios ( e.g. Segoe UI is taller font than Tahoma ). This means you have to scale x and y values independantly. So if you wanted to place a control at location (11,56) , you would have to change your positioning code from: Point pt = new Point(11, 56);control1.Location = pt; to Point pt = new Point( (int)Math.Round(11.0*this.scaleFactor.Width), (int)Math.Round(56.0*this.scaleFactor.Height));control1.Location = pt; The same applies if you were going to pick a font size: Font f = new Font("Segoe UI", 8, GraphicsUnit.Point); would have to become: Font f = new Font("Segoe UI", 8.0*this.scaleFactor.Width, GraphicsUnit.Point); And extracting a 32x32 icon to a bitmap would change from: Image i = new Icon(someIcon, new Size(32, 32)).ToBitmap(); to Image i = new Icon(someIcon, new Size( (int)Math.Round(32.0*this.scaleFactor.Width), (int)Math.Round(32.0*this.scaleFactor.Height))).ToBitmap(); etc. Supporting non-standard DPI displays is a tax that all developers should pay . But the fact that nobody wants to is why Microsoft gave up and added to Vista the ability for the graphics card to stretch any applications that don't say they properly handle high-dpi . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/185804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21325/"
]
} |
185,836 | Does anyone know if it possible to define the equivalent of a "java custom class loader" in .NET? To give a little background: I am in the process of developing a new programming language that targets the CLR, called "Liberty". One of the features of the language is its ability to define "type constructors", which are methods that are executed by the compiler at compile time and generate types as output. They are sort of a generalization of generics (the language does have normal generics in it), and allow code like this to be written (in "Liberty" syntax): var t as tuple<i as int, j as int, k as int>;t.i = 2;t.j = 4;t.k = 5; Where "tuple" is defined like so: public type tuple(params variables as VariableDeclaration[]) as TypeDeclaration{ //...} In this particular example, the type constructor tuple provides something similar to anonymous types in VB and C#. However, unlike anonymous types, "tuples" have names and can be used inside public method signatures. This means that I need a way for the type that eventually ends up being emitted by the compiler to be shareable across multiple assemblies. For example, I want tuple<x as int> defined in Assembly A to end up being the same type as tuple<x as int> defined in Assembly B. The problem with this, of course, is that Assembly A and Assembly B are going to be compiled at different times, which means they would both end up emitting their own incompatible versions of the tuple type. I looked into using some sort of "type erasure" to do this, so that I would have a shared library with a bunch of types like this (this is "Liberty" syntax): class tuple<T>{ public Field1 as T;}class tuple<T, R>{ public Field2 as T; public Field2 as R;} and then just redirect access from the i, j, and k tuple fields to Field1 , Field2 , and Field3 . However that is not really a viable option. This would mean that at compile time tuple<x as int> and tuple<y as int> would end up being different types, while at runtime time they would be treated as the same type. That would cause many problems for things like equality and type identity. That is too leaky of an abstraction for my tastes. Other possible options would be to use "state bag objects". However, using a state bag would defeat the whole purpose of having support for "type constructors" in the language. The idea there is to enable "custom language extensions" to generate new types at compile time that the compiler can do static type checking with. In Java, this could be done using custom class loaders. Basically the code that uses tuple types could be emitted without actually defining the type on disk. A custom "class loader" could then be defined that would dynamically generate the tuple type at runtime. That would allow static type checking inside the compiler, and would unify the tuple types across compilation boundaries. Unfortunately, however, the CLR does not provide support for custom class loading. All loading in the CLR is done at the assembly level. It would be possible to define a separate assembly for each "constructed type", but that would very quickly lead to performance problems (having many assemblies with only one type in them would use too many resources). So, what I want to know is: Is it possible to simulate something like Java Class Loaders in .NET, where I can emit a reference to a non-existing type in and then dynamically generate a reference to that type at runtime before the code the needs to use it runs? NOTE: *I actually already know the answer to the question, which I provide as an answer below. However, it took me about 3 days of research, and quite a bit of IL hacking in order to come up with a solution. I figured it would be a good idea to document it here in case anyone else ran into the same problem. * | The answer is yes, but the solution is a little tricky. The System.Reflection.Emit namespace defines types that allows assemblies to be generated dynamically. They also allow the generated assemblies to be defined incrementally. In other words it is possible to add types to the dynamic assembly, execute the generated code, and then latter add more types to the assembly. The System.AppDomain class also defines an AssemblyResolve event that fires whenever the framework fails to load an assembly. By adding a handler for that event, it is possible to define a single "runtime" assembly into which all "constructed" types are placed. The code generated by the compiler that uses a constructed type would refer to a type in the runtime assembly. Because the runtime assembly doesn't actually exist on disk, the AssemblyResolve event would be fired the first time the compiled code tried to access a constructed type. The handle for the event would then generate the dynamic assembly and return it to the CLR. Unfortunately, there are a few tricky points to getting this to work. The first problem is ensuring that the event handler will always be installed before the compiled code is run. With a console application this is easy. The code to hookup the event handler can just be added to the Main method before the other code runs. For class libraries, however, there is no main method. A dll may be loaded as part of an application written in another language, so it's not really possible to assume there is always a main method available to hookup the event handler code. The second problem is ensuring that the referenced types all get inserted into the dynamic assembly before any code that references them is used. The System.AppDomain class also defines a TypeResolve event that is executed whenever the CLR is unable to resolve a type in a dynamic assembly. It gives the event handler the opportunity to define the type inside the dynamic assembly before the code that uses it runs. However, that event will not work in this case. The CLR will not fire the event for assemblies that are "statically referenced" by other assemblies, even if the referenced assembly is defined dynamically. This means that we need a way to run code before any other code in the compiled assembly runs and have it dynamically inject the types it needs into the runtime assembly if they have not already been defined. Otherwise when the CLR tried to load those types it will notice that the dynamic assembly does not contain the types they need and will throw a type load exception. Fortunately, the CLR offers a solution to both problems: Module Initializers. A module initializer is the equivalent of a "static class constructor", except that it initializes an entire module, not just a single class. Baiscally, the CLR will: Run the module constructor before any types inside the module are accessed. Guarantee that only those types directly accessed by the module constructor will be loaded while it is executing Not allow code outside the module to access any of it's members until after the constructor has finished. It does this for all assemblies, including both class libraries and executables, and for EXEs will run the module constructor before executing the Main method. See this blog post for more information about constructors. In any case, a complete solution to my problem requires several pieces: The following class definition, defined inside a "language runtime dll", that is referenced by all assemblies produced by the compiler (this is C# code). using System;using System.Collections.Generic;using System.Reflection;using System.Reflection.Emit;namespace SharedLib{ public class Loader { private Loader(ModuleBuilder dynamicModule) { m_dynamicModule = dynamicModule; m_definedTypes = new HashSet<string>(); } private static readonly Loader m_instance; private readonly ModuleBuilder m_dynamicModule; private readonly HashSet<string> m_definedTypes; static Loader() { var name = new AssemblyName("$Runtime"); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); var module = assemblyBuilder.DefineDynamicModule("$Runtime"); m_instance = new Loader(module); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); } static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (args.Name == Instance.m_dynamicModule.Assembly.FullName) { return Instance.m_dynamicModule.Assembly; } else { return null; } } public static Loader Instance { get { return m_instance; } } public bool IsDefined(string name) { return m_definedTypes.Contains(name); } public TypeBuilder DefineType(string name) { //in a real system we would not expose the type builder. //instead a AST for the type would be passed in, and we would just create it. var type = m_dynamicModule.DefineType(name, TypeAttributes.Public); m_definedTypes.Add(name); return type; } }} The class defines a singleton that holds a reference to the dynamic assembly that the constructed types will be created in. It also holds a "hash set" that stores the set of types that have already been dynamically generated, and finally defines a member that can be used to define the type. This example just returns a System.Reflection.Emit.TypeBuilder instance that can then be used to define the class being generated. In a real system, the method would probably take in an AST representation of the class, and just do the generation it's self. Compiled assemblies that emit the following two references (shown in ILASM syntax): .assembly extern $Runtime{ .ver 0:0:0:0}.assembly extern SharedLib{ .ver 1:0:0:0} Here "SharedLib" is the Language's predefined runtime library that includes the "Loader" class defined above and "$Runtime" is the dynamic runtime assembly that the consructed types will be inserted into. A "module constructor" inside every assembly compiled in the language. As far as I know, there are no .NET languages that allow Module Constructors to be defined in source. The C++ /CLI compiler is the only compiler I know of that generates them. In IL, they look like this, defined directly in the module and not inside any type definitions: .method privatescope specialname rtspecialname static void .cctor() cil managed{ //generate any constructed types dynamically here...} For me, It's not a problem that I have to write custom IL to get this to work. I'm writing a compiler, so code generation is not an issue. In the case of an assembly that used the types tuple<i as int, j as int> and tuple<x as double, y as double, z as double> the module constructor would need to generate types like the following (here in C# syntax): class Tuple_i_j<T, R>{ public T i; public R j;}class Tuple_x_y_z<T, R, S>{ public T x; public R y; public S z;} The tuple classes are generated as generic types to get around accessibility issues. That would allow code in the compiled assembly to use tuple<x as Foo> , where Foo was some non-public type. The body of the module constructor that did this (here only showing one type, and written in C# syntax) would look like this: var loader = SharedLib.Loader.Instance;lock (loader){ if (! loader.IsDefined("$Tuple_i_j")) { //create the type. var Tuple_i_j = loader.DefineType("$Tuple_i_j"); //define the generic parameters <T,R> var genericParams = Tuple_i_j.DefineGenericParameters("T", "R"); var T = genericParams[0]; var R = genericParams[1]; //define the field i var fieldX = Tuple_i_j.DefineField("i", T, FieldAttributes.Public); //define the field j var fieldY = Tuple_i_j.DefineField("j", R, FieldAttributes.Public); //create the default constructor. var constructor= Tuple_i_j.DefineDefaultConstructor(MethodAttributes.Public); //"close" the type so that it can be used by executing code. Tuple_i_j.CreateType(); }} So in any case, this was the mechanism I was able to come up with to enable the rough equivalent of custom class loaders in the CLR. Does anyone know of an easier way to do this? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/185836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737192/"
]
} |
185,844 | What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors: class foo{ private: static int i;};int foo::i = 0; I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this? | The class declaration should be in the header file (Or in the source file if not shared). File: foo.h class foo{ private: static int i;}; But the initialization should be in source file. File: foo.cpp int foo::i = 0; If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.The initialisation of the static int i must be done outside of any function. Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const integer type ( bool , char , char8_t [since C++20], char16_t , char32_t , wchar_t , short , int , long , long long , or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants. ). You can then declare and initialize the member variable directly inside the class declaration in the header file: class foo{ private: static int const i = 42;}; | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/185844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
185,893 | I have a production server running with the following flag: - XX:+HeapDumpOnOutOfMemoryError Last night it generated a java-38942.hprof file when our server encountered a heap error. It turns out that the developers of the system knew of the flag but no way to get any useful information from it. Any ideas? | If you want a fairly advanced tool to do some serious poking around, look at the Memory Analyzer project at Eclipse, contributed to them by SAP. Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-memory objects, i.e. SELECT toString(firstName) FROM com.yourcompany.somepackage.User Totally brilliant. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
]
} |
185,899 | Recently I was asked this during a job interview. I was honest and said I knew how a symbolic link behaves and how to create one, but do not understand the use of a hard link and how it differs from a symbolic one. | Underneath the file system, files are represented by inodes. (Or is it multiple inodes? Not sure.) A file in the file system is basically a link to an inode. A hard link, then, just creates another file with a link to the same underlying inode. When you delete a file, it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted. A symbolic link is a link to another name in the file system. Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode. Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/185899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
]
} |
185,934 | It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object. Here's a simple, contrived proof: <?phpclass A { public $b;}function set_b($obj) { $obj->b = "after"; }$a = new A();$a->b = "before";$c = $a; //i would especially expect this to create a copy.set_b($a);print $a->b; //i would expect this to show 'before'print $c->b; //i would ESPECIALLY expect this to show 'before'?> In both print cases I am getting 'after' So, how do I pass $a to set_b() by value, not by reference? | In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated). You can use the 'clone' operator in PHP5 to copy objects: $objectB = clone $objectA; Also, it's just objects that are passed by reference, not everything as you've said in your question... | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
]
} |
185,936 | How can I delete the contents of a local folder in Python? The current project is for Windows, but I would like to see *nix also. | import os, shutilfolder = '/path/to/folder'for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/185936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
185,937 | I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down. Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project. Anyhow - I was developing a basic shopping cart which could contain an ArrayList of Book objects . In order to implement the addBook() , removeBook() , and hasBook() methods of the Cart, I wanted to check if the Book already existed in the Cart . So off I go - public boolean equals(Book b) { ... // More code here - null checks if (b.getID() == this.getID()) return true; else return false;} All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much. Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following: public boolean hasBook(int i) { Book b = new Book(i); return hasBook(b);}public boolean hasBook(Book b) { // .. more code here return this.books.contains(b);} All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following: public boolean equals(Object o) { Book b = (Book) o; ... // The rest goes here } Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly was a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light? | In Java, the equals() method that is inherited from Object is: public boolean equals(Object other); In other words, the parameter must be of type Object . This is called overriding ; your method public boolean equals(Book other) does what is called overloading to the equals() method. The ArrayList uses overridden equals() methods to compare contents (e.g. for its contains() and equals() methods), not overloaded ones. In most of your code, calling the one that didn't properly override Object 's equals was fine, but not compatible with ArrayList . So, not overriding the method correctly can cause problems. I override equals the following everytime: @Overridepublic boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (!(other instanceof MyClass)) return false; MyClass otherMyClass = (MyClass)other; ...test other properties here...} The use of the @Override annotation can help a ton with silly mistakes. Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
]
} |
185,947 | As a programming exercise, I've written a Ruby snippet that creates a class, instantiates two objects from that class, monkeypatches one object, and relies on method_missing to monkeypatch the other one. Here's the deal. This works as intended: class Monkey def chatter puts "I am a chattering monkey!" end def method_missing(m) puts "No #{m}, so I'll make one..." def screech puts "This is the new screech." end endendm1 = Monkey.newm2 = Monkey.newm1.chatterm2.chatterdef m1.screech puts "Aaaaaargh!"endm1.screechm2.screechm2.screechm1.screechm2.screech You'll notice that I have a parameter for method_missing. I did this because I was hoping to use define_method to dynamically create missing methods with the appropriate name. However, it doesn't work. In fact, even using define_method with a static name like so: def method_missing(m) puts "No #{m}, so I'll make one..." define_method(:screech) do puts "This is the new screech." endend Ends with the following result: ArgumentError: wrong number of arguments (2 for 1)method method_missing in untitled document at line 9method method_missing in untitled document at line 9at top level in untitled document at line 26Program exited. What makes the error message more bewildering is that I only have one argument for method_missing ... | define_method is a (private) method of the object Class . You are calling it from an instance . There is no instance method called define_method , so it recurses to your method_missing , this time with :define_method (the name of the missing method), and :screech (the sole argument you passed to define_method ). Try this instead (to define the new method on all Monkey objects): def method_missing(m) puts "No #{m}, so I'll make one..." self.class.send(:define_method, :screech) do puts "This is the new screech." endend Or this (to define it only on the object it is called upon, using the object's "eigenclass"): def method_missing(m) puts "No #{m}, so I'll make one..." class << self define_method(:screech) do puts "This is the new screech." end endend | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/185947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21493/"
]
} |
185,965 | What is the best way to create a custom title for pages in a Rails app without using a plug-in? | In your views do something like this: <% content_for :title, "Title for specific page" %><!-- or --><h1><%= content_for(:title, "Title for specific page") %></h1> The following goes in the layout file: <head> <title><%= yield(:title) %></title> <!-- Additional header tags here --></head><body> <!-- If all pages contain a headline tag, it's preferable to put that in the layout file too --> <h1><%= yield(:title) %></h1></body> It's also possible to encapsulate the content_for and yield(:title) statements in helper methods (as others have already suggested). However, in simple cases such as this one I like to put the necessary code directly into the specific views without custom helpers. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/185965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
]
} |
185,966 | <div id="myDiv"> <a>...</a> <a>...</a> <a>...</a> <a>...</a> <a>...</a> <a>...</a></div> If you wanted to select the 2nd, 3rd and 4th a tags in the above example, how would you do that? The only thing I can think of is: $("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)") But that doesn't look to be very efficient or pretty. I guess you could also select ALL the a s and then do run .each over them, but that could get very inefficient if there were a lot more a s. | jQuery slice() function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself. In your particular case you should use $("#myDiv a").slice(1, 4) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/185966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.