source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
167,946
As part of the base class for some extensive unit testing, I am writing a helper function which recursively compares the nodes of one XmlDocument object to another in C# (.NET). Some requirements of this: The first document is the source , e.g. what I want the XML document to look like. Thus the second is the one I want to find differences in and it must not contain extra nodes not in the first document. Must throw an exception when too many significant differences are found, and it should be easily understood by a human glancing at the description. Child element order is important, attributes can be in any order. Some attributes are ignorable; specifically xsi:schemaLocation and xmlns:xsi , though I would like to be able to pass in which ones are. Prefixes for namespaces must match in both attributes and elements. Whitespace between elements is irrelevant. Elements will either have child elements or InnerText , but not both. While I'm scrapping something together: has anyone written such code and would it be possible to share it here? On an aside, what would you call the first and second documents? I've been referring to them as "source" and "target", but it feels wrong since the source is what I want the target to look like, else I throw an exception.
Microsoft has an XML diff API that you can use. Unofficial NuGet: https://www.nuget.org/packages/XMLDiffPatch .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/167946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ] }
167,952
Null or empty string -- is one better than the other to represent no data in a table column? (I specifically use MySQL, but I'm thinking this is system-independent.) Are there major advantages/disadvantages to using one over the other, or is it simply programmer preference?
I strongly disagree with everyone who says to unconditionally use NULL. Allowing a column to be NULL introduces an additional state that you wouldn't have if you set the column up as NOT NULL. Do not do this if you don't need the additional state. That is, if you can't come up with a difference between the meaning of empty string and the meaning of null, then set the column up as NOT NULL and use empty string to represent empty. Representing the same thing in two different ways is a bad idea. Most of the people who told you to use NULL also gave an example where NULL would mean something different than empty string. And in those examples, they are right. Most of the time, however, NULL is a needless extra state that just forces programmers to have to handle more cases. As others have mentioned, Oracle does not allow this extra state to exist because it treats NULL and empty string as the same thing (it is impossible to store an empty string in a column that does not allow null in Oracle).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/167952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7596/" ] }
168,017
Does any one know how can I convert a BSTR to an int in VC++ 2008 Thanks in advance.
You can pass a BSTR safely to any function expecting a wchar_t * . So you can use _wtoi ().
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24927/" ] }
168,037
I have an application that takes the quality results for a manufacturing process and creates graphs both to show Pareto charts of the bad, and also to show production throughput. To automate the task of testing these statistical procedures I would like to deterministically be able to add records into the database and have the quality tech go to certain graphs and compare to a known good graph. But, I also would like to simulate the results so they would go into the database as if a user was running through the testing process. One idea I have had is to fill a list with i number good, j number bad1, k number bad 2, etc. And then somehow randomly sort the list before insertion into the database. So, my question, is there a standard algorithm to take a sorted list of values and create a randomly sorted list?
You'll want to use a shuffle algorithm. Make sure to use a proper shuffle algorithm and not a home-baked one, because it may introduce some form of subtle pattern to the data. See this post by Jeff Atwood about the problem with using "random enough" shuffles.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425/" ] }
168,119
I have a pretty unusual problem (for me). I am writing an application that will allow a user to change their system time forward or back either by explicit date (change my date to 6/3/1955) or by increment using buttons (go forward 1 month). I'm writing this to help some of my users test some software that requires jumps like this in order to simulate real world usage of a billing system. Changing the time in Delphi is of course very easy: SetDateTime(2008,05,21,16,07,21,00); But I'm not sure if Delphi (2006) has any built in helpers for date math, which is one of my least favorite things :) Any suggestions for the best way to handle this? I'd prefer to stay native as the winapi datetime calls suck. Thanks!
As mentioned by gabr and mliesen, have a look at the DateUtils and SysUtils units, useful functions include. IncDay - Add a or subtract a number of days. IncMonth - Add a or subtract a number of months. IncWeek - Add a or subtract a number of weeks. IncYear - Add a or subtract a number of years. EncodeDate - Returns a TDateTime value from the Year, Month, and Day params.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172/" ] }
168,169
Has anyone else seen people do this: private string _name;public string Name{ get{ return _name; } set{ _name = value;}} I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to do this, why not just make the variable public to begin with? Am I missing something?
If you make the member a public field, then you can't later refactor it into a property without changing the interface to your class. If you expose it as a property from the very beginning, you can make whatever changes to the property accessor functions that you need and the class's interface remains unchanged. Note that as of C# 3.0, you can implement a property without creating a backing field, e.g.: public string Name { get; set; } This removes what is pretty much the only justification for not implementing public fields as properties in the first place.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/168169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19038/" ] }
168,170
Do .net applications run on linux? Are there any free/paid interop libraries available ?
Mono is a .NET-compatible platform, including compiler and runtime. The Mono Migration Analyzer helps figure out compatibility issues.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/168170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13337/" ] }
168,171
Can someone provide a regular expression for parsing name/value pairs from a string? The pairs are separated by commas, and the value can optionally be enclosed in quotes. For example: AssemblyName=foo.dll,ClassName="SomeClass",Parameters="Some,Parameters"
No escape: /([^=,]*)=("[^"]*"|[^,"]*)/ Double quote escape for both key and value: /((?:"[^"]*"|[^=,])*)=((?:"[^"]*"|[^=,])*)/key=value,"key with "" in it"="value with "" in it",key=value" "with" "spaces Backslash string escape: /([^=,]*)=("(?:\\.|[^"\\]+)*"|[^,"]*)/key=value,key="value",key="val\"ue" Full backslash escape: /((?:\\.|[^=,]+)*)=("(?:\\.|[^"\\]+)*"|(?:\\.|[^,"\\]+)*)/key=value,key="value",key="val\"ue",ke\,y=val\,ue Edit: Added escaping alternatives. Edit2: Added another escaping alternative. You would have to clean up the keys/values by removing any escape-characters and surrounding quotes.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/168171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ] }
168,173
I have a webpage that pulls information from a database, converts it to .csv format, and writes the file to the HTTPResponse. string csv = GetCSV();Response.Clear();Response.ContentType = "text/csv";Response.Write(csv); This works fine, and the file is sent to the client with no problems. However, when the file is sent to the client, the name of the current page is used, instead of a more friendly name (like "data.csv"). My question is, how can I change the name of the file that is written to the output stream without writing the file to disk and redirecting the client to the file's url? EDIT: Thanks for the responses guys. I got 4 of the same response, so I just chose the first one as the answer.
I believe this will work for you. Response.AddHeader("content-disposition", "attachment; filename=NewFileName.csv");
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21461/" ] }
168,214
What is the easiest way to encode a PHP string for output to a JavaScript variable? I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable. Normally, I would just construct my JavaScript in a PHP file, à la: <script> var myvar = "<?php echo $myVarValue;?>";</script> However, this doesn't work when $myVarValue contains quotes or newlines.
Expanding on someone else's answer: <script> var myvar = <?php echo json_encode($myVarValue); ?>;</script> Using json_encode() requires: PHP 5.2.0 or greater $myVarValue encoded as UTF-8 (or US-ASCII, of course) Since UTF-8 supports full Unicode, it should be safe to convert on the fly. Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/168214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13238/" ] }
168,236
I am trying to set attributes for an IFRAME html control from the code-behind aspx.cs file. I came across a post that says you can use FindControl to find the non-asp controls using: The aspx file contains: <iframe id="contentPanel1" runat="server" /> and then the code-behind file contains: protected void Page_Load(object sender, EventArgs e){ HtmlControl contentPanel1 = (HtmlControl)this.FindControl("contentPanel1"); if (contentPanel1 != null) contentPanel1.Attributes["src"] = "http://www.stackoverflow.com";} Except that it's not finding the control, contentPanel1 is null. Update 1 Looking at the rendered html: <iframe id="ctl00_ContentPlaceHolder1_contentPanel1"></iframe> i tried changing the code-behind to: HtmlControl contentPanel1 = (HtmlControl)this.FindControl("ctl00_ContentPlaceHolder1_contentPanel1");if (contentPanel1 != null) contentPanel1.Attributes["src"] = "http://www.clis.com"; But it didn't help. i am using a MasterPage. Update 2 Changing the aspx file to: <iframe id="contentPanel1" name="contentPanel1" runat="server" /> also didn't help Answer The answer is obvious, and unworthy of even asking the original question. If you have the aspx code: <iframe id="contentPanel1" runat="server" /> and want to access the iframe from the code-behind file, you just access it: this.contentPanel1.Attributes["src"] = "http://www.stackoverflow.com";
If the iframe is directly on the page where the code is running, you should be able to reference it directly: contentPanel1.Attribute = value; If not (it's in a child control, or the MasterPage), you'll need a good idea of the hierarchy of the page... Or use the brute-force method of writing a recursive version of FindControl().
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ] }
168,249
Let's say I have a multithreaded C++ program that handles requests in the form of a function call to handleRequest(string key) . Each call to handleRequest occurs in a separate thread, and there are an arbitrarily large number of possible values for key . I want the following behavior: Simultaneous calls to handleRequest(key) are serialized when they have the same value for key . Global serialization is minimized. The body of handleRequest might look like this: void handleRequest(string key) { KeyLock lock(key); // Handle the request.} Question: How would I implement KeyLock to get the required behavior? A naive implementation might start off like this: KeyLock::KeyLock(string key) { global_lock->Lock(); internal_lock_ = global_key_map[key]; if (internal_lock_ == NULL) { internal_lock_ = new Lock(); global_key_map[key] = internal_lock_; } global_lock->Unlock(); internal_lock_->Lock();}KeyLock::~KeyLock() { internal_lock_->Unlock(); // Remove internal_lock_ from global_key_map iff no other threads are waiting for it.} ...but that requires a global lock at the beginning and end of each request, and the creation of a separate Lock object for each request. If contention is high between calls to handleRequest , that might not be a problem, but it could impose a lot of overhead if contention is low.
You could do something similar to what you have in your question, but instead of a single global_key_map have several (probably in an array or vector) - which one is used is determined by some simple hash function on the string. That way instead of a single global lock, you spread that out over several independent ones. This is a pattern that is often used in memory allocators (I don't know if the pattern has a name - it should). When a request comes in, something determines which pool the allocation will come from (usually the size of the request, but other parameters can factor in as well), then only that pool needs to be locked. If an allocation request comes in from another thread that will use a different pool, there's no lock contention.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24923/" ] }
168,369
After working for a few days with Eclipse Java I totally got addicted to pressing Ctrl and clicking on an identifier to go to its definition. Since then I've been looking for a way to achieve this in Visual Studio as well. I realize VS has right click, Go to definition, and that F12 does the same. I also realize that Visual Assist does something similar with Alt + G . Yet none of these are as perfect as Ctrl + click. I've actually tried my luck for a few hours trying to write a VS plugin to do it but didn't get anywhere in the time frame I thought reasonable for this. Does anyone know how this could be achieved? A ready plugin? A macro of some kind?
If you use Visual Studio 2010, you can use the free Visual Studio 2010 Productivity Power Tools from Microsoft to achieve this.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/168369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ] }
168,375
I find that quite often Visual Studio memory usage will average ~150-300 MB of RAM. As a developer who very often needs to run with multiple instances of Visual Studio open, are there any performance tricks to optimize the amount of memory that VS uses? I am running VS 2005 with one add-in (TFS)
From this blog post : [...] These changes are all available from the Options dialog (Tools –> Options): Environment General : Disable “Animate environment tools” Documents : Disable “Detect when file is changed outside the environment” Keyboard : Remove the F1 key from the Help.F1Help command Help\Online : Set “When loading Help content” to “Try local first, then online” or “Try local only, not online” Startup : Change the “At startup” option to “Show empty environment” Projects and Solutions General : Disable “Track Active Item in Solution Explorer” Text Editor General (for each language you want): Disable “Navigation bar” (this is the toolbar that shows the objects and procedures drop down lists allowing you to choose a particular object in your code. Disable “Track changes” Windows Forms Designer General : Set “AutotoolboxPopulate” to false. Set “EnableRefactoringOnRename” to false.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15683/" ] }
168,409
What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?
I've done this in the past for a Python script to determine the last updated files in a directory: import globimport ossearch_dir = "/mydir/"# remove anything from the list that is not a file (directories, symlinks)# thanks to J.F. Sebastion for pointing out that the requirement was a list # of files (presumably not including directories) files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))files.sort(key=lambda x: os.path.getmtime(x)) That should do what you're looking for based on file mtime. EDIT : Note that you can also use os.listdir() in place of glob.glob() if desired - the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here's what it would look like: import ossearch_dir = "/mydir/"os.chdir(search_dir)files = filter(os.path.isfile, os.listdir(search_dir))files = [os.path.join(search_dir, f) for f in files] # add path to each filefiles.sort(key=lambda x: os.path.getmtime(x))
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/168409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24953/" ] }
168,426
One of the few annoying things about the Eclipse Java plug-in is the absence of a keyboard shortcut to build the project associated with the current resource. Anyone know how to go about it?
In the Preferences dialog box, under the General section is a dialog box called "Keys". This lets you attach key bindings to many events, including Build Project.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/168426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24039/" ] }
168,427
Which of Crystal Reports and SSRS (SQL Server Reporting Services) is better to use?
On the one-hand, Crystal Reports is a steaming pile of expensive and overhyped donkey poo, and on the other hand SSRS actually fulfils all the promises that CR marketing makes - and it's free. My contempt for CR stems from many years of being obliged to use the horrible thing. There's really no point in detailing the utter odiousness of CR when I can give you references like Clubbing the Crystal Dodo or Crystal Reports Sucks Donkey Dork (not as funny but rather more literate and substantiated with technical details). Free?! Yup. You don't even have to buy MS SQL Server to get it - you can install SQL Express with Advanced Services. This is available as a download that includes SQL Server Reporting Services . While SQL Express is limited in the number of concurrent users it can support, the following observations are salient: The licence for SSRS obtained aspart of SQL Express only requiresthat it be deployed as part of SQLExpress. There is nothing forbiddingconnection to other data sources orrequiring that a report obtain datafrom SQL Server. The abovementioned version of SSRShas no intrinsic restrictions onuser connections. All limitationsare imposed on the SQL Expressdatabase engine. SSRS uses ADO.NET, which includes,out of the box, drivers for Oracle,Jet (Access), OLEDB and ODBC Thus you can connect the free version of SSRS to any back-end to which you can connect ADO.NET, which includes (for example) MySQL. I am told by Rory in a comment below that this is "not supported". That's true but I can't find anything in the licence that forbids it and while the drivers are not supplied by SSExpress they certainly are supplied by most versions of Visual Studio and you can ship them in your setup kit. This may not be an expressly supported configuration but so what? Even if you did have a full MSSQL licence it would be asking a bit much to expect Microsoft to help you talk to some third party database (not to mention a bit weird). I use SSRS extensively at work both for inward facing reports and for outward facing reports embedded in ASP.NET applications that provide bureau services to large numbers of paying customers. In our case it happens that the backing store is a licensed copy of Microsoft SQL Server 2008, but this is incidental to the technical merits of our reporting solution. There is a long list of capabilities that Crystal Reports claims to support but which either don't work or which require a staggeringly expensive licence if you want more than five users. You can't even trust CR to do SQL correctly. SELECT COUNT(*) FROM SOMETABLE WHERE 1=0 should produce a result of zero but it it produces one . The built-in query engine is defective, and a team that screws up something a bunch of amateurs can do for free (eg MySQL) has no hope of getting anything you'd describe as performance out of their code. And they don't. The evil thing leaks memory like a bucket with no bottom, and if you use SQL profiling tools you will find it is spectacularly inefficient. As for the alleged support, I can personally attest that dialog resize bugs have gone uncorrected for decades after they were first publicly documented. If you get out your credit card and pay the extortionate ransoms demanded (I too would want handsome pay to support such a horror) you will find yourself talking to someone who claims his name is David, but inexplicably pronounces it "Dah-feet", and who doesn't even understand your question, much less have an answer. The SSRS support situation is fairly similar, but it actually works so you don't really need much. SSRS, on the other hand, does everything that CR claims to. It is not without bugs, but they are delightfully few, and they seldom survive more than one release cycle. The SSRS designer UI is hosted within the Visual Studio IDE. It is attractively presented in typical Microsoft style, but more than this it is quite well thought out, incorporating several simple but fundamental departures from traditional report designers. For example, to present tabular data you define a table rather than fiddling about with individual text boxes. As a result you don't have to screw around trying to line them up, and putting borders on them is a trivial stylesheet exercise. SSRS actually does all the things CR claims to, it's inexpensive, there is extensive reliable technical documentation, it's designed to be extended (also documented) and you can connect it to anything for which you can get an ODBC driver. This is a no brainer. Some shortcomings of SSRS It is not obvious how to bind fields in page headers and footers. It is not possible (so far as I know) to position relative to the bottom of a page. This is a genuine problem for certain types of report, and one for which I can think of no workaround. There's no support for expando horizontal rollups in cross-tabulations. There's no direct support for report headers and footers. Use Rectangle objects at top and bottom of the report layout, with pagebreaking properties set appropriately. Or use subreports. The people who complain about this obviously haven't tried very hard. Lack of support for overlapping group intervals (the CR grouping system can do this) UPDATE SSRS 2008 R2 now supports this. It's buried in the grouping edit dialog. Look up "group variables" and read this . It actually looks like overlapping groups can be done with SSRS2005 too, although I never knew that. I wonder did anyone ever crack the bottom-relative positioning issue?
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/168427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14299/" ] }
168,455
How do you post data to an iframe?
Depends what you mean by "post data". You can use the HTML target="" attribute on a <form /> tag, so it could be as simple as: <form action="do_stuff.aspx" method="post" target="my_iframe"> <input type="submit" value="Do Stuff!"></form><!-- when the form is submitted, the server response will appear in this iframe --><iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe> If that's not it, or you're after something more complex, please edit your question to include more detail. There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here ), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3. I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself. default.asp <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html> <head> <title>Form Iframe Demo</title> </head> <body> <form action="do_stuff.asp" method="post" target="my_frame"> <input type="text" name="someText" value="Some Text"> <input type="submit"> </form> <iframe name="my_frame" src="do_stuff.asp"> </iframe> </body></html> do_stuff.asp <%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html> <head> <title>Form Iframe Demo</title> </head> <body> <% if (Request.Form.Count) { %> You typed: <%=Request.Form("someText").Item%> <% } else { %> (not submitted) <% } %> </body></html> I would be very interested to hear of any browser that doesn't run these examples correctly.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/168455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24958/" ] }
168,486
For my customer I occasionally do work in their live database in order to fix a problem they have created for themselves, or in order to fix bad data that my product's bugs created. Much like Unix root access, it's just dangerous. What lessons should I learn ahead of time? What is the #1 thing you do to be careful about operating on live data?
Three things I've learned the hard way over the years... First, if you're doing updates or deletes on live data, first write a SELECT query with the WHERE clause you'll be using. Make sure it works. Make sure it's correct. Then prepend the UPDATE/DELETE statement to the known working WHERE clause. You never want to have DELETE FROM Customers sitting in your query analyzer waiting for you to write the WHERE clause... accidentally hit "execute" and you've just killed your Customer table. Oops. Also, depending on your platform, find out how to take a quick'n'dirty backup of a table. In SQL Server 2005, SELECT *INTO CustomerBackup200810032034FROM Customer will copy every row from the entire Customer table into a new table called CustomerBackup200810032034, which you can then delete once you've done your updates and made sure everything's OK. If the worst happens, it's a lot easier to restore missing data from this table than to try and restore last night's backup from disk or tape. Finally, be wary of cascade deletes getting rid of stuff you didn't intend to delete - check your tables' relationships and key constraints before modifying anything.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/168486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10906/" ] }
168,530
I didn't realize until recently that Perl 5.10 had significant new features and I was wondering if anyone could give me some good resources for learning about those. I searched for them on Google and all I found was some slides and a quick overview. Some of the features (to me at least) would be nice if they had more explanation. Any links would be appreciated. -fREW
There's been a string of articles in Perl Tips about Perl 5.10: Regular Expressions in Perl 5.10 Perl 5.10: Defined-or and state Switch (given and when) Perl 5.10 and Hash::Util::FieldHash Smart-match in Perl 5.10 There are also my What's new in Perl 5.10 slides on Perl Training Australia's presentations page , but since they were written before 5.10 was released, some things may have changed slightly. I believe that rjbs' Perl 5.10 for people who aren't totally insane now covers everything my slides used to. All the best, Paul Mandatory bias disclosure: I wrote almost all of the resources mentioned in this post,
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ] }
168,550
How can I display a tooltip over a button using Windows Forms ?
The ToolTip is a single WinForms control that handles displaying tool tips for multiple elements on a single form. Say your button is called MyButton. Add a ToolTip control (under CommonControls in the Windows Formstoolbox) to your form. Give it aname - say MyToolTip Set the "Tooltip on MyToolTip" property of MyButton (under Misc inthe button property grid) to the text that should appear when you hover over it. The tooltip will automatically appear when the cursor hovers over the button, but if you need to display it programmatically, call MyToolTip.Show("Tooltip text goes here", MyButton); in your code to show the tooltip, and MyToolTip.Hide(MyButton); to make it disappear again.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/168550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
168,559
tempfile.mkstemp() returns: a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order. How do I convert that OS-level handle to a file object? The documentation for os.open() states: To wrap a file descriptor in a "file object", use fdopen(). So I tried: >>> import tempfile>>> tup = tempfile.mkstemp()>>> import os>>> f = os.fdopen(tup[0])>>> f.write('foo\n')Traceback (most recent call last): File "<stdin>", line 1, in ?IOError: [Errno 9] Bad file descriptor
You can use os.write(tup[0], "foo\n") to write to the handle. If you want to open the handle for writing you need to add the "w" mode f = os.fdopen(tup[0], "w")f.write("foo")
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/168559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ] }
168,589
I can do this: $ find .../b./b/foo./c./c/foo And this: $ find . -type f -exec cat {} \;This is in b.This is in c. But not this: $ find . -type f -exec cat > out.txt {} \; Why not?
find's -exec argument runs the command you specify once for each file it finds. Try: $ find . -type f -exec cat {} \; > out.txt or: $ find . -type f | xargs cat > out.txt xargs converts its standard input into command-line arguments for the command you specify. If you're worried about embedded spaces in filenames, try: $ find . -type f -print0 | xargs -0 cat > out.txt
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/168589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22917/" ] }
168,610
I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?
Check the AUTH_USER request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user. In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and AUTH_USER will be MYDOMAIN\user.name without the users having to explicitly log in to your web app.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/168610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ] }
168,639
In Java, suppose I have a String variable S, and I want to search for it inside of another String T, like so: if (T.matches(S)) ... (note: the above line was T.contains() until a few posts pointed out that that method does not use regexes. My bad.) But now suppose S may have unsavory characters in it. For instance, let S = "[hi". The left square bracket is going to cause the regex to fail. Is there a function I can call to escape S so that this doesn't happen? In this particular case, I would like it to be transformed to "\[hi".
String.contains does not use regex, so there isn't a problem in this case. Where a regex is required, rather rejecting strings with regex special characters, use java.util.regex.Pattern.quote to escape them.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24973/" ] }
168,706
I have an third-party applet that requires JRE v1.5_12 to work correctly. THe user is installing JRE v1.6.07 or better. It used to be with 1.5 and below, that I could have multiple JRE's on the machine and specify which one to use - but with 1.6 that apepars to be broken. How do I tell the browser I want to use v1.5_12 instead of the latest one installed?
For security reasons, you can no longer force it to use older JRE's. Say release 12 has a huge security hole, and everyone installs release 13 to patch it. Evil java applets could just say "run with release 12 please" and then carry out their exploits, rendering the patches useless. Most likely you have some code with security holes that the newer JRE is blocking, because it would cause a security risk. Fix your code, should be pretty minor changes, then you wont have to worry. See this page for more info on the change.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5038/" ] }
168,724
Is there a way to produce a diagram showing existing tables and their relationships given a connection to a database? This is for SQL Server 2008 Express Edition.
Yes you can use SQL Server 2008 itself but you need to install SQL Server Management Studio Express (if not installed ) . Just right Click on Database Diagrams and create new diagram. Select the exisiting tables and if you have specified the references in your tables properly. You will be able to see the complete diagram of selected tables. For further reference see Getting started with SQL Server database diagrams
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/168724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1959/" ] }
168,736
How do you set a default value for a MySQL Datetime column? In SQL Server it's getdate() . What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.
IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5 , take a look at the other post below... Previous versions can't do that with DATETIME... But you can do it with TIMESTAMP: mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);Query OK, 0 rows affected (0.00 sec)mysql> desc test;+-------+-------------+------+-----+-------------------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-------------+------+-----+-------------------+-------+| str | varchar(32) | YES | | NULL | | | ts | timestamp | NO | | CURRENT_TIMESTAMP | | +-------+-------------+------+-----+-------------------+-------+2 rows in set (0.00 sec)mysql> insert into test (str) values ("demo");Query OK, 1 row affected (0.00 sec)mysql> select * from test;+------+---------------------+| str | ts |+------+---------------------+| demo | 2008-10-03 22:59:52 | +------+---------------------+1 row in set (0.00 sec)mysql> CAVEAT: IF you define a column with CURRENT_TIMESTAMP ON as default, you will need to ALWAYS specify a value for this column or the value will automatically reset itself to "now()" on update. This means that if you do not want the value to change, your UPDATE statement must contain "[your column name] = [your column name]" (or some other value) or the value will become "now()". Weird, but true. I am using 5.5.56-MariaDB
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/168736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ] }
168,802
Where is a good place to get started learning how to use jQuery? It seems to be all the rage nowadays. I know some basics of JavaScript but I'm by no means an expert.
Officially from jQuery http://docs.jquery.com/Tutorials Or try anything on this site that compiles a bunch of jQuery learning material: http://www.noupe.com/tutorial/51-best-of-jquery-tutorials-and-examples.html
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ] }
168,827
I'm not very experienced at using ASP.NET, but I've used built in membership providers for simple WebForms application, and I found them PITA when trying to extend the way they work (add/remove few fields and redo controls accordingly).Now I'm preparing for MVC (ASP.NET MVC or Monorail based) project, and I'm thinking - is there a better way to handle users? Have them log in/log out, keep certain parts of the site available to certain users (like logged in users, or something similar to "share this with friends" feature of many social networking sites, where you can designate users that have access to certain things.How best to acheave this in the way that will scale well? I guess, I wasn't clear on that. To rephrase my question:Would you use standard ASP.NET membership provider for a web-facing app, or something else (what)?
The Membership Provider in ASP.NET is very handy and extensible. It's simple to use the "off the shelf" features like Active Directory, SQL Server, and OpenLDAP. The main advantage is the ability to not reinvent the wheel. If your needs are more nuanced than that you can build your own provider by extending overriding the methods that the ASP.NET controls use. I am building my own Custom Membership Provider for an e-commerce website. Below are some resources for more information on Membership Providers. I asked myself the same questions when I start that project. These resources were useful to me for my decision: Writing a Custom Membership Provider - DevX How do I create a Customer Membership Provider - ASP.NET, Microsoft Implementing a Membership Provider - MSDN Examining ASP.NET 2.0's Membership, Roles, and Profile - 4GuysFromRolla Create Custom Membership Provider for ASP.NET Website Security - David Hayden Setting up a Custom Membership Provider - Channel 9 I personally don't think there is a need to use something other than the builtin stuff unless you either want to abuse yourself or your needs are impossible to satisfy by the builtin functionality.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13163/" ] }
168,838
I am trying to visualize some values on a form. They range from 0 to 200 and I would like the ones around 0 be green and turn bright red as they go to 200. Basically the function should return color based on the value inputted. Any ideas ?
Basically, the general method for smooth transition between two values is the following function: function transition(value, maximum, start_point, end_point): return start_point + (end_point - start_point)*value/maximum That given, you define a function that does the transition for triplets (RGB, HSV etc). function transition3(value, maximum, (s1, s2, s3), (e1, e2, e3)): r1= transition(value, maximum, s1, e1) r2= transition(value, maximum, s2, e2) r3= transition(value, maximum, s3, e3) return (r1, r2, r3) Assuming you have RGB colours for the s and e triplets, you can use the transition3 function as-is. However, going through the HSV colour space produces more "natural" transitions. So, given the conversion functions (stolen shamelessly from the Python colorsys module and converted to pseudocode :): function rgb_to_hsv(r, g, b): maxc= max(r, g, b) minc= min(r, g, b) v= maxc if minc == maxc then return (0, 0, v) diff= maxc - minc s= diff / maxc rc= (maxc - r) / diff gc= (maxc - g) / diff bc= (maxc - b) / diff if r == maxc then h= bc - gc else if g == maxc then h= 2.0 + rc - bc else h = 4.0 + gc - rc h = (h / 6.0) % 1.0 //comment: this calculates only the fractional part of h/6 return (h, s, v)function hsv_to_rgb(h, s, v): if s == 0.0 then return (v, v, v) i= int(floor(h*6.0)) //comment: floor() should drop the fractional part f= (h*6.0) - i p= v*(1.0 - s) q= v*(1.0 - s*f) t= v*(1.0 - s*(1.0 - f)) if i mod 6 == 0 then return v, t, p if i == 1 then return q, v, p if i == 2 then return p, v, t if i == 3 then return p, q, v if i == 4 then return t, p, v if i == 5 then return v, p, q //comment: 0 <= i <= 6, so we never come here , you can have code as following: start_triplet= rgb_to_hsv(0, 255, 0) //comment: green converted to HSVend_triplet= rgb_to_hsv(255, 0, 0) //comment: accordingly for redmaximum= 200… //comment: value is defined somewhere herergb_triplet_to_display= hsv_to_rgb(transition3(value, maximum, start_triplet, end_triplet))
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4694/" ] }
168,891
If I have a sorted list (say quicksort to sort), if I have a lot of values to add, is it better to suspend sorting, and add them to the end, then sort, or use binary chop to place the items correctly while adding them. Does it make a difference if the items are random, or already more or less in order?
If you add enough items that you're effectively building the list from scratch, you should be able to get better performance by sorting the list afterwards. If items are mostly in order, you can tweak both incremental update and regular sorting to take advantage of that, but frankly, it usually isn't worth the trouble. (You also need to be careful of things like making sure some unexpected ordering can't make your algorithm take much longer , q.v. naive quicksort) Both incremental update and regular list sort are O(N log N) but you can get a better constant factor sorting everything afterward (I'm assuming here that you've got some auxiliary datastructure so your incremental update can access list items faster than O(N)...). Generally speaking, sorting all at once has a lot more design freedom than maintaining the ordering incrementally, since incremental update has to maintain a complete order at all times, but an all-at-once bulk sort does not. If nothing else, remember that there are lots of highly-optimized bulk sorts available.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/168891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ] }
168,901
private IEnumerable<string> Tables{ get { yield return "Foo"; yield return "Bar"; }} Let's say I want iterate on those and write something like processing #n of #m. Is there a way I can find out the value of m without iterating before my main iteration? I hope I made myself clear.
IEnumerable doesn't support this. This is by design. IEnumerable uses lazy evaluation to get the elements you ask for just before you need them. If you want to know the number of items without iterating over them you can use ICollection<T> , it has a Count property.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/168901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23893/" ] }
168,931
When you guys are unit testing an application that relies on values from an app.config file? How do you test that those values are read in correctly and how your program reacts to incorrect values entered into a config file? It would be ridiculous to have to modify the config file for the NUnit app, but I can't read in the values from the app.config I want to test. Edit: I think I should clarify perhaps. I'm not worried about the ConfigurationManager failing to read the values, but I am concerned with testing how my program reacts to the values read in.
I usually isolate external dependencies like reading a config file in their own facade-class with very little functionality. In tests I can create a mock version of this class that implements and use that instead of the real config file. You can create your own mockup's or use a framework like moq or rhino mocks for this. That way you can easily try out your code with different configuration values without writing complex tests that first write xml-configuration files. The code that reads the configuration is usually so simple that it needs very little testing.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/168931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ] }
168,946
Here's my scenario. I created an application which uses Integrated Windows Authentication in order to work. In Application_AuthenticateRequest() , I use HttpContext.Current.User.Identity to get the current WindowsPrincipal of the user of my website. Now here's the funny part. Some of our users have recently gotten married, and their names change. (i.e. the user's NT Login changes from jsmith to jjones ) and when my application authenticates them, IIS passes me their OLD LOGIN . I continue to see jsmith passed to my application until I reboot my SERVER! Logging off the client does not work. Restarting the app pool does not work. Only a full reboot. Does anyone know what's going on here? Is there some sort of command I can use to flush whatever cache is giving me this problem? Is my server misconfigured? Note: I definitely do NOT want to restart IIS, my application pools, or the machine. As this is a production box, these are not really viable options. AviD - Yes, their UPN was changed along with their login name. And Mark/Nick... This is a production enterprise server... It can't just be rebooted or have IIS restarted. Follow up (for posterity): Grhm's answer was spot-on. This problem pops up in low-volume servers where you don't have a lot of people using your applications, but enough requests are made to keep the users' identity in the cache. The key part of the KB which seems to describe why the cache item is not refreshed after the default of 10 minutes is: The cache entries do time out, however chances are that recurring queries by applications keep the existing cache entry alive for the maximum lifetime of the cache entry. I'm not exactly sure what in our code was causing this (the recurring queries), but the resolution which worked for us was to cut the LsaLookupCacheExpireTime value from the seemingly obscene default of 1 week to just a few hours. This, for us, cut the probability that a user would be impacted in the real world to essentially zero, and yet at the same time doesn't cause an extreme number of SID-Name lookups against our directory servers. An even better solution IMO would be if applications looked up user information by SID instead of mapping user data to textual login name. (Take note, vendors! If you're relying on AD authentication in your application, you'll want to put the SID in your authentication database!)
I've had similar issues lately and as stated in Robert MacLean's answer , AviD's group policy changes don't work if you're not logging in as the users. I found changing the LSA Lookup Cache size as described is MS KB946358 worked without rebooting or recycling any apppool or services. I found this as an answer to this similar question: Wrong authentication after changing user's logon name . You might want to look into the following system calls such as the following ones: LookupAccountName()LookupAccountSid()LsaOpenPolicy() You could use them to write a C++/CLI (/Managed-C++) app to interrogate the LSA cache.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/168946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24995/" ] }
168,956
I need a (php) regex to match Yahoo's username rules: Use 4 to 32 characters and start with a letter. You may use letters, numbers, underscores, and one dot (.).
/^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/ Or a little shorter: /^[a-z](?=[\w.]{3,31}$)\w*\.?\w*$/i
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/168956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24999/" ] }
168,963
I have the following code making a GET request on a URL: $('#searchButton').click(function() { $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()); }); But the returned result is not always reflected. For example, I made a change in the response that spit out a stack trace but the stack trace did not appear when I clicked on the search button. I looked at the underlying PHP code that controls the ajax response and it had the correct code and visiting the page directly showed the correct result but the output returned by .load was old. If I close the browser and reopen it it works once and then starts to return the stale information. Can I control this by jQuery or do I need to have my PHP script output headers to control caching?
You have to use a more complex function like $.ajax() if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script: $.ajaxSetup ({ // Disable caching of AJAX responses cache: false});
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/168963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ] }
169,008
I'm trying to write a regex that will parse out the directory and filename of a fully qualified path using matching groups. so... /var/log/xyz/10032008.log would recognize group 1 to be "/var/log/xyz" and group 2 to be "10032008.log" Seems simple but I can't get the matching groups to work for the life of me. NOTE: As pointed out by some of the respondents this is probably not a good use of regular expressions. Generally I'd prefer to use the file API of the language I was using. What I'm actually trying to do is a little more complicated than this but would have been much more difficult to explain, so I chose a domain that everyone would be familiar with in order to most succinctly describe the root problem.
Try this: ^(.+)\/([^\/]+)$ EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/169008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ] }
169,070
How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir() , the cwd will not be changed after the function is called.
The answer for a decorator has been given; it works at the function definition stage as requested. With Python 2.5+, you also have an option to do that at the function call stage using a context manager: from __future__ import with_statement # needed for 2.5 ≤ Python < 2.6import contextlib, [email protected] remember_cwd(): curdir= os.getcwd() try: yield finally: os.chdir(curdir) which can be used if needed at the function call time as: print "getcwd before:", os.getcwd()with remember_cwd(): walk_around_the_filesystem()print "getcwd after:", os.getcwd() It's a nice option to have. EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ] }
169,071
How would you, as a developer with little (or no) artistic inclination, design a GUI for an application? In particular, I'm thinking about desktop apps but anything that relates to Web apps is welcome as well.I find it extremely hard to design something that both I and potential users find pleasing. I can look up color schemes on the net, but how would I know where to place buttons/textboxes/etc.? Update: To clarify, I don't mean what controls and such to use. Rather, are there any guidelines/hints to when I should buttons, combos, textboxes and so on? How long should they be and where would I place them on the form?
The first thing you need to do is get out of your developer-point-of-view. We tend to think in terms of forms, controls, buttons, lists, grids etc. And this tends to push us to solutions that are not always optimal for the user. Users don't want to use our software. (except when you're programming games) They just want to get stuff done. So when desinging UI and user interactions it makes sense to start from there. Write down what a user wants to do with your software. Think about how a user would go about doing these things and what your application could do to make things easier. Try to work with different tools than you use for programming. These make you think in UI widgets again. Start with a pencil and a piece of paper to sketch things, also try to think about the behaviour as well as the layout etc. If you've got a clear picture of what you want to build you can start thinking about how you're going to build it. That's when the widgets, buttons and pages come in.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23202/" ] }
169,107
I'm in a situation where I would to generate a script for a database that I could run on another server and get a database identical to the original one, but without any of the data. In essence, I want to end up with a big create script that captures the database schema. I am working in an environment that has SQL Server 2000 installed, and I am unable to install the 2005 client tools (in the event that they would help). I can't afford RedGate, but I really would like to have a database with identical schema on another server. Any suggestions? Any simple .exe (no installation required) tools, tips, or T-SQL tricks would be much appreciated. Update: The database I'm working with has 200+ tables and several foreign-key relationships and constraints, so manually scripting each table and pasting together the script is not a viable option. I'm looking for something better than this manual solution Additional Update Unless I'm completely missing something, this is not a viable solution using the SQL 2000 tools. When I select the option to generate a create script on a database. I end up with a script that contains a CREATE DATABASE command, and creates none of the objects - the tables, the constraints, etc. SQL 2005's Management studio may handle the objects as well, but the database is in an environment where there is no way for me to connect an installation of Management Studio to it.
Run SQL Server Management Studio, right click on the database and select Script Database as > Create to > file That's for SQL Server 2005. SQL Server 2000 Enterprise Manager has a similar command. Just right-click on the database > All Tasks > Generate Scripts . EDIT: In SQL Server 2005, you can select "Database" in the object explorer pane and select several databases in the details pane. Then, right-click on your selection and "Script Database as > Create to > file". This will cause it to put them all into one script and it will include all tables, keys, stored procedures, and constraints.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19452/" ] }
169,121
When I try to bind port 80 to a socket in c, i always get the error, that I don't have permission to use this port. is there an easy way to get this permission?
Usually only the superuser (root) can bind to 'privileged' ports (i.e. those port numbers below 1024). This means that you either have to run your program as root or make your executable 'suid root'. Both of these have security consequences so you may want to consider using the suid approach and relinquishing superuser privileges once the bind call has been made.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25017/" ] }
169,164
I have a fairly large codebase that depends on MooTools v1.11 and am about to convert to version 1.2. Since this is a pretty major overhaul, I've toyed with the idea of converting to jQuery. Anyone have advice on whether to update to jQuery or just stick with MooTools? I mostly use MooTools for Ajax, drag and drop, and some minor effects.
If it's not broken. Don't fix it. jQuery might have X or Y but if everything is dependent on MooTools, you might have a lot of work ahead of you to convert from MooTools. Keep MooTools if you used it extensively through out your site. However, if you only have 2-3 pages with minor effects... the change might be worth it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4133/" ] }
169,201
In ActionScript 3.0, is there an automatic way to calculate the number of days, hours, minutes and seconds between two specified dates? Basicly, what I need is the ActionScript equivalent of the .NET Timespan class. Any idea?
I created an ActionScript TimeSpan class with a similar API to System.TimeSpan to fill that void, but there are differences due to the lack of operator overloading. You can use it like so: TimeSpan.fromDates(later, earlier).totalDays; Below is the code for the class (sorry for the big post - I won't include the Unit Tests ;) /** * Represents an interval of time */ public class TimeSpan{ private var _totalMilliseconds : Number; public function TimeSpan(milliseconds : Number) { _totalMilliseconds = Math.floor(milliseconds); } /** * Gets the number of whole days * * @example In a TimeSpan created from TimeSpan.fromHours(25), * totalHours will be 1.04, but hours will be 1 * @return A number representing the number of whole days in the TimeSpan */ public function get days() : int { return int(_totalMilliseconds / MILLISECONDS_IN_DAY); } /** * Gets the number of whole hours (excluding entire days) * * @example In a TimeSpan created from TimeSpan.fromMinutes(1500), * totalHours will be 25, but hours will be 1 * @return A number representing the number of whole hours in the TimeSpan */ public function get hours() : int { return int(_totalMilliseconds / MILLISECONDS_IN_HOUR) % 24; } /** * Gets the number of whole minutes (excluding entire hours) * * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), * totalSeconds will be 65.5, but seconds will be 5 * @return A number representing the number of whole minutes in the TimeSpan */ public function get minutes() : int { return int(_totalMilliseconds / MILLISECONDS_IN_MINUTE) % 60; } /** * Gets the number of whole seconds (excluding entire minutes) * * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), * totalSeconds will be 65.5, but seconds will be 5 * @return A number representing the number of whole seconds in the TimeSpan */ public function get seconds() : int { return int(_totalMilliseconds / MILLISECONDS_IN_SECOND) % 60; } /** * Gets the number of whole milliseconds (excluding entire seconds) * * @example In a TimeSpan created from TimeSpan.fromMilliseconds(2123), * totalMilliseconds will be 2001, but milliseconds will be 123 * @return A number representing the number of whole milliseconds in the TimeSpan */ public function get milliseconds() : int { return int(_totalMilliseconds) % 1000; } /** * Gets the total number of days. * * @example In a TimeSpan created from TimeSpan.fromHours(25), * totalHours will be 1.04, but hours will be 1 * @return A number representing the total number of days in the TimeSpan */ public function get totalDays() : Number { return _totalMilliseconds / MILLISECONDS_IN_DAY; } /** * Gets the total number of hours. * * @example In a TimeSpan created from TimeSpan.fromMinutes(1500), * totalHours will be 25, but hours will be 1 * @return A number representing the total number of hours in the TimeSpan */ public function get totalHours() : Number { return _totalMilliseconds / MILLISECONDS_IN_HOUR; } /** * Gets the total number of minutes. * * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), * totalSeconds will be 65.5, but seconds will be 5 * @return A number representing the total number of minutes in the TimeSpan */ public function get totalMinutes() : Number { return _totalMilliseconds / MILLISECONDS_IN_MINUTE; } /** * Gets the total number of seconds. * * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), * totalSeconds will be 65.5, but seconds will be 5 * @return A number representing the total number of seconds in the TimeSpan */ public function get totalSeconds() : Number { return _totalMilliseconds / MILLISECONDS_IN_SECOND; } /** * Gets the total number of milliseconds. * * @example In a TimeSpan created from TimeSpan.fromMilliseconds(2123), * totalMilliseconds will be 2001, but milliseconds will be 123 * @return A number representing the total number of milliseconds in the TimeSpan */ public function get totalMilliseconds() : Number { return _totalMilliseconds; } /** * Adds the timespan represented by this instance to the date provided and returns a new date object. * @param date The date to add the timespan to * @return A new Date with the offseted time */ public function add(date : Date) : Date { var ret : Date = new Date(date.time); ret.milliseconds += totalMilliseconds; return ret; } /** * Creates a TimeSpan from the different between two dates * * Note that start can be after end, but it will result in negative values. * * @param start The start date of the timespan * @param end The end date of the timespan * @return A TimeSpan that represents the difference between the dates * */ public static function fromDates(start : Date, end : Date) : TimeSpan { return new TimeSpan(end.time - start.time); } /** * Creates a TimeSpan from the specified number of milliseconds * @param milliseconds The number of milliseconds in the timespan * @return A TimeSpan that represents the specified value */ public static function fromMilliseconds(milliseconds : Number) : TimeSpan { return new TimeSpan(milliseconds); } /** * Creates a TimeSpan from the specified number of seconds * @param seconds The number of seconds in the timespan * @return A TimeSpan that represents the specified value */ public static function fromSeconds(seconds : Number) : TimeSpan { return new TimeSpan(seconds * MILLISECONDS_IN_SECOND); } /** * Creates a TimeSpan from the specified number of minutes * @param minutes The number of minutes in the timespan * @return A TimeSpan that represents the specified value */ public static function fromMinutes(minutes : Number) : TimeSpan { return new TimeSpan(minutes * MILLISECONDS_IN_MINUTE); } /** * Creates a TimeSpan from the specified number of hours * @param hours The number of hours in the timespan * @return A TimeSpan that represents the specified value */ public static function fromHours(hours : Number) : TimeSpan { return new TimeSpan(hours * MILLISECONDS_IN_HOUR); } /** * Creates a TimeSpan from the specified number of days * @param days The number of days in the timespan * @return A TimeSpan that represents the specified value */ public static function fromDays(days : Number) : TimeSpan { return new TimeSpan(days * MILLISECONDS_IN_DAY); } /** * The number of milliseconds in one day */ public static const MILLISECONDS_IN_DAY : Number = 86400000; /** * The number of milliseconds in one hour */ public static const MILLISECONDS_IN_HOUR : Number = 3600000; /** * The number of milliseconds in one minute */ public static const MILLISECONDS_IN_MINUTE : Number = 60000; /** * The number of milliseconds in one second */ public static const MILLISECONDS_IN_SECOND : Number = 1000;}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ] }
169,217
In SQL Server you can use the IsNull() function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#. For example, I want to do something like: myNewValue = IsNull(myValue, new MyValue()); instead of: if (myValue == null) myValue = new MyValue();myNewValue = myValue; Thanks.
It's called the null coalescing ( ?? ) operator: myNewValue = myValue ?? new MyValue();
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/169217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ] }
169,220
I'm used to writing classes like this: public class foo { private string mBar = "bar"; public string Bar { get { return mBar; } set { mBar = value; } } //... other methods, no constructor ...} Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there? public class foo2theRevengeOfFoo { //private string mBar = "bar"; public string Bar { get; set; } //... other methods, no constructor ... //behavior has changed.} You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties. Something like this would make more sense to me: public string Bar { get; set; } = "bar";
Update - the answer below was written before C# 6 came along. In C# 6 you can write: public class Foo{ public string Bar { get; set; } = "bar";} You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value): public class Foo{ public string Bar { get; } public Foo(string bar) { Bar = bar; }} It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.) Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field. This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/169220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ] }
169,276
After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of "make work" for the programmer. It's work to PUT the dang things into the code, and then they make searching and reading code very annoying. What are the benefits? Why do coders go to the extra trouble to put this in their code. Make me a believer!
A similar question has already been asked. but... I would say not anymore . It was originally intended to hide generated code from WinForms in early versions of .NET. With partial classes the need seems to go away. IMHO it gets way overused now as an organizational construct and has no compiler value whatsoever. It's all for the IDE.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ] }
169,277
Is there a Generics Friendly way of using Collection.EMPTY_LIST in my Java Program. I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this. Something like users = Collections<User>.EMPTY_LIST;
By doing the following: List<User> users = Collections.emptyList(); The type of the returned list from Collections.emptyList(); will be inferred as a String due to the left-hand-side of the assignment. However, if you prefer to not have this inference, you can define it explicitly by doing the following: List<User> users = Collections.<User>emptyList(); In this particular instance, this may appear as redundant to most people (in fact, I've seen very little code out in the wild that makes use of explicit type arguments), however for a method with the signature: void doStuff(List<String> users) it would be perfectly clean for one to invoke doStuff() with an explicit type argument as follows: doStuff(Collections.<String>emptyList());
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
169,303
I want to be able to run unstrusted ruby code. I want to be able to pass variables to said untrusted code that it may use. I also want said code to return a result to me. Here is a conceptual example of what I am thinking input = "sweet"output = nilThread.start { $SAFE = 4 #... untrusted code goes here, it uses the input variable(s) #to calculate some result that it places in the output variable}#parse the output variable as a string. Just to clarify, I am basically using the untrusted code as a function. I want to provide its some inputs, and then allow it to write to the output. That is all I really want, I don't care how it is done, I just want the ability to use untrusted Ruby code as a sort of function. The solution does not have to look anything like the code I wrote above, I am just using it to illustrate what I want. Now, I can currently think of 3 ways to do this: Use the $SAFE level construct above. whytheluckystiff has a Sandbox plugin for ruby I could run each function in its own virtual machine, using some sort of os virtualization software like vmware or Xen or something. I am wondering if anyone has any recommendations for running untrusted ruby code in a functional way? What option would you recomend? How would you go about it? Thanks.
$SAFE is not enough; you need to be at least at the level of Why's freaky sandbox. However, I don't know if that sandbox code is actively maintained or if he/they ever solved the holes such as infinite loops, etc. Unsafe generally means hostile. If you can relax from hostile to, say, 'naive', and depending upon the requirements of your app, you might get away with sandboxing in Ruby. It's not really a first-class scenario in the language design. Even with that, though, you probably don't need to go to the machine level of separation. I'd feel pretty safe using a sandbox in a separately spawned process, with your app functioning as a process manager to kill off any that manage to hang/flame. Now, that is a few orders of magnitude more work than your simple block above. But remember and keep repeating, "SAFE can't deal with hostile".
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21317/" ] }
169,330
Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it our using SQL Server Management Studio, without having to install the GUI. I've seen some references to do thing via the PowerShell but in the end a C# console app is what I really want. To clarify.... I'd like to script out the stored procedures. The list via the Select * from sys.procedures is helpful, but in the end I need to script out each of these.
You can use SMO for that. First of all, add references to these assemblies to your project: Microsoft.SqlServer.ConnectionInfo Microsoft.SqlServer.Smo Microsoft.SqlServer.SmoEnum They are located in the GAC (browse to C:\WINDOWS\assembly folder). Use the following code as an example of scripting stored procedures: using System;using System.Collections.Generic;using System.Data;using Microsoft.SqlServer.Management.Smo;class Program{ static void Main(string[] args) { Server server = new Server(@".\SQLEXPRESS"); Database db = server.Databases["Northwind"]; List<SqlSmoObject> list = new List<SqlSmoObject>(); DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.StoredProcedure); foreach (DataRow row in dataTable.Rows) { string sSchema = (string)row["Schema"]; if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA") continue; StoredProcedure sp = (StoredProcedure)server.GetSmoObject( new Urn((string)row["Urn"])); if (!sp.IsSystemObject) list.Add(sp); } Scripter scripter = new Scripter(); scripter.Server = server; scripter.Options.IncludeHeaders = true; scripter.Options.SchemaQualify = true; scripter.Options.ToFileOnly = true; scripter.Options.FileName = @"C:\StoredProcedures.sql"; scripter.Script(list.ToArray()); }} See also: SQL Server: SMO Scripting Basics .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5678/" ] }
169,332
I want to use a timer in my simple .NET application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application. Is there a C# timer (or timer like) class for use in console applications?
System.Timers.Timer And as MagicKat says: System.Threading.Timer You can see the differences here: http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/ And you can see MSDN examples here: http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx And here: http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ] }
169,342
I have a solution that contains two projects. One project is an ASP.NET Web Application Project, and one is a class library. The web application has a project reference to the class library. Neither of these is strongly-named. In the class library, which I'll call "Framework," I have an endpoint behavior (an IEndpointBehavior implementation) and a configuration element (a class derived from BehaviorExtensionsElement). The configuration element is so I can attach the endpoint behavior to a service via configuration. In the web application, I have an AJAX-enabled WCF service. In web.config, I have the AJAX service configured to use my custom behavior. The system.serviceModel section of the configuration is pretty standard and looks like this: <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="MyEndpointBehavior"> <enableWebScript /> <customEndpointBehavior /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> <services> <service name="WebSite.AjaxService"> <endpoint address="" behaviorConfiguration="MyEndpointBehavior" binding="webHttpBinding" contract="WebSite.AjaxService" /> </service> </services> <extensions> <behaviorExtensions> <add name="customEndpointBehavior" type="Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> </behaviorExtensions> </extensions></system.serviceModel> At runtime, this works perfectly. The AJAX enabled WCF service correctly uses my custom configured endpoint behavior. The problem is when I try to add a new AJAX WCF service. If I do Add -> New Item... and select "AJAX-enabled WCF Service," I can watch it add the .svc file and codebehind, but when it gets to updating the web.config file, I get this error: The configuration file is not a valid configuration file for WCF Service Library. The type 'Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' registered for extension 'customEndpointBehavior' could not be loaded. Obviously the configuration is entirely valid since it works perfectly at runtime. If I remove the element from my behavior configuration temporarily and then add the AJAX-enabled WCF Service, everything goes without a hitch. Unfortunately, in a larger project where we will have multiple services with various configurations, removing all of the custom behaviors temporarily is going to be error prone. While I realize I could go without using the wizard and do everything manually, not everyone can, and it'd be nice to be able to just use the product as it was meant to be used - wizards and all. Why isn't my custom WCF behavior extension element type being found? Updates/clarifications: It does work at runtime, just not design time. The Framework assembly is in the web project's bin folder when I attempt to add the service. While I could add services manually ("without configuration"), I need the out-of-the-box item template to work - that's the whole goal of the question. This issue is being seen in Visual Studio 2008. In VS 2010 this appears to be resolved. I filed this issue on Microsoft Connect and it turns out you either have to put your custom configuration element in the GAC or put it in the IDE folder. They won't be fixing it, at least for now. I've posted the workaround they provided as the "answer" to this question.
Per the workaround that Microsoft posted on the Connect issue I filed for this, it's a known issue and there won't be any solution for it, at least in the current release: The reason for failing to add a new service item: When adding a new item and updating the configuration file, the system will try to load configuration file, so it will try to search and load the assembly of the cusom extension in this config file. Only in the cases that the assembly is GACed or is located in the same path as vs exe (Program Files\Microsoft Visual Studio 9.0\Common7\IDE), the system can find it. Otherwise, the error dialog will pop up and "add a new item" will fail. I understand your pain points. Unfortunately we cannot take this change in current release. We will investigate it in later releases and try to provide a better solution then,such as providing a browse dialog to enable customers to specify the path, or better error message to indicate some work around solution, etc... Can you try the work around in current stage: GAC your custom extension assembly or copy it to "Program Files\Microsoft Visual Studio 9.0\Common7\IDE"? We will provide the readme to help other customers who may run into the same issue. Unfortunately, it appears I'm out of luck on this one.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8116/" ] }
169,362
I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python?
You can use the zipfile module to compress the file using the zip standard, the email module to create the email with the attachment, and the smtplib module to send it - all using only the standard library. Python - Batteries Included If you don't feel like programming and would rather ask a question on stackoverflow.org instead, or (as suggested in the comments) left off the homework tag, well, here it is: import smtplibimport zipfileimport tempfilefrom email import encodersfrom email.message import Messagefrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='[email protected]'): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') zip.write(the_file) zip.close() zf.seek(0) # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close() """ # alternative to the above 4 lines if you're using gmail server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login("username", "password") server.sendmail(sender,recipients,themsg) server.quit() """ With this function, you can just do: send_file_zipped('result.txt', ['[email protected]']) You're welcome.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
169,378
ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?
Static methods versus Instance methods Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see this answer for some more details on that). Rule CA1822 in FxCop or Code Analysis states: "After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check atruntime for each call that ensures the current object pointer isnon-null. This can result in a measurable performance gain forperformance-sensitive code. In some cases, the failure to access thecurrent object instance represents a correctness issue." Utility Class You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees) method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/169378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ] }
169,428
this code always returns 0 in PHP 5.2.5 for microseconds: <?php$dt = new DateTime();echo $dt->format("Y-m-d\TH:i:s.u") . "\n";?> Output: [root@www1 ~]$ php date_test.php2008-10-03T20:31:26.000000[root@www1 ~]$ php date_test.php2008-10-03T20:31:27.000000[root@www1 ~]$ php date_test.php2008-10-03T20:31:27.000000[root@www1 ~]$ php date_test.php2008-10-03T20:31:28.000000 Any ideas?
This seems to work, although it seems illogical that http://us.php.net/date documents the microsecond specifier yet doesn't really support it: function getTimestamp(){ return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25039/" ] }
169,453
We're running a web app on Tomcat 6 and Apache mod_proxy 2.2.3. Seeing a lot of 502 errors like this: Bad Gateway! The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET /the/page.do. Reason: Error reading from remote server If you think this is a server error, please contact the webmaster. Error 502 Tomcat has plenty of threads, so it's not thread-constrained. We're pushing 2400 users via JMeter against the app. All the boxes are sitting inside our firewall on a fast unloaded network, so there shouldn't be any network problems. Anyone have any suggestions for things to look at or try? We're heading to tcpdump next. UPDATE 10/21/08: Still haven't figured this out. Seeing only a very small number of these under load. The answers below haven't provided any magical answers...yet. :)
Just to add some specific settings, I had a similar setup (with Apache 2.0.63 reverse proxying onto Tomcat 5.0.27). For certain URLs the Tomcat server could take perhaps 20 minutes to return a page. I ended up modifying the following settings in the Apache configuration file to prevent it from timing out with its proxy operation (with a large over-spill factor in case Tomcat took longer to return a page): Timeout 5400ProxyTimeout 5400 Some backgound ProxyTimeout alone wasn't enough. Looking at the documentation for Timeout I'm guessing (I'm not sure) that this is because while Apache is waiting for a response from Tomcat, there is no traffic flowing between Apache and the Browser (or whatever http client) - and so Apache closes down the connection to the browser. I found that if I left the Timeout setting at its default (300 seconds), then if the proxied request to Tomcat took longer than 300 seconds to get a response the browser would display a "502 Proxy Error" page. I believe this message is generated by Apache, in the knowledge that it's acting as a reverse proxy, before it closes down the connection to the browser (this is my current understanding - it may be flawed). The proxy error page says: Proxy Error The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET. Reason: Error reading from remote server ...which suggests that it's the ProxyTimeout setting that's too short, while investigation shows that Apache's Timeout setting (timeout between Apache and the client) that also influences this.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671/" ] }
169,506
I have a form with many input fields. When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?
$('#myForm').submit(function() { // get all the inputs into an array. var $inputs = $('#myForm :input'); // not sure if you wanted this, but I thought I'd add it. // get an associative array of just the values. var values = {}; $inputs.each(function() { values[this.name] = $(this).val(); });}); Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray : var values = {};$.each($('#myForm').serializeArray(), function(i, field) { values[field.name] = field.value;}); Note that this snippet will fail on <select multiple> elements. It appears that the new HTML 5 form inputs don't work with serializeArray in jQuery version 1.3. This works in version 1.4+
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/169506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ] }
169,511
How do I iterate over a range of numbers in Bash when the range is given by a variable? I know I can do this (called "sequence expression" in the Bash documentation ): for i in {1..5}; do echo $i; done Which gives: 1 2 3 4 5 Yet, how can I replace either of the range endpoints with a variable? This doesn't work: END=5for i in {1..$END}; do echo $i; done Which prints: {1..5}
for i in $(seq 1 $END); do echo $i; done edit: I prefer seq over the other methods because I can actually remember it ;)
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/169511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24923/" ] }
169,574
Like most *nix people, I tend to play with my tools and get them configured just the way that I like them. This was all well and good until recently. As I do more and more work, I tend to log onto more and more machines, and have more and more stuff that's configured great on my home machine, but not necessarily on my work machine, or my web server, or any of my work servers... How do you keep these config files updated? Do you just manually copy them over? Do you have them stored somewhere public?
I've had pretty good luck keeping my files under a revision control system. It's not for everyone, but most programmers should be able to appreciate the benefits. Read Keeping Your Life in Subversion for an excellent description, including how to handle non-dotfile configuration (like cron jobs via the svnfix script ) on multiple machines.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24817/" ] }
169,590
I need to fire an event when the mouse is above a PictureBox with the mouse button already clicked and held down. Problems: The MouseDown and MouseEnter event handlers do not work together very well. For instance once a mouse button is clicked and held down, C# will fire the MouseDown event handler, but when the cursor moves over the PictureBox the MouseEnter event does not fire, until the mouse button is realeased.
When the mouse is pressed down most controls will then Control.Capture the mouse input. This means that all MouseMove events are sent to the original control that captured rather than the control the mouse happens to be over. This continues until the mouse loses capture which typically happens on the mouse up. If you really need to know when the mouse is over your control even when another control has captured mouse input then you only really have one way. You need to snoop the windows messages destined for other controls inside your application. To do that you need add a message filter ... Application.AddMessageFilter(myFilterClassInstance); Then you need to implement the IMessageFilter on a suitable class... public class MyFilterClass : IMessageFilter{ public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_MOUSEMOVE) // Check if mouse is over my picture box! return false; }} Then you watch for mouse move events and check if they are over your picture box and do whatever it is you want to do.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609/" ] }
169,620
I'm familiar with the LAMP stack and over the years have successfully deployed a handful of web sties based on it. I've used everything from Apache + modPerl, to PHP, to Ruby and Rails. With good use of caching my Rails site can sustain a pretty good load, but I'm not talking massive. I never really liked Java as a language, or XML for that matter, and have very much been ignoring the whole Java EE side of things. For those who have had real and direct experience in both worlds: is there something super cool about Java EE that I'm missing, or is just a bunch of hot air? What justifies the high price of the proprietary app servers? I'm not trolling here: I'm looking for concrete examples of things that Java EE really nails that are missing from modern LAMP frameworks, if such differences exist. (Modern = Rails, Django, etc). Alternatively pipe in with those things that LAMP really does better (fewer XML sit ups for one). +++++ Update October 16, 2008 I'm sad to report that most of the replies here are not helpful, and simply fall into one of two categories: "It scales because here are three examples of large web sites" and "It scales because it is really actually much better than the LAMP stack". I've done quite a bit of reading, and have concluded that Java EE only has one really good trick: transactions (thanks Will) and as for the rest you can succeed or fail on your own merit, there is nothing intrinsically in the environment to cause you to create a scalable and reliable web site, indeed Java EE has quite a few traps that make it easy to fail (for instance it is easy to start using session beans without realizing that you are paying now for quite a bit of JMS traffic that perhaps could have been avoided with a different design.) Useful discussion http://www.subbu.org/blog/2007/10/large-scale-web-site-development http://highscalability.com/ http://www.oreillynet.com/onlamp/blog/2004/07/php_scales.html http://www.schlossnagle.org/~george/blog/index.php?/archives/29-Why-PHP-Scales-A-Cranky,-Snarky-Answer.html http://blogs.law.harvard.edu/philg/2003/09/20/
The key differentiator that Java EE offers over the LAMP stack can be boiled down to a single word. Transactions. Most smaller systems simply rely on the transaction system supplied by the database, and for many applications that is (obviously) quite satisfactory. But each Java EE server includes a distributed transaction manager. This lets you do more complicated things, across diverse systems, safely and reliably. The most simple example of this is the simple scenario of taking a record from a database, putting it on a messaging queue (JMS), and then deleting that row from the database. This simple case involves two separate systems, and can not reliably be done out side of a transaction. For example, you can put the row on to the message queue, but (due to a system failure) not remove the row from the database. You can see how having a transaction with the JMS provider and a separate transaction with the database doesn't really solve the problem, as the transactions are not linked together. Obviously this simple scenario can be worked around, a dealt with, etc. The nice thing with Java EE, though, is that you don't have to deal with these kind of issues -- the container gets to deal with them. And, again, not every problem requires this level o transaction handling. But for those that do, it's invaluable. And once you get used to using them, you'll find the transaction management of a Java EE server to be a great asset.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10157/" ] }
169,625
I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.
(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))? That's a (slightly modified) version of the official URI parsing regexp from RFC 2396 . It allows for #fragments and ?querystrings to appear after the filename, which may or may not be what you want. It also matches any valid domain, including localhost , which again might not be what you want, but it could be modified. A more traditional regexp for this might look like the below. ^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$ |-------- domain -----------|--- path ---|-- extension ---| EDIT See my other comment , which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for karma-whoring completeness reasons.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
169,637
When I retrieve a record using LINQ that has a DateTime field only the ToString() is available. Where are all the other DateTime methods? I have to Convert.ToDateTime the DateTime? that the Field returns? What is the difference between (DateTime) and (DateTime?)
If by DateTime? you mean a Nullable<DateTime> , then you can get the DateTime value via the DateTime?. Value property.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ] }
169,713
What made it hard to find? How did you track it down? Not close enough to close but see also https://stackoverflow.com/questions/175854/what-is-the-funniest-bug-youve-ever-experienced
A jpeg parser, running on a surveillance camera, which crashed every time the company's CEO came into the room. 100% reproducible error. I kid you not! This is why: For you who doesn't know much about JPEG compression - the image is kind of broken down into a matrix of small blocks which then are encoded using magic etc. The parser choked when the CEO came into the room, because he always had a shirt with a square pattern on it, which triggered some special case of contrast and block boundary algorithms. Truly classic.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/169713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10960/" ] }
169,721
I keep hearing that Flex is open source and I figured that a great way to learn about the inner workings would be to look at it. I can easily find the Flex SDK ( http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code ), but I'm wanting to look at the class definitions for the MXML core library (like NumericStepper). Have I misunderstood, or is this kind of thing available somewhere? Note, I'm looking for the source of some core MXML components so I can see how they work internally, not for the compiler's source. Does what I've linked above have what I'm looking for and I just can't find it in the director structure?
If you have installed the sdk or Flex builder all of the source files are installed locally on your computer, I believe. I have flex builder 3 installed source is located here(depending on where you installed): Source for flex 3 sdk C:\Program Files\Adobe\Flex Builder 3\sdks\3.0.0\frameworks\projects\framework\src\mx Source for flex 2 sdk C:\Program Files\Adobe\Flex Builder 3\sdks\2.0.1\frameworks\source\mx Hope this helps and alleviates the need to be online to view the source...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9619/" ] }
169,731
In Javascript, I have an object: obj = { one: "foo", two: "bar" }; Now, I want do do this var a = 'two';if(confirm('Do you want One')){ a = 'one';}alert(obj.a); But of course it doesn't work. What would be the correct way of referencing this object dynamically?
short answer: obj[a] long answer: obj.field is just a shorthand for obj["field"] , for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ] }
169,765
Suppose you're working on an enterprise project in which you have to get management signoff in order for you to develop a new feature set. Usually your management has no problem signing off on some bright shiny new UI feature. Unfortunately they have a hard time appreciating some behind-the-scenes issues that are crucial to the application's well-being such as transactions, data integrity, workflow routing, configurability, security, etc. Since they're non-technical and these issues are not immediately visible, it's not obvious to them that this is crucial. How have you convinced them that these infrastructural issues have to be dealt with and that it is important to their business process?
Every craft has its unsexy sides. Things that HAVE to be done, but nobody notices them directly. In a grocery store somebody has to organize how and when to fill the grocery shelves so they always look fresh. In a laundry you need somebody who thinks about how the processes should be optimized so that the customer gets his clothes in time. The tricky part is: The customer won't notice when these subtle things have been done right UNTIL HE NOTICES THEY ARE MISSING! Like when the laundry is not ready on time but two days late, or the veggies in the super market have brown spots and look terrible. Same goes for IT. You don't notice good transactions until your major customer knocks on your door and tells you that an important and expensive project has failed because the database entries of your product were mysteriously mixed up. You don't notice good security until customer credit card information shows up in Elbonia (and soon after word is in the national newspapers warning customers of your company). The thing you really have to hammer in again and again and again is that software is NOT static. It has to be cared for even after its initial development phase is over. It is not just a product you buy once and forget about. Every car manufacturer knows that services is of prime importance to the products they build, simply because things WILL occur that have to be fixed and improved. It's the same with software. So make a presentation, visualize, verbalize, translate your technical information into benefits. Business people don't care about your wish for code aesthetics in a refactoring project, but they WILL understand that your changes will help the product to become more reliable, gain a better reputation and reduce the amount of future service requests. Make them understand by showing them the benefits!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205/" ] }
169,784
I am totally new to SQL . I have a simple select query similar to this: SELECT COUNT(col1) FROM table1 There are some 120 records in the table and shown on the GUI .For some reason, this query always returns a number which is less than the actual count. Can somebody please help me?
You might have some null values in col1 column. Aggregate functions ignore nulls.try this SELECT COUNT(ISNULL(col1,0)) FROM table1
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25065/" ] }
169,799
I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this. When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically. I've been trying to use JPanels like usercontrols in C#. I created a JPanel form called BlurbEditor . This has a few simple controls on it. I am trying to add it to another panel at run time on a button event. Here is the code that I thought would work: mainPanel.add(new BlurbEditor());mainPanel.revalidate();//I've also tried all possible combinations of these too//mainPanel.repaint();//mainPanel.validate(); This unfortunately is not working. What am I doing wrong?
I figured it out. The comments under the accepted answer here explain it: Dynamically added JTable not displaying Basically I just added the following before the mainPanel.add() mainPanel.setLayout(new java.awt.BorderLayout());
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21811/" ] }
169,810
I'm writing a simulator in Python, and am curious about options and opinions regarding basic 2D animations. By animation, I'm referring to rendering on the fly, not displaying prerendered images. I'm currently using matplotlib (Wxagg backend), and it's possible that I'll be able to continue using it, but I suspect it won't be able to sufficiently scale in terms of performance or capabilities. Requirements are: Cross-platform (Linux, MacOS X,Windows) Low complexity overhead Plays well with wxpython (at least won't step on each other's toes unduly) Interactivity. Detect when objects are clicked on, moused over, etc. Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good. Your thoughts?
I am a fan of pyglet which is a completely self contained library for doing graphical work under win32, linux, and OS X. It has very low overhead, and you can see this for yourself from the tutorial on the website. It should play well with wxpython, or at least I seem to recall posts to the mailing list about wxpython and pyglet being used together. It however does not offer selection of objects via mouse clicks - this you will have to handle yourself. Generally speaking for a 2D application this is not too difficult to do. mactorii is an OS X application of mine written in pure python+pyglet, and has some basic animation (scrolling) and click detection. It doesn't use wxpython, but perhaps it will give you an idea of what is involved. Note however mactorii is using the old pyglet api, so the run loop I have in there is obsolete. I will get around to updating it one day... :P
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22897/" ] }
169,812
Will there be a functional language which does for the Java community what F# does for the .NET community? What functional programming languages are available, or in development, for the JVM?
Scala would be the language. Though not strictly functional (it's a mix of functional and object-oriented) and it is not strictly for Java (there is a .NET version of Scala ), that would be the closest analog to F# in the JVM.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ] }
169,815
In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't. I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for. See also: Perl - Common gotchas .NET - Common gotchas
Comparing equality of objects using == instead of .equals() -- which behaves completely differently for primitives. This gotcha ensures newcomers are befuddled when "foo" == "foo" but new String("foo") != new String("foo") .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205/" ] }
169,817
I'm thinking the answer is no, but I'd love it it anybody had any insight into how to crawl a tree structure to any depth in SQL (MySQL), but with a single query More specifically, given a tree structured table (id, data, data, parent_id), and one row in the table, is it possible to get all descendants (child/grandchild/etc), or for that matter all ancestors (parent/grandparent/etc) without knowing how far down or up it will go, using a single query? Or is using some kind of recursion require, where I keep querying deeper until there are no new results? Specifically, I'm using Ruby and Rails, but I'm guessing that's not very relevant.
Here are several resources: http://forums.mysql.com/read.php?10,32818,32818#msg-32818 Managing Hierarchical Data in MySQL http://lists.mysql.com/mysql/201896 Basically, you'll need to do some sort of cursor in a stored procedure or query or build an adjacency table. I'd avoid recursion outside of the db: depending on how deep your tree is, that could get really slow/sketchy.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14873/" ] }
169,829
INotifyPropertyChanged is fairly self explanatory and I think I'm clear on when to raise that one (i.e. when I've finished updating the values). If I implement INotifyPropertyChanging I'm tending to raise the event as soon as I enter the setter or other method that changes the objects state and then continue with any guards and validations that may occur. So I'm treating the event as a notification that the property may change but hasn't yet been changed, and might not actually finish changing successfully. If consumers of the object are using this property (like let's say LINQ to SQL using the event for change tracking) should I be holding off and only raising the event once I have validated that the the values I've been given are good and the state of the object is valid for the change? What is the contract for this event and what side effects would there be in subscribers?
If your object is given a value that is invalid for the property and you throw an exception then you shouldn't raise the PropertyChanging event. You should only raise the event when you've decided that the value will change. The typical usage scenario is for changing a simple field: public T Foo { get { return m_Foo; } set { if (m_Foo == value) return; //no need for change (or notification) OnPropertyChanging("Foo"); m_Foo = value; OnPropertyChanged("Foo"); } }
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15572/" ] }
169,833
I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas?
The reference returned by window.open() is to the child window's window object. So you can do anything you would normally do, here's an example: var myWindow = window.open('...')myWindow.document.getElementById('foo').style.backgroundColor = 'red' Bear in mind that this will only work if the parent and child windows have the same domain . Otherwise cross-site scripting security restrictions will stop you.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ] }
169,862
I'm not looking for a full implementation, I'm more interested in how they do it. I know they use GWT, but I'd like a more low level answer. Naively, I would start by thinking when you click the popout link they simply open a new window and copy content into it. There are lots of reasons why that won't work out well, so I'm wondering if anyone knows or has ideas on how they do this or how it could be done.
I recently needed to solve exactly this problem in an app. I ended up using this great little jQuery plugin to do the trick: WindowMsg (see link at bottom) While I'm sure there are other ways to accomplish the same task, that plugin does works thusly: first you create a new child window from your original window using window.open you save a reference to the window object returned by window.open you call a library method in the child window that adds a hidden form for the library to store data in you call a library method in the parent window that uses window.document.forms to populate form fields on the child window (the library abstracts all of this stuff so you wouldn't even know there was a form involved unless you looked at the source) window.document.forms works the same on all major browsers so this abstraction in x-browser compatible finally, the child window refers back to its parent window using window.opener and can communicate back via a parallel hidden form on the parent the library implements a convenient helper that takes a callback function to run on each side to make the callback chain easy to deal with In my experience working with the library, it would have also been quite nice if they had included the JSON 2 lib from JSON.org. Out of the box, WindowMsg only allows you to send string messages between windows, but with some pretty simple use of the JSON 2 lib, I was able to hack it to allow the sending of full JSON objects between windows. I bet more mature libraries (such as whatever google uses) include that kind of serialization and de-serialization baked in. I am putting this link here because for some reason, the Stack Overflow formatter turns it into an anchor link with no closing tag and I don't want my whole post to be one giant hyperlink! WindowMsg: http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ] }
169,894
The Flot API documentation describes the library's extensive hooks for customizing the axes of a graph. You can set the number of ticks, their color, etc. separately for each axis. However, I can not figure out how to prevent Flot from drawing the vertical grid lines without also removing the x-axis labels. I've tried changing the tickColor, ticks, and tickSize options with no success. I want to create beautiful, Tufte-compatible graphs such as these: http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg I find the vertical ticks on my graphs to be chart junk. I am working with a time series that I am displaying as vertical bars so the vertical ticks often cut through the bars in a way that is visually noisy.
As Laurimann noted, Flot continues to evolve. The ability to control this has been added to the API (as noted in the flot issue Nelson linked to). If you download the latest version (which is still labeled 0.6), you can disable lines on an axis with "tickLength", like so: xaxis: { tickLength: 0} Rather annoyingly, this addition hasn't been updated in the API documentation.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/169894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10419/" ] }
169,897
I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error. And I found the py2exe said: The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security'] So how do I solve this problem? Thanks.
I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out. You can explicitly specify modules to include on the py2exe command line: python setup.py py2exe -p win32com -i twisted.web.resource Something like that. Read up on the options and experiment.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25077/" ] }
169,904
I'm using HttpListener to allow a user to set up a proxy on a user-defined port. When I start the HttpListener, I get an exception if the application isn't running under administrator privileges in Vista. From what I've read, this is expected behavior - administrator privileges are required to start listening on a port. But I'm sure there are ways around this, as I run plenty of programs (like Skype) which listen on a port without requiring elevation to administrator. Is there a way to do this with HttpListener? If not, can I make other API calls in .NET code to set up the port?
While you can write your own HTTP server using normal TCP/IP (it's relatively simple), it is easier to use HttpListener, which takes advantage of the HTTP.SYS functionality added in Windows XP SP2. However, HTTP.SYS adds the concept of URL ACLs. This is partly because HTTP.SYS allows you to bind to sub-namespaces on port 80. Using TCP/IP directly avoids this requirement, but means that you can't bind to a port that's already in use. On Windows XP, you can use the HttpCfg.exe program to set up a URL ACL granting your user account the right to bind to a particular URL. It's in the Platform SDK samples. On Windows Vista, HTTPCFG is still supported, but the functionality has been absorbed into NETSH: netsh http show urlacl ...will show a list of existing URL ACLs. The ACLs are expressed in SDDL. netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\User listen=yes ...will configure the MyURI namespace so that DOMAIN\User can listen to requests.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/169904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ] }
169,907
I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from dbb and marxidad )?
You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp : Function EncodeBase64(text As String) As String Dim arrData() As Byte arrData = StrConv(text, vbFromUnicode) Dim objXML As MSXML2.DOMDocument Dim objNode As MSXML2.IXMLDOMElement Set objXML = New MSXML2.DOMDocument Set objNode = objXML.createElement("b64") objNode.dataType = "bin.base64" objNode.nodeTypedValue = arrData EncodeBase64 = Replace(objNode.Text, vbLf, "") Set objNode = Nothing Set objXML = NothingEnd Function
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/169907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ] }
169,925
I want to convert a string into a double and after doing some math on it, convert it back to a string. How do I do this in Objective-C? Is there a way to round a double to the nearest integer too?
You can convert an NSString into a double with double myDouble = [myString doubleValue]; Rounding to the nearest int can then be done as int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5)) I'm honestly not sure if there's a more streamlined way to convert back into a string than NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/169925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ] }
169,929
I'm looking into writing an Eclipse plugin for FlexUnit and was wondering where I could get the sources for the JUnit Eclipse plugin. I checked the JUnit sources at sourceforge but couldn't spot any code that looked like the plugin code. Any idea where this code is available?
You can find it on Eclipse's repository: http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.pde.junit/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17255/" ] }
169,936
I'm wondering what's a reasonable size for iPhone Apps. Right now I'm working on an iPhone game, and of course it loads fast into my device since I'm connected directly to it through a USB cable, but I've no idea how long it would actually take to download from the App Store. In my case it's about 2mb in size, which is reasonable for a desktop or even a flash game, but I've no idea if this is reasonable size for the iPhone. My other concern is what's the non-wifi download limit of the App Store? Occasionally there are Apps that won't download unless you've got a wifi connection. And personally I've never downloaded such apps, since it gives me a bad impression. So I'd definitely want to stay below that limit. Also since I'm already asking about app sizes, it would be probably be useful to collect good sizes for other types of apps as well. Thanks!
Looking through some of the games i have on my phone they weigh in around 7 or 8 mb a pop. I think your 2mb will be fine. One thing i can tell you for sure is that if you want to be distributable over the cell network your application has to be under 50 mb. If you exceed this it will have to be downloaded using wifi or itunes on a computer.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/169936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ] }
169,973
When is it better to use a List vs a LinkedList ?
In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list. LinkedList<T> is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a List<T> is essentially just an array (with a wrapper) random access is fine. List<T> also offers a lot of support methods - Find , ToArray , etc; however, these are also available for LinkedList<T> with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/169973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ] }
170,004
Let's say: <div> pre text <div class="remove-just-this"> <p>child foo</p> <p>child bar</p> nested text </div> post text</div> to this: <div> pre text <p>child foo</p> <p>child bar</p> nested text post text</div> I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.
Using jQuery you can do this: var cnt = $(".remove-just-this").contents();$(".remove-just-this").replaceWith(cnt); Quick links to the documentation: contents ( ) : jQuery replaceWith ( content : [ String | Element | jQuery ] ) : jQuery
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/170004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20838/" ] }
170,019
I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved. Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session_start() as well as naming it before hand with session_name(). An added note . I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session_id($id); My intention in using session_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session_id not the session_name. It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session_id and your sessions will function as expected.
Session Cookies Remember that HTTP is stateless , so sessions are tracked on your server, but the client has to identify itself with each request. When you declare session_start(), your browser is usually setting a cookie (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name. All of this is to say that cookies are playing an active role in your sessions, so if the client doesn't support cookies , then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating. If cookies aren't an option for your client, you're going to have to find another way to pass a session id to the server. This can be done in the query string , for example, although it's a considered a bit less private to send a session id in this way. mysite.com?PHPSESSID=10alksdjfq9e How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the PHP website . Sidenote: Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns. Sidenote: @Uberfuzzy makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the curl manual .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8880/" ] }
170,021
We are currently running a SQL Job that archives data daily at every 10PM. However, the end users complains that from 10PM to 12, the page shows a time out error. Here's the pseudocode of the job while @jobArchive = 1 and @countProcecessedItem < @maxItem exec ArchiveItems @countProcecessedItem out if error occured set @jobArchive = 0 delay '00:10' The ArchiveItems stored procedure grabs the top 100 item that was created 30 days ago, process and archive them in another database and delete the item in the original table, including other tables that are related with it. finally sets the @countProcecessedItem with the number of item processed. The ArchiveItems also creates and deletes temporary tables it used to hold some records. Note: if the information I've provide is incomplete, reply and I'll gladly add more information if possible.
Session Cookies Remember that HTTP is stateless , so sessions are tracked on your server, but the client has to identify itself with each request. When you declare session_start(), your browser is usually setting a cookie (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name. All of this is to say that cookies are playing an active role in your sessions, so if the client doesn't support cookies , then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating. If cookies aren't an option for your client, you're going to have to find another way to pass a session id to the server. This can be done in the query string , for example, although it's a considered a bit less private to send a session id in this way. mysite.com?PHPSESSID=10alksdjfq9e How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the PHP website . Sidenote: Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns. Sidenote: @Uberfuzzy makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the curl manual .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24755/" ] }
170,028
This seems very noisy to me. Five lines of overhead is just too much. m_Lock.EnterReadLock()Try Return m_List.CountFinally m_Lock.ExitReadLock()End Try So how would you simply this?
I was thinking the same, but in C# ;-p using System;using System.Threading;class Program{ static void Main() { ReaderWriterLockSlim sync = new ReaderWriterLockSlim(); using (sync.Read()) { // etc } }}public static class ReaderWriterExt{ sealed class ReadLockToken : IDisposable { private ReaderWriterLockSlim sync; public ReadLockToken(ReaderWriterLockSlim sync) { this.sync = sync; sync.EnterReadLock(); } public void Dispose() { if (sync != null) { sync.ExitReadLock(); sync = null; } } } public static IDisposable Read(this ReaderWriterLockSlim obj) { return new ReadLockToken(obj); }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ] }
170,036
Does windows have any decent sampling (eg. non-instrumenting) profilers available? Preferably something akin to Shark on MacOS, although i am willing to accept that i am going to have to pay for such a profiler on windows. I've tried the profiler in VS Team Suite and was not overly impressed, and was wondering if there were any other good ones. [Edit: Erk, i forgot to say this is for C/C++, rather than .NET -- sorry for any confusion]
Intel VTune is good and is non-instrumenting. We evaluated a whole bunch of profilers for Windows, and this was the best for working with driver code (though it does unmanaged user level code as well). A particular strength is that it reads all the Intel processor performance counters, so you can get a good understanding of why your code is running slowly, and it was useful for putting prefetch instructions into our code and sorting out data layout to work well with the cache lines, and the way cache lines get invalidated in multi core systems. It is commercial, and I have to say it isn't the easiest UI in the world.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784/" ] }
170,070
What criteria should I use to decide whether I write VBA code like this: Set xmlDocument = New MSXML2.DOMDocument or like this: Set xmlDocument = CreateObject("MSXML2.DOMDocument") ?
As long as the variable is not typed as object Dim xmlDocument as MSXML2.DOMDocumentSet xmlDocument = CreateObject("MSXML2.DOMDocument") is the same as Dim xmlDocument as MSXML2.DOMDocumentSet xmlDocument = New MSXML2.DOMDocument both use early binding. Whereas Dim xmlDocument as ObjectSet xmlDocument = CreateObject("MSXML2.DOMDocument") uses late binding. See MSDN here . When you’re creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function. New requires that a type library is referenced. Whereas CreateObject uses the registry. CreateObject can be used to create an object on a remote machine.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ] }
170,078
How do I set a variable to the result of select query without using a stored procedure? I want to do something like:OOdate DATETIME SET OOdate = Select OO.Date FROM OLAP.OutageHours as OOWHERE OO.OutageID = 1 Then I want to use OOdate in this query: SELECT COUNT(FF.HALID) from Outages.FaultsInOutages as OFIOINNER join Faults.Faults as FF ON FF.HALID = OFIO.HALIDWHERE CONVERT(VARCHAR(10),OO.Date,126) = CONVERT(VARCHAR(10),FF.FaultDate,126)) ANDOFIO.OutageID = 1
You can use something like SET @cnt = (SELECT COUNT(*) FROM User) or SELECT @cnt = (COUNT(*) FROM User) For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis. Edit : Have you tried something like this? DECLARE @OOdate DATETIMESET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1Select COUNT(FF.HALID) from Outages.FaultsInOutages as OFIO inner join Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE @OODate = FF.FaultDate AND OFIO.OutageID = 1
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ] }
170,097
I've gone to http://sourceforge.net/project/showfiles.php?group_id=2435 , downloaded the Automated MinGW Installer for MinGW 5.1.4 and at the same time the GNU Source-Level Debugger Release Candidate: GDB 6.8-3. I've then installed MinGW base tools into C:\MinGW. No problem so far. However when I come to install the gdb debugger it has a lot of files and folders with the same names as some already installed but the files are different to those already installed. e.g C:\MinGW\include\bfd.h is 171 KB but gdb-6.8-mingw-3\include\bfd.h is 184 KB. How do I add gdb to MinGW without breaking what's already installed?
In a command prompt I browsed to C:\MinGW\bin and ran: mingw-get.exe install gdb That fixed it for me. Not sure if it matters but I have C:\MinGW\bin in my path (guess I probably didn't need to browse to C:\MinGW\bin).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25093/" ] }
170,152
I know that in the end it, can't be done. But, what are the options to: a) limit the options for persons to create multiple accounts, b) increase the chance of detecting multiple accounts / person for a blog-like web service? (people can sign up for their own blog) Update: I think the 'limit the options' has been answered nicely. (there is no reliable method, but we can raise the bar) However, I would still like to know what other options there are to detect multiple accounts?
I'm assuming you're talking about a free service? I can't think of any ways that don't either have serious drawbacks or would be trivial to defeat. Things like setting a cookie, requiring a unique e-mail address are easy to defeat. Requiring a unique IP address is not foolproof but might work to some degree, up to the point that you have lots of users and get complaints from people behind proxies. The best ways are to charge money or require people provide some kind of personal information, like real name/phone/address that you verify, or a CC number, but that's invasive (then again maybe you only want serious users who are willing to provide this sort of info). I guess I would turn the question around and ask "Why don't you want to let people have multiple accounts?" There may be some other ways of mitigating whatever your underlying reason is, i.e. if you're worried about lots of orphaned blogs you could scan for a period of inactivity and disable them or at least schedule them to be looked at by a human. If you're worried about spam blogs you could periodically scan all blog content for spammy stuff. If you're worried about bots and are using some generic software like WordPress, change the names of the form variables and otherwise protect your forms from bots. Definitely think of other ways of dealing with the problem, because you are not going to be able to block people from registering multiple accounts if it's a typical free service like Blogger. As for detecting multiple accounts by one person, the first thing you need to do is have a log file store complete data on every user login (username, timestamp, IP, user-agent etc.), that you can then analyze later. I'll list a few things to look out for, but just by poring over the log file you will likely discover other patterns. Some ideas of things to look for are: Set a tracking cookie (i.e. random hash) and log its value on login, look for multiple logins from the same cookie value Logins from same IP address/user-agent combination Logins from same IP address only (less reliable than the previous two bullets) Accounts with email addresses from free webmail services (Gmail etc.) Accounts with same password If you're worried about spam blogs, you could try doing some analysis of blog content, i.e. extract all the <a href> s and look for correlations between blogs. You could run the blog content itself though something like SpamAssassin or otherwise filter for spammy words like "viagra" and "rolex."
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22674/" ] }
170,168
I am looking for a template engine to use client side. I have been trying a few like jsRepeater and jQuery Templates. While they seem to work OK in FireFox they all seem to break down in IE7 when it comes down to rendering HTML tables. I also took a look at MicrosoftAjaxTemplates.js (from http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16766 ) but turns out that has the same problem. Any advice on other templating engines to use?
Check out Rick Strahl's post Client Templating with jQuery . He explores jTemplates, but then makes a better case for John Resig's micro-templating solution , even improving it some. Good comparisons, lots of samples.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/170168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19676/" ] }
170,180
I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though: function config() { $("#frmMain").children().map(function() { var child = $("this"); if (child.is(":checkbox")) this[child.attr("name")] = child.attr("checked"); if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); return null; }); Neither does the following (inspired by jobscry's answer): function config() { $("#frmMain").children().each(function() { var child = $("this"); alert(child.length); if (child.is(":checkbox")) { this[child.attr("name")] = child.attr("checked"); } if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); });} The alert always shows that child.length == 0 . Manually selecting the elements works: >>> $("#frmMain").children()Object length=42>>> $("#frmMain").children().filter(":checkbox")Object length=3 Any hints on how to do the loop correctly?
don't think you need quotations on this: var child = $("this"); try: var child = $(this);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25097/" ] }
170,186
I was previously taught today how to set parameters in a SQL query in .NET in this answer ( click ). Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter. e.g. Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn)If actLimit.ToLower() = "unlimited" Then ' It's not nulling :( dc.Parameters.Add(New SqlParameter("Limit", Nothing))Else dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit)))End If Is there something I'm missing? Am I doing it wrong?
you want DBNull .Value. In my shared DAL code, I use a helper method that just does: foreach (IDataParameter param in cmd.Parameters) { if (param.Value == null) param.Value = DBNull.Value; }
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/170186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ] }
170,207
What kind of optimization patterns can be used to improve the performance of the garbage collector? My reason for asking is that I do a lot of embedded software using the Compact Framework. On slow devices the garbage collection can become a problem, and I would like to reduce the times the garbage collector kicks in, and when it does, I want it to finish quicker. I can also see that working with the garbage collector instead of against it could help improve any .NET or Java application, especially heavy duty web applications. Here are some of my thoughts, but I haven’t done any benchmarks. reusing temporary classes/arrays (keep down allocation count) keeping the amount of live objects to a minimum (faster collections) try to use structs instead of classes
The key is to understand how the CF GC works for allocations. It's a simple mark-and-sweep, non-generational GC with specific algorithms for what will trigger a GC, and what will cause compaction and/or pitching after collection. There is almost nothing you can do at an app level to control the GC (the only method available is Collect, and it's use is pretty limited, as you can't force compaction anyway). Object re-use is a good start, but simply keeping the object count low is probably one of the best tools, as all roots have to be walked for any collection operation. Keeping that walk short is a good idea. If compaction is killing you, then preventing segment fragmentation will help. Objects >64k can be helpful in that regard as they get their own segment and are treated differently than smaller objects. To really understand how the CF GC works, I'd recommend watching the MSDN Webcast on CF memory management .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20715/" ] }
170,223
Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups. However, when inserting one must always check if the first index already exists in the hash. For example: h = Hash.newh['x'] = Hash.new if not h.key?('x')h['x']['y'] = value_to_insert It would be preferable to do the following where the new Hash is created automatically: h = Hash.newh['x']['y'] = value_to_insert Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error. looked_up_value = h['w']['z'] One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task?
You can pass the Hash.new function a block that is executed to yield a default value in case the queried value doesn't exist yet: h = Hash.new { |h, k| h[k] = Hash.new } Of course, this can be done recursively. There's an article explaining the details . For the sake of completeness, here's the solution from the article for arbitrary depth hashes: hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)})) The person to originally come up with this solution is Kent Sibilev .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/170223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3533/" ] }
170,272
I have a class like the following: public class DropDownControl<T, Key, Value> : BaseControl where Key: IComparable{ private IEnumerable<T> mEnumerator; private Func<T, Key> mGetKey; private Func<T, Value> mGetValue; private Func<Key, bool> mIsKeyInCollection; public DropDownControl(string name, IEnumerable<T> enumerator, Func<T, Key> getKey, Func<T, Value> getValue, Func<Key, bool> isKeyInCollection) : base(name) { mEnumerator = enumerator; mGetKey = getKey; mGetValue = getValue; mIsKeyInCollection = isKeyInCollection; } And I want to add a convenience function for Dictionaries (because they support all operations efficiently on their own). But the problem is that such a constructor would only specify Key and Value but not T directly, but T is just KeyValuePair. Is there a way to tell the compiler for this constructor T is KeyValuePair, like: public DropDownControl<KeyValuePair<Key, Value>>(string name, IDictionary<Key, Value> dict) { ... } Currently I use a static Create function as workaround, but I would like a direct constructor better. public static DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue> Create<DKey, DValue>(string name, IDictionary<DKey, DValue> dictionary) where DKey: IComparable { return new DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue>(name, dictionary, kvp => kvp.Key, kvp => kvp.Value, key => dictionary.ContainsKey(key)); }
No, basically. The static method in a non-generic class (such as DropDownControl [no <>]) is the best approach, as you should be able to use type-inference when you call Create() - i.e. var control = DropDownControl.Create(name, dictionary); C# 3.0 helps here both via "var" (very welcome here) and by the much-improved generic type inference rules. In some (more general) case, another similar option is an extension method, but an extension method to create a very specific control from a dictionary doesn't feel very natural - I'd use a non-extension method. Something like: public static class DropDownControl{ public static DropDownControl<KeyValuePair<TKey,TValue>, TKey, TValue> Create<TKey,TValue>(IDictionary<TKey, TValue> value, string name) where TKey : IComparable { return new DropDownControl<KeyValuePair<TKey, TValue>, TKey, TValue> (name, value, pair => pair.Key, pair => pair.Value, key => value.ContainsKey(key) ); }} Another option is inheritance, but I don't like it much... public class DropDownControl<TKey, TValue> : DropDownControl<KeyValuePair<TKey, TValue>, TKey, TValue> where TKey : IComparable{ public DropDownControl(IDictionary<TKey, TValue> lookup, string name) : base(name, lookup, pair => pair.Key, pair => pair.Value, key => lookup.ContainsKey(key)) { }} This adds complexity and reduces your flexibility... I wouldn't do this... Overall, it sounds like you want to be working with just IDictionary<,> - I wonder if you can't simplify your control to just use this, and force non-dictionary callers to wrap themselves in an IDictionary<,> facade?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21566/" ] }
170,328
I would like to execute a stored procedure within a stored procedure, e.g. EXEC SP1BEGINEXEC SP2END But I only want SP1 to finish after SP2 has finished running so I need to find a way for SP1 to wait for SP2 to finish before SP1 ends. SP2 is being executed as part of SP1 so I have something like: CREATE PROCEDURE SP1ASBEGINEXECUTE SP2END
T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want. CREATE PROCEDURE SP1 AS EXEC SP2 PRINT 'Done'
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ] }