source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
148,968 | As I understand it, .bat is the old 16-bit naming convention, and .cmd is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will never need to run on anything older than NT, does it really matter which way I name my batch files, or is there some gotcha awaiting me by using the wrong suffix? | From this news group posting by Mark Zbikowski himself: The differences between .CMD and .BAT as far as CMD.EXE is concerned are: With extensions enabled, PATH/APPEND/PROMPT/SET/ASSOC in .CMD files will set ERRORLEVEL regardless of error. .BAT sets ERRORLEVEL only on errors. In other words, if ERRORLEVEL is set to non-0 and then you run one of those commands, the resulting ERRORLEVEL will be: left alone at its non-0 value in a .bat file reset to 0 in a .cmd file. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/148968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
]
} |
148,977 | What is the keyboard-shortcut that expands the menu, from the little red line, and offers the option to have the necessary using statement appended to the top of the file? | Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10 . This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/148977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3268/"
]
} |
148,982 | I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time. ex. function A: add(new Array("hello", some function)); function B: public function b(args:Array) { var myString = args[0]; var myFunc = args[1];} | Simply pass the function name as an argument, no, just like in AS2 or JavaScript? function functionToPass(){}function otherFunction( f:Function ){ // passed-in function available here f();}otherFunction( functionToPass ); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
148,988 | I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree. XML example: <?xml version="1.0" encoding="utf-8"?><node> <attribute/> <node> <attribute/> <node/> </node></node> Which is the best way to validate it? Recursion? | if you need a recursive type declaration, here is an example that might help: <xs:schema id="XMLSchema1" targetNamespace="http://tempuri.org/XMLSchema1.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XMLSchema1.xsd" xmlns:mstns="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="node" type="nodeType"></xs:element> <xs:complexType name="nodeType"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="node" type="nodeType"></xs:element> </xs:sequence> </xs:complexType></xs:schema> As you can see, this defines a recursive schema with only one node named "node" which can be as deep as desired. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19012/"
]
} |
149,032 | Some people want to move code from user space to kernel space in Linux for some reason. A lot of times the reason seems to be that the code should have particularly high priority or simply "kernel space is faster". This seems strange to me. When should I consider writing a kernel module? Are there a set of criterias? How can I motivate keeping code in user space that (I believe) belong there? | Rule of thumb: try your absolute best to keep your code in user-space. If you don't think you can, spend as much time researching alternatives to kernel code as you would writing the code (ie: a long time), and then try again to implement it in user-space. If you still can't, research more to ensure you're making the right choice, then very cautiously move into the kernel. As others have said, there are very few circumstances that dictate writing kernel modules and debugging kernel code can be quite hellish, so steer clear at all costs. As far as concrete conditions you should check for when considering writing kernel-mode code, here are a few: Does it need access to extremely low-level resources, such as interrupts? Is your code defining a new interface/driver for hardware that cannot be built on top of currently exported functionality? Does your code require access to data structures or primitives that are not exported out of kernel space? Are you writing something that will be primarily used by other kernel subsystems, such as a scheduler or VM system (even here it isn't entirely necessary that the subsystem be kernel-mode: Mach has strong support for user-mode virtual memory pagers, so it can definitely be done)? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6759/"
]
} |
149,033 | I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++? I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested. | Having dealt with this in actual financial systems, I can tell you you probably want to use a number with at least 6 decimal places of precision (assuming USD). Hopefully since you're talking about currency values you won't go way out of whack here. There are proposals for adding decimal types to C++, but I don't know of any that are actually out there yet. The best native C++ type to use here would be long double. The problem with other approaches that simply use an int is that you have to store more than just your cents. Often financial transactions are multiplied by non-integer values and that's going to get you in trouble since $100.25 translated to 10025 * 0.000123523 (e.g. APR) is going cause problems. You're going to eventually end up in floating point land and the conversions are going to cost you a lot. Now the problem doesn't happen in most simple situations. I'll give you a precise example: Given several thousand currency values, if you multiply each by a percentage and then add them up, you will end up with a different number than if you had multiplied the total by that percentage if you do not keep enough decimal places. Now this might work in some situations, but you'll often be several pennies off pretty quickly. In my general experience making sure you keep a precision of up to 6 decimal places (making sure that the remaining precision is available for the whole number part). Also understand that it doesn't matter what type you store it with if you do math in a less precise fashion. If your math is being done in single precision land, then it doesn't matter if you're storing it in double precision. Your precision will be correct to the least precise calculation. Now that said, if you do no math other than simple addition or subtraction and then store the number then you'll be fine, but as soon as anything more complex than that shows up, you're going to be in trouble. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
149,037 | How can I instantiate a JMS queue listener in java (JRE /JDK / J2EE 1.4) that only receives messages that match a given JMSCorrelationID? The messages that I'm looking to pick up have been published to a queue and not a topic, although that can change if needed. Here's the code that I'm currently using to put the message in the queue: /** * publishResponseToQueue publishes Requests to the Queue. * * @param jmsQueueFactory -Name of the queue-connection-factory * @param jmsQueue -The queue name for the request * @param response -A response object that needs to be published * * @throws ServiceLocatorException -An exception if a request message * could not be published to the Topic */private void publishResponseToQueue( String jmsQueueFactory, String jmsQueue, Response response ) throws ServiceLocatorException { if ( logger.isInfoEnabled() ) { logger.info( "Begin publishRequestToQueue: " + jmsQueueFactory + "," + jmsQueue + "," + response ); } logger.assertLog( jmsQueue != null && !jmsQueue.equals(""), "jmsQueue cannot be null" ); logger.assertLog( jmsQueueFactory != null && !jmsQueueFactory.equals(""), "jmsQueueFactory cannot be null" ); logger.assertLog( response != null, "Request cannot be null" ); try { Queue queue = (Queue)_context.lookup( jmsQueue ); QueueConnectionFactory factory = (QueueConnectionFactory) _context.lookup( jmsQueueFactory ); QueueConnection connection = factory.createQueueConnection(); connection.start(); QueueSession session = connection.createQueueSession( false, QueueSession.AUTO_ACKNOWLEDGE ); ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setJMSCorrelationID(response.getID()); objectMessage.setObject( response ); session.createSender( queue ).send( objectMessage ); session.close(); connection.close(); } catch ( Exception e ) { //XC3.2 Added/Modified BEGIN logger.error( "ServiceLocator.publishResponseToQueue - Could not publish the " + "Response to the Queue - " + e.getMessage() ); throw new ServiceLocatorException( "ServiceLocator.publishResponseToQueue " + "- Could not publish the " + "Response to the Queue - " + e.getMessage() ); //XC3.2 Added/Modified END } if ( logger.isInfoEnabled() ) { logger.info( "End publishResponseToQueue: " + jmsQueueFactory + "," + jmsQueue + response ); }} // end of publishResponseToQueue method | The queue connection setup is the same, but once you have the QueueSession, you set the selector when creating a receiver. QueueReceiver receiver = session.createReceiver(myQueue, "JMSCorrelationID='theid'"); then receiver.receive() or receiver.setListener(myListener); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231627/"
]
} |
149,042 | My questions is simple! Would you start learning Smalltalk if you had the time? Why? Why not? Do you already know Smalltalk? Why would you recommend Smalltalk? Why not? Personally I'm a Ruby on Rails programmer and I really like it. However, I'm thinking about Smalltalk because I read various blogs and some people are calling Ruby something like "Smalltalk Light". The second reason why I'm interested in Smalltalk is Seaside . Maybe someone has made the same transition before? EDIT: Actually, what got me most excited about Smalltalk/Seaside is the following Episode of WebDevRadio: Episode 52: Randal Schwartz on Seaside (among other things) | If you like Ruby you'll probably like Smalltalk. IIRC Seaside has been ported to the Gemstone VM, which is part of their Gemstone/S OODBMS. This has much better thread support than Ruby, so it is a better back-end for a high-volume system. This might be a good reason to take a close look at it. Reasons to learn Smalltalk: It's a really, really nice programming environment. Once you've got your head around it (it tends to be a bit of a culture shock for people used to C++ or Java) you'll find it to be a really good environment to work in. Even a really crappy smalltalk like the Old Digitalk ones I used is a remarkably pleasant system to use. Many of the old XP and O-O guru types like Kent Beck and Martin Fowler cut their teeth on Smalltalk back in the day and can occasionally be heard yearning for the good old days in public (Thanks to Frank Shearer for the citation, +1) - Agile development originated on this platform. It's one of the most productive development platforms in history. Several mature implementations exist and there's a surprisingly large code base out there. At one point it got quite trendy in financial market circles where developer productivity and time-to-market is quite a big deal. Up until the mid 1990s it was more or less the only game in town (With the possible exception of LISP) if you wanted a commercially supported high-level language that was suitable for application development. Deployment is easy - just drop the image file in the appropriate directory. Not really a reason, but the Gang of Four Book uses Smalltalk for quite a few of their examples. Reasons not to learn Smalltalk: It's something of a niche market. You may have trouble finding work. However if you are producing some sort of .com application where you own the servers this might not be an issue. It's viewed as a legacy system by many. There is relatively little new development on the platform (although Seaside seems to be driving a bit of a renaissance). It tends not to play nicely with traditional source control systems (at least as of the early-mid 90's when I used it). This may or may not still be the case. It is somewhat insular and likes to play by itself. Python or Ruby are built for integration from the ground up and tend to be more promiscuous and thus easier to integrate with 3rd party software. However, various other more mainstream systems suffer from this type of insularity to a greater or lesser degree and that doesn't seem to impede their usage much. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/149042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467/"
]
} |
149,055 | I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this: "$ 2,500.00" How can I do this? | Number.prototype.toFixed This solution is compatible with every single major browser: const profits = 2489.8237; profits.toFixed(3) // Returns 2489.824 (rounds up) profits.toFixed(2) // Returns 2489.82 profits.toFixed(7) // Returns 2489.8237000 (pads the decimals) All you need is to add the currency symbol (e.g. "$" + profits.toFixed(2) ) and you will have your amount in dollars. Custom function If you require the use of , between each digit, you can use this function: function formatMoney(number, decPlaces, decSep, thouSep) { decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces, decSep = typeof decSep === "undefined" ? "." : decSep; thouSep = typeof thouSep === "undefined" ? "," : thouSep; var sign = number < 0 ? "-" : ""; var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces))); var j = (j = i.length) > 3 ? j % 3 : 0; return sign + (j ? i.substr(0, j) + thouSep : "") + i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) + (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");}document.getElementById("b").addEventListener("click", event => { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);}); <label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label><br /><button id="b">Get Output</button><p id="x">(press button to get output)</p> Use it like so: (123456789.12345).formatMoney(2, ".", ","); If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you. (123456789.12345).formatMoney(2); If your culture has the two symbols flipped (i.e., Europeans) and you would like to use the defaults, just paste over the following two lines in the formatMoney method: d = d == undefined ? "," : d, t = t == undefined ? "." : t, Custom function (ES6) If you can use modern ECMAScript syntax (i.e., through Babel), you can use this simpler function instead: function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") { try { decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount < 0 ? "-" : ""; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length > 3) ? i.length % 3 : 0; return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : ""); } catch (e) { console.log(e) }};document.getElementById("b").addEventListener("click", event => { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);}); <label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label><br /><button id="b">Get Output</button><p id="x">(press button to get output)</p> | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/149055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
]
} |
149,057 | How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders. Also, I want to to be able to modify the file directly, and not just print everything to stdout. | Here is an OS X >= 10.6 Snow Leopard solution. It Ignores .git and .svn folders and their contents. Also it won't leave a backup file. (export LANG=C LC_CTYPE=Cfind . -not \( -name .svn -prune -o -name .git -prune \) -type f -print0 | perl -0ne 'print if -T' | xargs -0 sed -Ei 's/[[:blank:]]+$//') The enclosing parenthesis preserves the L* variables of current shell – executing in subshell. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19718/"
]
} |
149,073 | I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace: public function PrintStackTrace() { try { throw new Error('StackTrace'); } catch (e:Error) { trace(e.getStackTrace()); }} I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know. Thanks! | As far as I know, the only way to make the stack trace available to your own code is via the getStackTrace() method in the Error class, just like you're already doing. In response to the example in your question, though, I would mention that you don't actually have to throw the Error -- you can just create it and call the method on it: var tempError:Error = new Error();var stackTrace:String = tempError.getStackTrace(); Also, like the documentation says, this only works in the debug version of Flash Player, so you can wrap this functionality in an if-block that checks the value of Capabilities.isDebugger if you want. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/149073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
]
} |
149,078 | Suppose I have a database table with two fields, "foo" and "bar". Neither of them are unique, but each of them are indexed. However, rather than being indexed together, they each have a separate index. Now suppose I perform a query such as SELECT * FROM sometable WHERE foo='hello' AND bar='world'; My table a huge number of rows for which foo is 'hello' and a small number of rows for which bar is 'world'. So the most efficient thing for the database server to do under the hood is use the bar index to find all fields where bar is 'world', then return only those rows for which foo is 'hello'. This is O(n) where n is the number of rows where bar is 'world'. However, I imagine it's possible that the process would happen in reverse, where the fo index was used and the results searched. This would be O(m) where m is the number of rows where foo is 'hello'. So is Oracle smart enough to search efficiently here? What about other databases? Or is there some way I can tell it in my query to search in the proper order? Perhaps by putting bar='world' first in the WHERE clause? | Oracle will almost certainly use the most selective index to drive the query, and you can check that with the explain plan. Furthermore, Oracle can combine the use of both indexes in a couple of ways -- it can convert btree indexes to bitmaps and perform a bitmap ANd operation on them, or it can perform a hash join on the rowid's returned by the two indexes. One important consideration here might be any correlation between the values being queried. If foo='hello' accounts for 80% of values in the table and bar='world' accounts for 10%, then Oracle is going to estimate that the query will return 0.8*0.1= 8% of the table rows. However this may not be correct - the query may actually return 10% of the rwos or even 0% of the rows depending on how correlated the values are. Now, depending on the distribution of those rows throughout the table it may not be efficient to use an index to find them. You may still need to access (say) 70% or the table blocks to retrieve the required rows (google for "clustering factor"), in which case Oracle is going to perform a ful table scan if it gets the estimation correct. In 11g you can collect multicolumn statistics to help with this situation I believe. In 9i and 10g you can use dynamic sampling to get a very good estimation of the number of rows to be retrieved. To get the execution plan do this: explain plan forSELECT *FROM sometableWHERE foo='hello' AND bar='world'/select * from table(dbms_xplan.display)/ Contrast that with: explain plan forSELECT /*+ dynamic_sampling(4) */ *FROM sometableWHERE foo='hello' AND bar='world'/select * from table(dbms_xplan.display)/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
]
} |
149,118 | We have been designing our reports around Crystal Reports in VS2008 for our web application and I just discovered the Microsoft provided ReportViewer control. I've searched around a bit but cannot find a good breakdown of the pros and cons of each method of producing reports. I'm looking for pros and cons regarding: Ease of development Ease of deployment Ability to export data Ease of support and finding help on the web | Well, I can answer for one side. I have used ReportViewer aka Client Side Reporting. I can tell you its easy to use, easy to deploy and easy to develop. If you can create SQL Reporting Services reports, you can create these. They can take any kind of datasource so you have full control. Here is an excellent book on Client Side reporting . There are built in PDF and Excel exports available but you can add your own export handling also. You can use in winforms, Asp.Net in your own services. You can do really anything you can imagine with them. For Crystal Reports, I do not know much about them. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7561/"
]
} |
149,130 | In an aspx C#.NET page (I am running framework v3.5), I need to know where the user came from since they cannot view pages without logging in. If I have page A (the page the user wants to view) redirect to page B (the login page), the Request.UrlReferrer object is null. Background: If a user isn't logged in, I redirect to the Login page ( B in this scenario). After login, I would like to return them to the page they were requesting before they were forced to log in. UPDATE: A nice quick solution seems to be: //if user not logged in Response.Redirect("..MyLoginPage.aspx?returnUrl=" + Request.ServerVariables["SCRIPT_NAME"]); Then, just look at QueryString on login page you forced them to and put the user where they were after successful login. | If you use the standard Membership provider, and set the Authorization for the directory/page, the code will automatically set a query parameter of ReturnUrl and redirect after a successfull login. If you don't want to use the Membership provider pattern, I would suggest manually doing the query string parameter thing as well. HTTP referrers are not very reliable. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8426/"
]
} |
149,132 | I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario: I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table. How do I do this without the use of cursors? Should be an easy one for you sql gurus! | This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example: CREATE TABLE #t (uniqueid int)INSERT INTO #t EXEC p_YourStoredProcUPDATE TargetTable SET a.FlagColumn = 1FROM TargetTable a JOIN #t b ON a.uniqueid = b.uniqueidDROP TABLE #t | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
]
} |
149,163 | Are there any templates/patterns/guides I can follow for designing a multithreaded server? I can't find anything terribly useful online through my google searches. My program will start a thread to listen for connections using TcpListener.Every client connection will be handled by it's own IClientHandler thread. The server will wrap the clientHandler.HandleClient in a delegate, call BeginInvoke, and then quit caring about it. I also need to be able to cleanly shutdown the listening thread, which is something I'm not finding a lot of exampes of online. I'm assuming some mix of lock/AutoResetEvents/threading magic combined with the async BeginAceptTcpClient and EndAcceptTcpClient will get me there, but when it comes to networking code, to me it's all been done. So I have to believe there's just some pattern out there I can follow and not get totally confused by the myriad multithreaded corner cases I can never seem to get perfect. Thanks. | Oddly enough you may find something on a Computer Science Assignment, CSC 512 Programming Assignment 4: Multi-Threaded Server With Patterns . Altough it's C++ voodoo but the theory is quite understandable for someone who can do C#. Acceptor/ Connector Monitor Object Thread Safe Interface Wrapper Facade Scoped Locking Strategized Locking Reactor Half Sync/Half-Async Leaders/Followers Altough you can get the whole list of nice readings on the main page . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285/"
]
} |
149,191 | I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function: function Return-True { return $true } and then some sample code to invoke it: PS C:\> Return-TrueTruePS C:\> Return-True -eq $falseTruePS C:\> (Return-True) -eq $falseFalse Ideas? Comments? | When PowerShell sees the token Return-True it identifies it as a command and until evaluation or end of the statement, everything else is an argument which is passed to the function Return-True . You can see this in action if you do: PS > function Return-True { "The arguments are: $args"; return $true }PS > Return-True -eq $falseThe arguments are: -eq FalseTrue That's why all of the following return 'True', because all you are seeing is the result of calling Return-True with various arguments: PS > Return-True -eq $falseTruePS > Return-True -ne $falseTruePS > Return-True -eq $trueTruePS > Return-True -ne $trueTrue Using (Return-True) forces PowerShell to evaluate the function (with no arguments). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243/"
]
} |
149,198 | I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system. What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me. I heard Git supports this, please let me know if this is correct. | Mercurial can do this with the record extension. It'll prompt you for each file and each diff hunk. For example: % hg recorddiff --git a/prelim.tex b/prelim.tex2 hunks, 4 lines changedexamine changes to 'prelim.tex'? [Ynsfdaq?] @@ -12,7 +12,7 @@ \setmonofont[Scale=0.88]{Consolas} % missing from xunicode.sty \DeclareUTFcomposite[\UTFencname]{x00ED}{\'}{\i}-\else+\else foo \usepackage[pdftex]{graphicx} \firecord this change to 'prelim.tex'? [Ynsfdaq?] @@ -1281,3 +1281,5 @@ %% Local variables: %% mode: latex %% End:++foo\ No newline at end of filerecord this change to 'prelim.tex'? [Ynsfdaq?] nWaiting for Emacs... After the commit, the remaining diff will be left behind: % hg didiff --git a/prelim.tex b/prelim.tex--- a/prelim.tex+++ b/prelim.tex@@ -1281,3 +1281,5 @@ %% Local variables: %% mode: latex %% End:++foo\ No newline at end of file Alternatively, you may find it easier to use MQ (Mercurial Queues) to separate the individual changes in your repository into patches. There is a MQ variant of record (qrecord), too. Update: Also try the crecord extension, which provides a curses interface to hunk/line selection. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6752/"
]
} |
149,262 | What delphi function asserts that an object is not nil? | Like knight_killer pointed out above, you use the Assert() function, asserting that Assigned(obj) is true . Of course, like in most compiled languages, assertions are not executed (or even included in the compiler output) unless you've specifically enabled them, so you should not rely on assertions for release mode builds. You can, of course, simply check against nil , a la Assert(obj <> nil) . However, Assigned() produces the exact same compiler output and has the added benefit that it works on pointers to class methods too (which are in reality a pair of pointers, one to the method, and the other one to the class instance), so using Assigned() is a good habit to pick up. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
]
} |
149,268 | Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library? | Boost is organized by several members of the standard committee. So it is a breeding ground for libraries that will be in the next standard. It is an extension to the STL (it fills in the bits left out) It is well documented. It is well peer-reviewed. It has high activity so bugs are found and fixed quickly. It is platform neutral and works everywhere. It is free to use. With tr1 coming up soon it is nice to know that boost already has a lot of the ground covered. A lot of the libraries in tr1 are basically adapted directly from boost originals and thus have been tried and tested. The difference is that they have been moved into the std::tr1 namespace (rather than boost). All that you need to do is add the following to your compilers default include search path : <boost-install-path>/boost/tr1/tr1 Then when you include the standard headers boost will automatically import all the required stuff into the namespace std::tr1 For Example: To use std::tr1::share_ptr you just need to include <memory>. This will give you all the smart pointers with one file. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/149268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
]
} |
149,274 | Are there any major differences in performance between http and https? I seem to recall reading that HTTPS can be a fifth as fast as HTTP. Is this valid with the current generation webservers/browsers? If so, are there any whitepapers to support it? | There's a very simple answer to this: Profile the performance of your web server to see what the performance penalty is for your particular situation. There are several tools out there to compare the performance of an HTTP vs HTTPS server (JMeter and Visual Studio come to mind) and they are quite easy to use. No one can give you a meaningful answer without some information about the nature of your web site, hardware, software, and network configuration. As others have said, there will be some level of overhead due to encryption, but it is highly dependent on: Hardware Server software Ratio of dynamic vs static content Client distance to server Typical session length Etc (my personal favorite) Caching behavior of clients In my experience, servers that are heavy on dynamic content tend to be impacted less by HTTPS because the time spent encrypting (SSL-overhead) is insignificant compared to content generation time. Servers that are heavy on serving a fairly small set of static pages that can easily be cached in memory suffer from a much higher overhead (in one case, throughput was havled on an "intranet"). Edit: One point that has been brought up by several others is that SSL handshaking is the major cost of HTTPS. That is correct, which is why "typical session length" and "caching behavior of clients" are important. Many, very short sessions means that handshaking time will overwhelm any other performance factors. Longer sessions will mean the handshaking cost will be incurred at the start of the session, but subsequent requests will have relatively low overhead. Client caching can be done at several steps, anywhere from a large-scale proxy server down to the individual browser cache. Generally HTTPS content will not be cached in a shared cache (though a few proxy servers can exploit a man-in-the-middle type behavior to achieve this). Many browsers cache HTTPS content for the current session and often times across sessions. The impact the not-caching or less caching means clients will retrieve the same content more frequently. This results in more requests and bandwidth to service the same number of users. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/149274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
]
} |
149,318 | The IT department where I work is trying to move to 100% virtualized servers, with all the data stored on a SAN. They haven't done it yet, but the plan eventually calls for moving the existing physical SQL Server machines to virtual servers as well. A few months ago I attended the Heroes Happen Here launch event, and in one of the SQL Server sessions the speaker mentioned in passing that this is not a good idea for production systems. So I'm looking for a few things: What are the specific reasons why this is or is not a good idea? I need references, or don't bother responding. I could come up with a vague "I/O bound" response on my own via google. The HHH speaker recollection alone probably won't convince our IT department to change their minds. Can anyone point me directly to something more authoritative? And by "directly", I mean something more specific than just a vague Books OnLine comment. Please narrow it down a little. | I can say this from personal experience because I am dealing with this very problem as we speak. The place I am currently working as a contractor has this type of environment for their SQL Server development systems. I am trying to develop a fairly modest B.I. system on this environment and really struggling with the performance issues. TLB misses and emulated I/O are very slow on a naive virtual machine. If your O/S has paravirtualisation support (which is still not a mature technology on Windows) you use paravirtualised I/O (essentially a device driver that hooks into an API in the VM). Recent versions of the Opteron have support for nested page tables, which removes the need to emulate the MMU in software (which is really slow). Thus, applications that run over large data sets and do lots of I/O like (say) ETL processes trip over the achilles heel of virtualisation. If you have anything like a data warehouse system that might be hard on memory or Disk I/O you should consider something else. For a simple transactional application they are probably O.K. Put in perspective the systems I am using are running on blades (an IBM server) on a SAN with 4x 2gbit F/C links. This is a mid-range SAN. The VM has 4GB of RAM IIRC and now two virtual CPUs. At its best (when the SAN is quiet) this is still only half of the speed of my XW9300 , which has 5 SCSI disks (system, tempdb, logs, data, data) on 1 U320 bus and 4GB of RAM. Your mileage may vary, but I'd recommend going with workstation systems like the one I described for developing anything I/O heavy in preference to virtual servers on a SAN. Unless your resource usage requirements are beyond this sort of kit (in which case they are well beyond a virtual server anyway) this is a much better solution. The hardware is not that expensive - certainly much cheaper than a SAN, blade chassis and VMWare licencing. SQL Server developer edition comes with V.S. Pro and above. This also has the benefit that your development team is forced to deal with deployment right from the word go - you have to come up with an architecture that's easy to 'one-click' deploy. This is not as hard as it sounds. Redgate SQL Compare Pro is your friend here. Your developers also get a basic working knowledge of database administration. A quick trip onto HP's website got me a list price of around $4,600 for an XW8600 (their current xeon-based model) with a quad-core xeon chip, 4GB of RAM and 1x146 and 4x73GB 15k SAS hard disks. Street price will probably be somewhat less. Compare this to the price for a SAN, blade chassis and VMware licensing and the cost of backup for that setup. For backup you can provide a network share with backup where people can drop compressed DB backup files as necessary. EDIT: This whitepaper on AMD's web-site discusses some benchmarks on a VM. From the benchmarks in the back, heavy I/O and MMU workload really clobber VM performance. Their benchmark (to be taken with a grain of salt as it is a vendor supplied statistic) suggests a 3.5x speed penalty on an OLTP benchmark. While this is vendor supplied one should bear in mind: It benchmarks naive virtualisationand compares it to apara-virtualised solution, notbare-metal performance. An OLTP benchmark will have a morerandom-access I/O workload, and willspend more time waiting for diskseeks. A more sequential diskaccess pattern (characteristic ofdata warehouse queries) will have ahigher penalty, and a memory-heavyoperation (SSAS, for example, is abiblical memory hog) that has alarge number of TLB misses will alsoincur additional penalties. Thismeans that the slow-downs on thistype of processing would probably bemore pronounced than the OLTPbenchmark penalty cited in the whitepaper. What we have seen here is that TLB misses and I/O are very expensive on a VM. A good architecture with paravirtualised drivers and hardware support in the MMU will mitigate some or all of this. However, I believe that Windows Server 2003 does not support paravirtualisation at all, and I'm not sure what level of support is delivered in Windows 2008 server. It has certainly been my experience that a VM will radically slow down a server when working on an ETL process and SSAS cube builds compared to relatively modest spec bare-metal hardware. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
149,336 | What are some practical uses for the " Curiously Recurring Template Pattern "? The " counted class " example commonly shown just isn't a convincing example to me. | Simulated dynamic binding .Avoiding the cost of virtual function calls while retaining some of the hierarchical benefits is an enormous win for the subsystems where it can be done in the project I am currently working on. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6386/"
]
} |
149,379 | I want to create Code39 encoded barcodes from my application. I know I can use a font for this, but I'd prefer not to as I'd have to register the font on the server and I've had some pretty bad experiences with that. An example of what I've produced after asking this question is in the answers | This is my current codebehind, with lots of comments: Option Explicit OnOption Strict OnImports System.DrawingImports System.Drawing.ImagingImports System.Drawing.BitmapImports System.Drawing.GraphicsImports System.IOPartial Public Class Barcode Inherits System.Web.UI.Page 'Sebastiaan Janssen - 20081001 - TINT-30584 'Most of the code is based on this example: 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/25/writing-code-39-barcodes-with-javascript.aspx-generation.aspx 'With a bit of this thrown in: 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode Private _encoding As Hashtable = New Hashtable Private Const _wideBarWidth As Short = 8 Private Const _narrowBarWidth As Short = 2 Private Const _barHeight As Short = 100 Sub BarcodeCode39() _encoding.Add("*", "bWbwBwBwb") _encoding.Add("-", "bWbwbwBwB") _encoding.Add("$", "bWbWbWbwb") _encoding.Add("%", "bwbWbWbWb") _encoding.Add(" ", "bWBwbwBwb") _encoding.Add(".", "BWbwbwBwb") _encoding.Add("/", "bWbWbwbWb") _encoding.Add("+", "bWbwbWbWb") _encoding.Add("0", "bwbWBwBwb") _encoding.Add("1", "BwbWbwbwB") _encoding.Add("2", "bwBWbwbwB") _encoding.Add("3", "BwBWbwbwb") _encoding.Add("4", "bwbWBwbwB") _encoding.Add("5", "BwbWBwbwb") _encoding.Add("6", "bwBWBwbwb") _encoding.Add("7", "bwbWbwBwB") _encoding.Add("8", "BwbWbwBwb") _encoding.Add("9", "bwBWbwBwb") _encoding.Add("A", "BwbwbWbwB") _encoding.Add("B", "bwBwbWbwB") _encoding.Add("C", "BwBwbWbwb") _encoding.Add("D", "bwbwBWbwB") _encoding.Add("E", "BwbwBWbwb") _encoding.Add("F", "bwBwBWbwb") _encoding.Add("G", "bwbwbWBwB") _encoding.Add("H", "BwbwbWBwb") _encoding.Add("I", "bwBwbWBwb") _encoding.Add("J", "bwbwBWBwb") _encoding.Add("K", "BwbwbwbWB") _encoding.Add("L", "bwBwbwbWB") _encoding.Add("M", "BwBwbwbWb") _encoding.Add("N", "bwbwBwbWB") _encoding.Add("O", "BwbwBwbWb") _encoding.Add("P", "bwBwBwbWb") _encoding.Add("Q", "bwbwbwBWB") _encoding.Add("R", "BwbwbwBWb") _encoding.Add("S", "bwBwbwBWb") _encoding.Add("T", "bwbwBwBWb") _encoding.Add("U", "BWbwbwbwB") _encoding.Add("V", "bWBwbwbwB") _encoding.Add("W", "BWBwbwbwb") _encoding.Add("X", "bWbwBwbwB") _encoding.Add("Y", "BWbwBwbwb") _encoding.Add("Z", "bWBwBwbwb") End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load BarcodeCode39() Dim barcode As String = String.Empty If Not IsNothing(Request("barcode")) AndAlso Not (Request("barcode").Length = 0) Then barcode = Request("barcode") Response.ContentType = "image/png" Response.AddHeader("Content-Disposition", String.Format("attachment; filename=barcode_{0}.png", barcode)) 'TODO: Depending on the length of the string, determine how wide the image will be GenerateBarcodeImage(250, 140, barcode).WriteTo(Response.OutputStream) End If End Sub Protected Function getBCSymbolColor(ByVal symbol As String) As System.Drawing.Brush getBCSymbolColor = Brushes.Black If symbol = "W" Or symbol = "w" Then getBCSymbolColor = Brushes.White End If End Function Protected Function getBCSymbolWidth(ByVal symbol As String) As Short getBCSymbolWidth = _narrowBarWidth If symbol = "B" Or symbol = "W" Then getBCSymbolWidth = _wideBarWidth End If End Function Protected Overridable Function GenerateBarcodeImage(ByVal imageWidth As Short, ByVal imageHeight As Short, ByVal Code As String) As MemoryStream 'create a new bitmap Dim b As New Bitmap(imageWidth, imageHeight, Imaging.PixelFormat.Format32bppArgb) 'create a canvas to paint on Dim canvas As New Rectangle(0, 0, imageWidth, imageHeight) 'draw a white background Dim g As Graphics = Graphics.FromImage(b) g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight) 'write the unaltered code at the bottom 'TODO: truely center this text Dim textBrush As New SolidBrush(Color.Black) g.DrawString(Code, New Font("Courier New", 12), textBrush, 100, 110) 'Code has to be surrounded by asterisks to make it a valid Code39 barcode Dim UseCode As String = String.Format("{0}{1}{0}", "*", Code) 'Start drawing at 10, 10 Dim XPosition As Short = 10 Dim YPosition As Short = 10 Dim invalidCharacter As Boolean = False Dim CurrentSymbol As String = String.Empty For j As Short = 0 To CShort(UseCode.Length - 1) CurrentSymbol = UseCode.Substring(j, 1) 'check if symbol can be used If Not IsNothing(_encoding(CurrentSymbol)) Then Dim EncodedSymbol As String = _encoding(CurrentSymbol).ToString For i As Short = 0 To CShort(EncodedSymbol.Length - 1) Dim CurrentCode As String = EncodedSymbol.Substring(i, 1) g.FillRectangle(getBCSymbolColor(CurrentCode), XPosition, YPosition, getBCSymbolWidth(CurrentCode), _barHeight) XPosition = XPosition + getBCSymbolWidth(CurrentCode) Next 'After each written full symbol we need a whitespace (narrow width) g.FillRectangle(getBCSymbolColor("w"), XPosition, YPosition, getBCSymbolWidth("w"), _barHeight) XPosition = XPosition + getBCSymbolWidth("w") Else invalidCharacter = True End If Next 'errorhandling when an invalidcharacter is found If invalidCharacter Then g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight) g.DrawString("Invalid characters found,", New Font("Courier New", 8), textBrush, 0, 0) g.DrawString("no barcode generated", New Font("Courier New", 8), textBrush, 0, 10) g.DrawString("Input was: ", New Font("Courier New", 8), textBrush, 0, 30) g.DrawString(Code, New Font("Courier New", 8), textBrush, 0, 40) End If 'write the image into a memorystream Dim ms As New MemoryStream Dim encodingParams As New EncoderParameters encodingParams.Param(0) = New EncoderParameter(Encoder.Quality, 100) Dim encodingInfo As ImageCodecInfo = FindCodecInfo("PNG") b.Save(ms, encodingInfo, encodingParams) 'dispose of the object we won't need any more g.Dispose() b.Dispose() Return ms End Function Protected Overridable Function FindCodecInfo(ByVal codec As String) As ImageCodecInfo Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders For Each e As ImageCodecInfo In encoders If e.FormatDescription.Equals(codec) Then Return e Next Return Nothing End FunctionEnd Class | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018/"
]
} |
149,380 | This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern RDBMS solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end. I speak of dynamic sorting. In my fantasy world, it should be as simple as something like: ORDER BY @sortCol1, @sortCol2 This is the canonical example given by newbie SQL and Stored Procedure developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an ORDER BY clause. I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are very good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice. Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really really easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me. But this brings back the point that it isn't possible — or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication." The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack. We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default): DECLARE @sortCol1 AS varchar(20)DECLARE @sortCol2 AS varchar(20)DECLARE @dir1 AS varchar(20)DECLARE @dir2 AS varchar(20)DECLARE @col1 AS varchar(20)DECLARE @col2 AS varchar(20)SET @col1 = 'storagedatetime';SET @col2 = 'vehicleid';IF @sort = 1 -- Default sort.BEGIN SET @sortCol1 = @col1; SET @dir1 = 'asc'; SET @sortCol2 = @col2; SET @dir2 = 'asc';ENDELSE IF @sort = 2 -- Reversed order default sort.BEGIN SET @sortCol1 = @col1; SET @dir1 = 'desc'; SET @sortCol2 = @col2; SET @dir2 = 'desc';END You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause: ORDER BY CASE @dir1 WHEN 'desc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir1 WHEN 'asc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END, CASE @dir2 WHEN 'desc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir2 WHEN 'asc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick. The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following: ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble." Yet it did work. My question is then: is there a better way? I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET? And thank you for reading (or at least skimming) such a long question! PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, AND try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them. Update: I would like to avoid dynamic SQL . Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that — like I'm still living in the Classic ASP world. A lot of the reason we want stored procedures in the first place is for security . I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :) | Yeah, it's a pain, and the way you're doing it looks similar to what I do: order bycase when @SortExpr = 'CustomerName' and @SortDir = 'ASC' then CustomerName end asc, case when @SortExpr = 'CustomerName' and @SortDir = 'DESC' then CustomerName end desc,... This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs. What I do from code is refactor the paging and sorting so I at least don't have a lot of repetition there with populating values for @SortExpr and @SortDir . As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it's at least neat and recognizable when you go in to make changes. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/149380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290/"
]
} |
149,395 | We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on Windows. | FreeTDS + unixODBC or iODBC Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine. unixODBC has isql, iODBC has iodbctest You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL) I'm personally using FreeTDS + iODBC: $more /etc/freetds/freetds.conf[10.0.1.251] host = 10.0.1.251 port = 1433 tds version = 8.0$ more /etc/odbc.ini[ACCT]Driver = /usr/local/freetds/lib/libtdsodbc.soDescription = ODBC to SQLServer via FreeTDSTrace = NoServername = 10.0.1.251Database = accounts_ver8 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
]
} |
149,421 | How does Stackoverflow implement the resizable textarea? Is that something they rolled themselves or is it a publicly available component that I can easily attach to textareas on my sites? I found this question and it doesn't quite do what I want. autosizing-textarea That talks more about automatically resizing textareas whereas I want the little grab-area that you can drag up and down. | StackOverflow uses a jQuery plugin to accomplish this: TextAreaResizer . It's easy enough to verify this - just pull the JS files from the site. Historical note: when this answer was originally written, WMD and TextAreaResizer were two separate plugins, neither one of which was authored by the SO Dev Team (see also: micahwittman's answer ). Also, the JavaScript for the site was quite easy to read... None of these are strictly true anymore, but TextAreaResizer still works just fine. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
} |
149,479 | Well, it seems simple enough, but I can't find a way to add a caption to an equation.The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great. | The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example: \begin{figure}\[ E = m c^2 \]\caption{A famous equation}\end{figure} The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this: \[ E = m c^2 \]\captionof{figure}{A famous equation} This will also produce an entry for the \listoffigures , if your document has one. To align parts of an equation, take a look at the eqnarray environment , or some of the environments of the amsmath package: align, gather, multiline,... | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/149479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
]
} |
149,491 | I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower CamelCasing . They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties: string firstName;public string FirstName {...} But they are used to this: string _firstname;public string firstName {...} I try to keep up with their "standard" so the code looks the same but I just don't like it. I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.: System.Console.WriteLine("string") What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything. Update: I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.) | I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is consistently using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14533/"
]
} |
149,500 | What does the following code do in C/C++? if (blah(), 5) { //do something} | Comma operator is applied and the value 5 is used to determine the conditional's true/false. It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression. Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/149500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630/"
]
} |
149,570 | Has anyone ever done work to get Ruby to do continuations (like Seaside on Smalltalk)? | Yes, in most cases. MRI (1.8) have supported them as far as my memory reaches, Ruby 1.9 (YARV) does it, too , so does Rubinius. JRuby and IronRuby don't have continuations, and it's quite unlikely they will get them (JVM and CLR use stack-instrospection for security) Ruby as a language supports continuations via callcc keyword. They're used, for example, to implement Generator class from standard library. continuations on ruby-doc Continuation-based web frameworks (like seaside, or one from Arc's std. library) seem less popular. I've found wee that claim to let you do optional continuations, but I've never used it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23513/"
]
} |
149,573 | Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected. (The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :) | While I'm not sure about exactly what you want to accomplish, this bit of code worked for me. <select id="mySelect" multiple="multiple"> <option value="1">First</option> <option value="2">Second</option> <option value="3">Third</option> <option value="4">Fourth</option></select><script type="text/javascript"> $(document).ready(function() { if (!$("#mySelect option:selected").length) { $("#mySelect option[value='3']").attr('selected', 'selected'); }});</script> | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/149573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
]
} |
149,600 | Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too. | PHP Code Beautifier is a useful free tool that should do what you're after, although their download page does require an account to be created. The tool has been declined into 3 versions: A GUI version which allow to process file visually. A command line version which allow to be batched or integrated with other tools (CVS, SubVersion, IDE ...). As an integrated tool of PHPEdit. Basically, it'll turn: if($code == BAD){$action = REWRITE;}else{$action = KEEP;}for($i=0; $i<10;$i++){while($j>0){$j++;doCall($i+$j);if($k){$k/=10;}}} into if ($code == BAD) { $action = REWRITE;} else { $action = KEEP;}for($i = 0; $i < 10;$i++) { while ($j > 0) { $j++; doCall($i + $j); if ($k) { $k /= 10; } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
]
} |
149,609 | Does the using catch the exception or throw it? i.e. using (StreamReader rdr = File.OpenText("file.txt")){ //do stuff} If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it? | using statements do not eat exceptions. All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block. There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
]
} |
149,617 | Let's assume that I have some packets with a 16-bit checksum at the end. I would like to guess which checksum algorithm is used. For a start, from dump data I can see that one byte change in the packet's payload totally changes the checksum, so I can assume that it isn't some kind of simple XOR or sum. Then I tried several variations of CRC16 , but without much luck. This question might be more biased towards cryptography, but I'm really interested in any easy to understand statistical tools to find out which CRC this might be. I might even turn to drawing different CRC algorithms if everything else fails. Backgroud story: I have serial RFID protocol with some kind of checksum. I can replay messages without problem, and interpret results (without checksum check), but I can't send modified packets because device drops them on the floor. Using existing software, I can change payload of RFID chip. However, unique serial number is immutable, so I don't have ability to check every possible combination. Allthough I could generate dumps of values incrementing by one, but not enough to make exhaustive search applicable to this problem. dump files with data are available if question itself isn't enough :-) Need reference documentation? A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS is great reference which I found after asking question here. In the end, after very helpful hint in accepted answer than it's CCITT, I used this CRC calculator , and xored generated checksum with known checksum to get 0xffff which led me to conclusion that final xor is 0xffff instread of CCITT's 0x0000. | There are a number of variables to consider for a CRC: PolynomialNo of bits (16 or 32)Normal (LSB first) or Reverse (MSB first)Initial valueHow the final value is manipulated (e.g. subtracted from 0xffff), or is a constant value Typical CRCs: LRC: Polynomial=0x81; 8 bits; Normal; Initial=0; Final=as calculatedCRC16: Polynomial=0xa001; 16 bits; Normal; Initial=0; Final=as calculatedCCITT: Polynomial=0x1021; 16 bits; reverse; Initial=0xffff; Final=0x1d0fXmodem: Polynomial=0x1021; 16 bits; reverse; Initial=0; Final=0x1d0fCRC32: Polynomial=0xebd88320; 32 bits; Normal; Initial=0xffffffff; Final=inverted valueZIP32: Polynomial=0x04c11db7; 32 bits; Normal; Initial=0xffffffff; Final=as calculated The first thing to do is to get some samples by changing say the last byte. This will assist you to figure out the number of bytes in the CRC. Is this a "homemade" algorithm. In this case it may take some time. Otherwise try the standard algorithms. Try changing either the msb or the lsb of the last byte, and see how this changes the CRC. This will give an indication of the direction. To make it more difficult, there are implementations that manipulate the CRC so that it will not affect the communications medium (protocol). From your comment about RFID, it implies that the CRC is communications related. Usually CRC16 is used for communications, though CCITT is also used on some systems. On the other hand, if this is UHF RFID tagging, then there are a few CRC schemes - a 5 bit one and some 16 bit ones. These are documented in the ISO standards and the IPX data sheets. IPX: Polynomial=0x8005; 16 bits; Reverse; Initial=0xffff; Final=as calculatedISO 18000-6B: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculatedISO 18000-6C: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated Data must be padded with zeroes to make a multiple of 8 bitsISO CRC5: Polynomial=custom; 5 bits; Reverse; Initial=0x9; Final=shifted left by 3 bits Data must be padded with zeroes to make a multiple of 8 bitsEPC class 1: Polynomial=custom 0x1021; 16 bits; Reverse; Initial=0xffff; Final=post processing of 16 zero bits Here is your answer!!!! Having worked through your logs, the CRC is the CCITT one. The first byte 0xd6 is excluded from the CRC. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1081/"
]
} |
149,646 | In the Apple documentation for NSRunLoop there is sample code demonstrating suspending execution while waiting for a flag to be set by something else. BOOL shouldKeepRunning = YES; // globalNSRunLoop *theRL = [NSRunLoop currentRunLoop];while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a NSLog on the line after the flag is being set (in another method) and then a line after the while() there is a seemingly random wait between the two log statements of several seconds. The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds. I have worked around this issue with the following code but it does not seem right that the original code doesn't work. NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];while (webViewIsLoading && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil]) loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1]; using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart. Anyone any ideas why the original code exhibits this behaviour? | Runloops can be a bit of a magic box where stuff just happens. Basically you're telling the runloop to go process some events and then return. OR return if it doesn't process any events before the timeout is hit. With 0.1 second timeout, you're htting the timeout more often than not. The runloop fires, doesn't process any events and returns in 0.1 of second. Occasionally it'll get a chance to process an event. With your distantFuture timeout, the runloop will wait foreever until it processes an event. So when it returns to you, it has just processed an event of some kind. A short timeout value will consume considerably more CPU than the infinite timeout but there are good reasons for using a short timeout, for example if you want to terminate the process/thread the runloop is running in. You'll probably want the runloop to notice that a flag has changed and that it needs to bail out ASAP. You might want to play around with runloop observers so you can see exactly what the runloop is doing. See this Apple doc for more information. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496/"
]
} |
149,690 | I am trying to extract a certain part of a column that is between delimiters. e.g. find foo in the following test 'esf :foo: bar So in the above I'd want to return foo, but all the regexp functions only return true|false,is there a way to do this in MySQL | Here ya go, bud: SELECT SUBSTR(column, LOCATE(':',column)+1, (CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column))) FROM table Yea, no clue why you're doing this, but this will do the trick. By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)). With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR_LENGTH ( don't use LENGTH() for this ), we can use a little math to discover the length of the string between the two instances of ':'. This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'. Again, it's gross, but to each his own. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
149,718 | I have several .NET Windows Forms applications that I'm preparing to convert into a ClickOnce /smart-client deployment scenario. I've read the isn't-this-great tutorials, but are there pitfalls or "gotchas" that I should be aware of? There are several minor applications used off and on, but the main application is in C#, runs 24/7, is quite large, but only changes every few weeks. It also writes to a log file locallly and talks to local hardware devices. | Here are a few that I am aware of. Can't put an icon on the desktop. You can now. I can't install for all users. I need to jump through hoops to move the deployment to a different server. It is not a problem if you are developing internally, and the users can see the server that you are publishing to or if you are deploying to the public web, but it is not great if you need to roll out to multiple customer sites independently. Since .NET 3.5 SP1 you do not need to sign the deployment manifest anymore which makes it much easier to move deployments to new servers. I can't install assemblies in the GAC . You can get around this by creating regular install packages that are pre-requisites of the ClickOnce application. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9345/"
]
} |
149,763 | I'm benchmarking a WPF application on various platforms and I need an easy way to determine if WPF is using hardware or software rendering. I seem to recall a call to determine this, but can't lay my hands on it right now. Also, is there an easy, code based way to force one rendering pipeline over the other? | Check RenderCapability.Tier Graphics Rendering Tiers RenderCapability Class [ UPDATE ] RenderCapability.IsPixelShaderVersionSupported - Gets a value that indicates whether the specified pixel shader version is supported. RenderCapability.IsShaderEffectSoftwareRenderingSupported - Gets a value that indicates whether the system can render bitmap effects in software. RenderCapability.Tier - Gets a value that indicates the rendering tier for the current thread. RenderCapability.TierChanged - Occurs when the rendering tier has changed for the Dispatcher object of the current thread. RenderCapability.Tier >> 16 Rendering Tier 0 - No graphics hardware acceleration. The DirectX version level is less than version 7.0. Rendering Tier 1 - Partial graphics hardware acceleration. The DirectX version level is greater than or equal to version 7.0, and lesser than version 9.0. Rendering Tier 2 - Most graphics features use graphics hardware acceleration. The DirectX version level is greater than or equal to version 9.0. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10119/"
]
} |
149,772 | Basically the question is how to get from this: foo_id foo_name1 A1 B2 C to this: foo_id foo_name1 A B2 C | SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id; https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat From the link above, GROUP_CONCAT : This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/149772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
]
} |
149,784 | This question comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this: insert into MyTable select * from MyTable where uniqueId = @Id; I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field). I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is. | Try this: insert into MyTable(field1, field2, id_backup) select field1, field2, uniqueId from MyTable where uniqueId = @Id; Any fields not specified should receive their default value (which is usually NULL when not defined). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/149784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
]
} |
149,821 | I have the following function that is pulling data from a database. The ajax call is working correctly. How can I send the tab delimited data in my success function to the user? Setting the contect type to "application/vnd.ms-excel" didn't work. The alert on success shows the correctly formatted data. function SendToExcel() { $.ajax({ type: "GET", url: "/Search.aspx", contentType: "application/vnd.ms-excel", dataType: "text", data: "{id: '" + "asdf" + "'}", success: function(data) { alert(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); }}); } I don't want to display the data in the browser--I want to send it to Excel. EDIT: I found a way to do what I wanted. Instead of redirecting the users to a new page that would prompt them to save/open an Excel file, I opened the page inside a hidden iframe. That way, the users click a button, and they are prompted to save/open an Excel file. No page redirection. Is it Ajax? No, but it solves the real problem I had. Here's the function I'm calling on the button click: function SendToExcel() { var dataString = 'type=excel' + '&Number=' + $('#txtNumber').val() + '&Reference=' + $('#txtReference').val() $("#sltCTPick option").each(function (i) { dataString = dataString + '&Columns=' + this.value; }); top.iExcelHelper.location.href = "/Reports/JobSearchResults.aspx?" + dataString;; } | AJAX is... the wrong choice. Redirect the user to a server resource that will send the data down with the proper MIME type, and let the browser figure out what to do with it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
]
} |
149,825 | I ran across the following code in Ely Greenfield's SuperImage from his Book component - I understand loader.load() but what does the rest of do? loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource)); It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement? | ? is called the 'ternary operator' and it's basic use is: (expression) ? (evaluate to this if expression is true) : (evaluate to this otherwise); In this case, if newSource is a URLRequest, loader.load will be passed newSource directly, otherwise it will be passed a new URLRequest built from newSource. The ternary operator is frequently used as a more concise form of if statement as it allows ifs to be inlined. The corresponding code in this case would be: if (newSource is URLRequest) loader.load(newSource);else loader.load(new URLRequest(newSource)); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
]
} |
149,848 | What is a strong way to protect against sql injection for a classic asp app? FYI I am using it with an access DB. (I didnt write the app) | Stored Procedures and/or prepared statements: https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes? Catching SQL Injection and other Malicious Web Requests With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway. Here's a link to the technique in Access: http://www.asp101.com/samples/storedqueries.asp Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic. Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code. Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place. In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target: Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ; Remember that your database needs to defend its own perimeter, and if various logins have rights to INSERT/UPDATE/DELETE in tables, any code in those applications (or compromised applications) can be a potential problem. If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior. (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23528/"
]
} |
149,860 | I have a popen() function which executes tail -f sometextfile . Aslong as there is data in the filestream obviously I can get the data through fgets() . Now, if no new data comes from tail, fgets() hangs. I tried ferror() and feof() to no avail. How can I make sure fgets() doesn't try to read data when nothing new is in the file stream? One of the suggestion was select() . Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see this post ). | In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking. #include <fcntl.h>FILE *proc = popen("tail -f /tmp/test.txt", "r");int fd = fileno(proc);int flags;flags = fcntl(fd, F_GETFL, 0);flags |= O_NONBLOCK;fcntl(fd, F_SETFL, flags); If there is no input available, fgets will return NULL with errno set to EWOULDBLOCK. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10010/"
]
} |
149,932 | It's helpful to name threads so one can sort out which threads are doing what for diagnostic and debugging purposes. Is there a particular naming convention for threads in a heavily multi-threaded application that works better than another? Any guidelines? What kind of information should go into the name for a thread? What have you learned about naming your threads that could be helpful to others? | There's to my knowledge no standard. Over the time I've found these guidelines to be helpful: Use short names because they don't make the lines in a log file too long. Create names where the important part is at the beginning. Log viewers in a graphical user interface tend to have tables with columns, and the thread column is usually small or will be made small by you to read everything else. Do not use the word "thread" in the thread name because it is obvious. make the thread names easily grep-able. Avoid similar sounding thread names if you have several threads of the same nature, enumerate them with IDs that are unique to one execution of the application or one log file, whichever fits your logging habits. avoid generalizations like "WorkerThread" (how do you name the next 5 worker threads?), "GUIThread" (which GUI? is it for one window? for everything?) or "Calculation" (what does it calculate?). if you have a test group that uses thread names to grep your application's log files, do not rename your threads after some time. Your testers will hate you for doing so. Thread names in well-tested applications should be there to stay. when you have threads that service a network connection, try to include the target network address in the thread name (e.g. channel_123.212.123.3). Don't forget about enumeration though if there are multiple connections to the same host. If you have many threads and forgot to name one, your log mechanism should output a unique thread ID instead (API-specific, e.g. by calling pthread_self() ) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/149932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
]
} |
149,937 | Is there a way to deploy a Java program in a format that is not reverse-engineerable? I know how to convert my application into an executable JAR file, but I want to make sure that the code cannot be reverse engineered, or at least, not easily. Obfuscation of the source code doesn't count... it makes it harder to understand the code, but does not hide it. A related question is How to lock compiled Java classes to prevent decompilation? Once I've completed the program, I would still have access to the original source, so maintaining the application would not be the problem. If the application is distributed, I would not want any of the users to be able to decompile it. Obfuscation does not achieve this as the users would still be able to decompile it, and while they would have difficulty following the action flows, they would be able to see the code, and potentially take information out of it. What I'm concerned about is if there is any information in the code relating to remote access. There is a host to which the application connects using a user-id and password provided by the user. Is there a way to hide the host's address from the user, if that address is located inside the source code? | You could obfuscate your JAR file with YGuard . It doesn't obfuscate your source code , but the compiled classes, so there is no problem about maintaining the code later. If you want to hide some string, you could encrypt it, making it harder to get it through looking at the source code (it is even better if you obfuscate the JAR file). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23249/"
]
} |
149,962 | I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this? | Adding "return false;" to the onclick attribute of the button will prevent the automatic postback. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/149962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
]
} |
150,014 | On the .Net WebBrowser control the only way I can see to load a page to it is to set the URL property. But I would like to instead give it some HTML code that I already have in memory without writing it out to a file first. Is there any way to do this? Or are there any controls that will do this? | You want the DocumentText Property: http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documenttext.aspx ? from http://www.codeguru.com/forum/showpost.php?p=1691329&postcount=9 :Also you should provide a couple things: Don't set DocumentText in the constructor. Use Form_Load or your own method.If you set DocumentText in the constructor, you will not be able to set it again anywhere in the application. Be sure to check that the Form Designer hasn't set it either. You can only set DocumentText once per method call. This is odd and most likely a bug, but it's true.For example: setting DocumentText in a for-loop will only set properly on the first iteration of the loop.You can however, create a small method to set DocumentText to the passed in string, then call this method in a for-loop. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
]
} |
150,033 | What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. | This should do it: [^\x00-\x7F]+ It matches any character which is not contained in the ASCII character set (0-127, i.e. 0x0 to 0x7F). You can do the same thing with Unicode: [^\u0000-\u007F]+ For unicode you can look at this 2 resources: Code charts list of Unicode ranges This tool to create a regex filtered by Unicode block. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/150033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
]
} |
150,053 | How can I limit my post-build events to running only for one type of build? I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode. | Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName) . For instance if $(ConfigurationName) == Debug xcopy something somewhere | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/150053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3615/"
]
} |
150,058 | mysql5.0 with a pair of databases "A" and "B", both with large innodb tables. "drop database A;" freezes database "B" for a couple minutes. Nothing is using "A" at that point, so why is this such an intensive operation? Bonus points: Given that we use "A", upload data into "B", and then switch to using "B", how can we do this faster? Dropping databases isn't the sort of thing one typically has to do all the time, so this is a bit off the charts. | So I'm not sure Matt Rogish's answer is going to help 100%. The problem is that MySQL* has a mutex (mutually exclusive lock) around opening and closing tables, so that basically means that if a table is in the process of being closed/deleted, no other tables can be opened. This is described by a colleague of mine here: http://www.mysqlperformanceblog.com/2009/06/16/slow-drop-table/ One excellent impact reduction strategy is to use a filesystem like XFS. The workaround is ugly. You essentially have to nibble away at all the data in the tables before dropping them (see comment #11 on the link above). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12332/"
]
} |
150,076 | I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response? require 'rubygems'require 'activeresource'class Event < ActiveResource::Base self.site = "http://localhost:3000"ende = Event.create( :name => "Shortest Event Ever!", :starts_at => 1.second.ago, :capacity => 25, :price => 10.00)e.destroy | So I'm not sure Matt Rogish's answer is going to help 100%. The problem is that MySQL* has a mutex (mutually exclusive lock) around opening and closing tables, so that basically means that if a table is in the process of being closed/deleted, no other tables can be opened. This is described by a colleague of mine here: http://www.mysqlperformanceblog.com/2009/06/16/slow-drop-table/ One excellent impact reduction strategy is to use a filesystem like XFS. The workaround is ugly. You essentially have to nibble away at all the data in the tables before dropping them (see comment #11 on the link above). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219658/"
]
} |
150,095 | I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example: foo = "0.0.0.0"goo = "here is some other stuff 0.0.0.0" if goo =~ /value of foo here dynamically/ puts "success!"end | Same as string insertion. if goo =~ /#{Regexp.quote(foo)}/#... | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/150095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
} |
150,113 | An older application using System.Web.Mail is throwing an exception on emails coming from [email protected] . Other addresses appear to be working correctly. We changed our mail server to Exchange 2007 when the errors started, so I assume that is where the problem is. Does anyone know what is happening? Here is the exception and stack trace: System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040212): The transport lost its connection to the server. --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) --- End of inner exception stack trace --- at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) at System.Web.Mail.CdoSysHelper.Send(MailMessage message) at System.Web.Mail.SmtpMail.Send(MailMessage message) at ProcessEmail.Main() | Same as string insertion. if goo =~ /#{Regexp.quote(foo)}/#... | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/150113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17287/"
]
} |
150,114 | I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this. Which of these offers the best performance in which situations? Parse(...) // Crash if the case is extremely rare .0001%If (SomethingIsValid) // Check the value before parsing Parse(...)TryParse(...) // Using TryParsetry{ Parse(...)}catch{ // Catch any thrown exceptions} | Always use T.TryParse(string str, out T value) . Throwing exceptions is expensive and should be avoided if you can handle the situation a priori . Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil . Yet we should not pass up our opportunities in that critical 3%" -Donald Knuth Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is worse and that the performance of TryParse is better . Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse. (edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested) Times for various failure rates on 10,000 inputs from the user (for the unbelievers): Failure Rate Try-Catch TryParse Slowdown 0% 00:00:00.0131758 00:00:00.0120421 0.1 10% 00:00:00.1540251 00:00:00.0087699 16.6 20% 00:00:00.2833266 00:00:00.0105229 25.9 30% 00:00:00.4462866 00:00:00.0091487 47.8 40% 00:00:00.6951060 00:00:00.0108980 62.8 50% 00:00:00.7567745 00:00:00.0087065 85.9 60% 00:00:00.7090449 00:00:00.0083365 84.1 70% 00:00:00.8179365 00:00:00.0088809 91.1 80% 00:00:00.9468898 00:00:00.0088562 105.9 90% 00:00:01.0411393 00:00:00.0081040 127.5100% 00:00:01.1488157 00:00:00.0078877 144.6/// <param name="errorRate">Rate of errors in user input</param>/// <returns>Total time taken</returns>public static TimeSpan TimeTryCatch(double errorRate, int seed, int count){ Stopwatch stopwatch = new Stopwatch(); Random random = new Random(seed); string bad_prefix = @"X"; stopwatch.Start(); for(int ii = 0; ii < count; ++ii) { string input = random.Next().ToString(); if (random.NextDouble() < errorRate) { input = bad_prefix + input; } int value = 0; try { value = Int32.Parse(input); } catch(FormatException) { value = -1; // we would do something here with a logger perhaps } } stopwatch.Stop(); return stopwatch.Elapsed;}/// <param name="errorRate">Rate of errors in user input</param>/// <returns>Total time taken</returns>public static TimeSpan TimeTryParse(double errorRate, int seed, int count){ Stopwatch stopwatch = new Stopwatch(); Random random = new Random(seed); string bad_prefix = @"X"; stopwatch.Start(); for(int ii = 0; ii < count; ++ii) { string input = random.Next().ToString(); if (random.NextDouble() < errorRate) { input = bad_prefix + input; } int value = 0; if (!Int32.TryParse(input, out value)) { value = -1; // we would do something here with a logger perhaps } } stopwatch.Stop(); return stopwatch.Elapsed;}public static void TimeStringParse(){ double errorRate = 0.1; // 10% of the time our users mess up int count = 10000; // 10000 entries by a user TimeSpan trycatch = TimeTryCatch(errorRate, 1, count); TimeSpan tryparse = TimeTryParse(errorRate, 1, count); Console.WriteLine("trycatch: {0}", trycatch); Console.WriteLine("tryparse: {0}", tryparse);} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/150114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22381/"
]
} |
150,129 | Could someone provide a good description of what a Lambda is? We have a tag for them and they're on the secrets of C# question, but I have yet to find a good definition and explanation of what they are in the first place. | Closures, lambdas, and anonymous functions are not necessarily the same thing. An anonymous function is any function that doesn't have (or, at least, need) its own name. A closure is a function that can access variables that were in its lexical scope when it was declared, even after they have fallen out of scope. Anonymous functions do not necessarily have to be closures, but they are in most languages and become rather less useful when they aren't. A lambda is.. not quite so well defined as far as computer science goes. A lot of languages don't even use the term; instead they will just call them closures or anon functions or invent their own terminology. In LISP, a lambda is just an anonymous function. In Python, a lambda is an anonymous function specifically limited to a single expression; anything more, and you need a named function. Lambdas are closures in both languages. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/150129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177/"
]
} |
150,161 | I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers. EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues. function Pause-Host{ param( $Delay = 1 ) $counter = 0; While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay)) { [Threading.Thread]::Sleep(1000) }} | Found something here : $counter = 0while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600)){ [Threading.Thread]::Sleep( 1000 )} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358/"
]
} |
150,167 | How do I list and export a private key from a keystore? | You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use keytool to convert to the standard format. Make sure you use the same password for both files (private key password, not the keystore password) or you will get odd failures later on in the second step. keytool -importkeystore -srckeystore keystore.jks \ -destkeystore intermediate.p12 -deststoretype PKCS12 Next, use OpenSSL to do the extraction to PEM: openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes You should be able to handle that PEM file easily enough; it's plain text with an encoded unencrypted private key and certificate(s) inside it (in a pretty obvious format). When you do this, take care to keep the files created secure. They contain secret credentials. Nothing will warn you if you fail to secure them correctly. The easiest method for securing them is to do all of this in a directory which doesn't have any access rights for anyone other than the user. And never put your password on the command line or in environment variables; it's too easy for other users to grab. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/150167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
]
} |
150,191 | I'm way buried in many nested levels of css, and I can't tell which style layer/level is messing up my display. How can I find out everything that's being applied to a particular element? | Click Inspect (upper left) to select the element you want to check then on the right panel select the tab labeled "Style". It will also tell you from which .css file that particular property comes from | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386/"
]
} |
150,192 | Even nowadays I often see underscores in Java variables and methods. An example are member variables (like "m_count" or "_count"). As far as I remember, to use underscores in these cases is called bad style by Sun . The only place they should be used is in constants (like in "public final static int IS_OKAY = 1;"), because constants should be all upper case and not camel case . Here, the underscore should make the code more readable. Do you think using underscores in Java is bad style? If so (or not), why? | If you have no code using it now, I'd suggest continuing that. If your codebase uses it, continue that. The biggest thing about coding style is consistency . If you have nothing to be consistent with, then the language vendor's recommendations are likely a good place to start. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/150192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13209/"
]
} |
150,208 | Is there a free third-party or .NET class that will convert HTML to RTF (for use in a rich-text enabled Windows Forms control)? The "free" requirement comes from the fact that I'm only working on a prototype and can just load the BrowserControl and just render HTML if need be (even if it is slow) and that Developer Express is going to be releasing their own such control soon-ish. I don't want to learn to write RTF by hand, and I already know HTML, so I figure this is the quickest way to get some demonstrable code out the door quickly. | Actually there is a simple and free solution: use your browser, ok this is the trick I used: var webBrowser = new WebBrowser();webBrowser.CreateControl(); // only if neededwebBrowser.DocumentText = *yourhtmlstring*;while (_webBrowser.DocumentText != *yourhtmlstring*) Application.DoEvents();webBrowser.Document.ExecCommand("SelectAll", false, null);webBrowser.Document.ExecCommand("Copy", false, null);*yourRichTextControl*.Paste(); This could be slower than other methods but at least it's free and works! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
]
} |
150,284 | I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both? | The docs say that If provided, at pickling time __reduce__() will be called with noarguments, and it must return either astring or a tuple. On the other hand, It is sometimes useful to know theprotocol version when implementing __reduce__ . This can be done byimplementing a method named __reduce_ex__ instead of __reduce__ . __reduce_ex__ , when itexists, is called in preference over __reduce__ (you may still provide __reduce__ for backwardscompatibility). The __reduce_ex__ method will be called with a singleinteger argument, the protocolversion. On the gripping hand, Guido says that this is an area that could be cleaned up. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
]
} |
150,294 | I'd like my program to read the cache line size of the CPU it's running on in C++. I know that this can't be done portably, so I will need a solution for Linux and another for Windows (Solutions for other systems could be usefull to others, so post them if you know them). For Linux I could read the content of /proc/cpuinfo and parse the line begining with cache_alignment. Maybe there is a better way involving a call to an API. For Windows I simply have no idea. | On Win32, GetLogicalProcessorInformation will give you back a SYSTEM_LOGICAL_PROCESSOR_INFORMATION which contains a CACHE_DESCRIPTOR , which has the information you need. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5861/"
]
} |
150,332 | If I have variable of type IEnumerable<List<string>> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an IEnumerable<string> ? | SelectMany - i.e. IEnumerable<List<string>> someList = ...; IEnumerable<string> all = someList.SelectMany(x => x); For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>. These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified): static IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { foreach(TSource item in source) { foreach(TResult result in selector(item)) { yield return result; } }} Although that is simplified somewhat. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
150,333 | We need to remotely create an Exchange 2007 distribution list from Asp.Net. Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company. Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API. It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work. Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break. Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange? | SelectMany - i.e. IEnumerable<List<string>> someList = ...; IEnumerable<string> all = someList.SelectMany(x => x); For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>. These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified): static IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { foreach(TSource item in source) { foreach(TResult result in selector(item)) { yield return result; } }} Although that is simplified somewhat. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23583/"
]
} |
150,339 | I am about to add a section to an ASP.NET app (VB.NET codebehind) that will allow a user to get data returned to them as an Excel file, which I will generate based on database data. While there are several ways of doing this, each has its own drawbacks. How would you return the data? I'm looking for something that's as clean and straightforward as possible. | CSV Pros: Simple Cons: It may not work in other locales or in different Excel configurations (i.e. List separator) Can't apply formatting, formulas, etc HTML Pros: Still pretty Simple Supports simple formating and formulas Cons: You have to name the file as xls and Excel may warn you about opening a non native Excel file One worksheet per workbook OpenXML (Office 2007 .XLSX) Pros: Native Excel format Supports all Excel features Do not require an install copy of Excel Can generate Pivot tables Can be generated using open source project EPPlus Cons: Limited compatibility outside Excel 2007 (shouldn't be a problem nowadays) Complicated unless you're using a third party component SpreadSheetML (open format XML) Pros: Simple compared to native Excel formats Supports most Excel features: formating, styles, formulas, multiple sheets per workbook Excel does not need to be installed to use it No third party libraries needed - just write out your xml Documents can be opened by Excel XP/2003/2007 Cons: Lack of good documentation Not supported in older versions of Excel (pre-2000) Write-only, in that once you open it and make changes from Excel it's converted to native Excel. XLS (generated by third party component) Pros: Generate native Excel file with all the formating, formulas, etc. Cons: Cost money Add dependencies COM Interop Pros: Uses native Microsoft libraries Read support for native documents Cons: Very slow Dependency/version matching issues Concurrency/data integrity issues for web use when reading Very slow Scaling issues for web use (different from concurrency): need to create many instances of heavy Excel app on the server Requires Windows Did I mention that it's slow? | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/150339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18009/"
]
} |
150,341 | How do people approach mocking out TcpClient (or things like TcpClient)? I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this? | When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the Adapter design pattern. In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this: public interface ITcpClient{ Stream GetStream(); // Anything you need here }public class TcpClientAdapter: ITcpClient{ private TcpClient wrappedClient; public TcpClientAdapter(TcpClient client) { wrappedClient = client; } public Stream GetStream() { return wrappedClient.GetStream(); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285/"
]
} |
150,355 | Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)? | C++11 #include <thread>//may return 0 when not able to detectconst auto processor_count = std::thread::hardware_concurrency(); Reference: std::thread::hardware_concurrency In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef lines): Win32 SYSTEM_INFO sysinfo;GetSystemInfo(&sysinfo);int numCPU = sysinfo.dwNumberOfProcessors; Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards) int numCPU = sysconf(_SC_NPROCESSORS_ONLN); FreeBSD, MacOS X, NetBSD, OpenBSD, etc. int mib[4];int numCPU;std::size_t len = sizeof(numCPU); /* set the mib for hw.ncpu */mib[0] = CTL_HW;mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;/* get the number of CPUs from the system */sysctl(mib, 2, &numCPU, &len, NULL, 0);if (numCPU < 1) { mib[1] = HW_NCPU; sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) numCPU = 1;} HPUX int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL); IRIX int numCPU = sysconf(_SC_NPROC_ONLN); Objective-C (Mac OS X >=10.5 or iOS) NSUInteger a = [[NSProcessInfo processInfo] processorCount];NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount]; | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/150355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5066/"
]
} |
150,375 | What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? | import pdb; pdb.set_trace() See Python: Coding in the Debugger for Beginners for this and more helpful hints. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
]
} |
150,404 | The examples I've seen online seem much more complex than I expected (manually parsing &/?/= into pairs, using regular expressions, etc). We're using asp.net ajax (don't see anything in their client side reference) and would consider adding jQuery if it would really help. I would think there is a more elegant solution out there - so far this is the best code I've found but I would love to find something more along the lines of the HttpRequest.QueryString object (asp.net server side) . Thanks in advance, Shane | There is indeed a QueryString plugin for jQuery, if you're willing to install the jQuery core and the plugin it could prove useful. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21261/"
]
} |
150,423 | What's the accepted way of storing quoted data in XML? For example, for a node, which is correct? (a) <name>Jesse "The Body" Ventura</name> (b) <name>Jesse \"The Body\" Ventura</name> (c) <name>Jesse "The Body" Ventura</name> (d) none of the above (please specify) If (a), what do you do for attributes? If (c), is it really appropriate to mix HTML & XML? Similarly, how do you handle single and curly quotes? | Your correct answer is A & C as the " is not a character that must be encoded in element data. You should always be XML encoding characters such as > , < , and & to ensure that you don't have issues if they are NOT inside a CDATA section. These are key items to be concerned about for element data. When talking about attributes you have to then also be careful of ' and " inside attribute values depending on the type of symbol you use to surround the value. I've found that often encoding " and ' is a better idea in all aspects as it helps at times when converting to other formats, where the " or ' might cause problems there as well. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
150,446 | I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this? | In 3.0, there's now an easier way - hook into the new motion events. The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events: @implementation ShakingView- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{ if ( event.subtype == UIEventSubtypeMotionShake ) { // Put in code here to handle shake } if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] ) [super motionEnded:motion withEvent:event];}- (BOOL)canBecomeFirstResponder{ return YES; }@end You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view). In the view controller, you want to set this view to become first responder: - (void) viewWillAppear:(BOOL)animated{ [shakeView becomeFirstResponder]; [super viewWillAppear:animated];}- (void) viewWillDisappear:(BOOL)animated{ [shakeView resignFirstResponder]; [super viewWillDisappear:animated];} Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns! This method works even if you set applicationSupportsShakeToEdit to NO. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/150446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944/"
]
} |
150,479 | Is there an official C# guideline for the order of items in terms of class structure? Does it go: Public Fields Private Fields Properties Constructors Methods ? I'm curious if there is a hard and fast rule about the order of items? I'm kind of all over the place. I want to stick with a particular standard so I can do it everywhere. The real problem is my more complex properties end up looking a lot like methods and they feel out of place at the top before the constructor. Any tips/suggestions? | According to the StyleCop Rules Documentation the ordering is as follows. Within a class, struct or interface: (SA1201 and SA1203) Constant Fields Fields Constructors Finalizers (Destructors) Delegates Events Enums Interfaces ( interface implementations ) Properties Indexers Methods Structs Classes Within each of these groups order by access: (SA1202) public internal protected internal protected private Within each of the access groups, order by static, then non-static: (SA1204) static non-static Within each of the static/non-static groups of fields, order by readonly, then non-readonly : (SA1214 and SA1215) readonly non-readonly An unrolled list is 130 lines long, so I won't unroll it here. The methods part unrolled is: public static methods public methods internal static methods internal methods protected internal static methods protected internal methods protected static methods protected methods private static methods private methods The documentation notes that if the prescribed order isn't suitable - say, multiple interfaces are being implemented, and the interface methods and properties should be grouped together - then use a partial class to group the related methods and properties together. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/150479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
]
} |
150,505 | I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object? My HttpRequest.GET currently returns an empty QueryDict object. I'd like to learn how to do this without a library, so I can get to know Django better. | When a URL is like domain/search/?q=haha , you would use request.GET.get('q', '') . q is the parameter you want, and '' is the default value if q isn't found. However, if you are instead just configuring your URLconf **, then your captures from the regex are passed to the function as arguments (or named arguments). Such as: (r'^user/(?P<username>\w{0,50})/$', views.profile_page,), Then in your views.py you would have def profile_page(request, username): # Rest of the method | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/150505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227001/"
]
} |
150,513 | I have a form in HTML where our users fill in the data and then print it. The data isn't saved anywhere. These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet. Normally another developer does them, but I have to do a few while he's out. Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents. It seems like there should be a better way. I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it. Any thoughts? | Add a separate CSS file for printing by doing something like this: <link rel="stylsheet" type="text/css" media="print" href="print.css"> add it to the <head> section of the page. In this(print.css) file include styling relevant to what you want to see when the page is printed, for example: input{border: 0px} should hide the border of input boxes when printing. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
150,532 | Similar to this question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python. I first read all ten bytes into a string. I then want to parse out the individual pieces of information. I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them. The struct package seems to be what I want, but I can't get it to work. Here is my code so-far (I am very new to python btw...so take it easy on me): def __init__(self, ten_byte_string): self.whole_string = ten_byte_string self.file_identifier = self.whole_string[:3] self.major_version = struct.pack('x', self.whole_string[3:4]) #this self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this self.flags = self.whole_string[5:6] self.len = self.whole_string[6:10] Printing out any value except is obviously crap because they are not formatted correctly. | If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by: >>> s = '\0\x02'>>> struct.unpack('>H', s)(2,) Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use. For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details. You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value: >>> a,b,c = struct.unpack('>HHi', some_string) Going by your code, you are looking for (in order): a 3 char string 2 single byte values (major and minor version) a 1 byte flags variable a 32 bit length quantity The format string for this would be: ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
} |
150,543 | In C, is it possible to forward the invocation of a variadic function? As in, int my_printf(char *fmt, ...) { fprintf(stderr, "Calling printf with fmt %s", fmt); return SOMEHOW_INVOKE_LIBC_PRINTF;} Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf. [Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function without modifying that function's definition .] | If you don't have a function analogous to vfprintf that takes a va_list instead of a variable number of arguments, you can't do it . See http://c-faq.com/varargs/handoff.html . Example: void myfun(const char *fmt, va_list argp) { vfprintf(stderr, fmt, argp);} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/150543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23600/"
]
} |
150,544 | In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it? | You can use Win32Exception and use its NativeErrorCode property to handle it appropriately. // http://support.microsoft.com/kb/186550const int ERROR_FILE_NOT_FOUND = 2;const int ERROR_ACCESS_DENIED = 5;const int ERROR_NO_APP_ASSOCIATED = 1155; void OpenFile(string filePath){ Process process = new Process(); try { // Calls native application registered for the file type // This may throw native exception process.StartInfo.FileName = filePath; process.StartInfo.Verb = "Open"; process.StartInfo.CreateNoWindow = true; process.Start(); } catch (Win32Exception e) { if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND || e.NativeErrorCode == ERROR_ACCESS_DENIED || e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED) { MessageBox.Show(this, e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
]
} |
150,548 | Despite the rather clear documentation which says that parseFloat() can return NaN as a value, when I write a block like: if ( NaN == parseFloat(input.text) ) { errorMessage.text = "Please enter a number."} I am warned that the comparison will always be false. And testing shows the warning to be correct. Where is the corrected documentation, and how can I write this to work with AS3? | Because comparing anything to NaN is always false. Use isNaN() instead. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
]
} |
150,552 | I will preface this question by saying, I do not think it is solvable. I also have a workaround, I can create a stored procedure with an OUTPUT to accomplish this, it is just easier to code the sections where I need this checksum using a function. This code will not work because of the Exec SP_ExecuteSQL @SQL calls. Anyone know how to execute dynamic SQL in a function? (and once again, I do not think it is possible. If it is though, I'd love to know how to get around it!) Create Function Get_Checksum( @DatabaseName varchar(100), @TableName varchar(100))RETURNS FLOATASBEGIN Declare @SQL nvarchar(4000) Declare @ColumnName varchar(100) Declare @i int Declare @Checksum float Declare @intColumns table (idRecord int identity(1,1), ColumnName varchar(255)) Declare @CS table (MyCheckSum bigint) Set @SQL = 'Insert Into @IntColumns(ColumnName)' + Char(13) + 'Select Column_Name' + Char(13) + 'From ' + @DatabaseName + '.Information_Schema.Columns (NOLOCK)' + Char(13) + 'Where Table_Name = ''' + @TableName + '''' + Char(13) + ' and Data_Type = ''int''' -- print @SQL exec sp_executeSql @SQL Set @SQL = 'Insert Into @CS(MyChecksum)' + Char(13) + 'Select ' Set @i = 1 While Exists( Select 1 From @IntColumns Where IdRecord = @i) begin Select @ColumnName = ColumnName From @IntColumns Where IdRecord = @i Set @SQL = @SQL + Char(13) + CASE WHEN @i = 1 THEN ' Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))' ELSE ' + Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))' END Set @i = @i + 1 end Set @SQL = @SQL + Char(13) + 'From ' + @DatabaseName + '..' + @TableName + ' (NOLOCK)' -- print @SQL exec sp_executeSql @SQL Set @Checksum = (Select Top 1 MyChecksum From @CS) Return isnull(@Checksum,0)ENDGO | It "ordinarily" can't be done as SQL Server treats functions as deterministic, which means that for a given set of inputs, it should always return the same outputs. A stored procedure or dynamic sql can be non-deterministic because it can change external state, such as a table, which is relied on. Given that in SQL server functions are always deterministic, it would be a bad idea from a future maintenance perspective to attempt to circumvent this as it could cause fairly major confusion for anyone who has to support the code in future. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23601/"
]
} |
150,575 | If I have an instance of a System.Timers.Timer that has a long interval - say 1 minute, how can I find out if it is started without waiting for the Tick? | System.Timer.Timer.Enabled should work, when you call "Start" it sets Enabled to TRUE, "Stop" sets it to FALSE. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/150575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
150,577 | Where can I test HTML 5 functionality today - is there any test build of any rendering engines which would allow testing, or is it to early? I'm aware that much of the spec hasn't been finalised, but some has, and it would be good to try it out! | Ones that are built using a recent webkit build, and Presto. Safari 3.1 for webkit Opera for Presto. I'm pretty sure firefox will start supporting html5 partially in 3.1 All support is extremely partial. Check here for information on what is supported. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
]
} |
150,588 | If I don't know the length of a text entry (e.g. a blog post, description or other long text), what's the best way to store it in MYSQL? | TEXT would be the most appropriate for unknown size text. VARCHAR is limited to 65,535 characters from MYSQL 5.0.3 and 255 chararcters in previous versions, so if you can safely assume it will fit there it will be a better choice. BLOB is for binary data, so unless you expect your text to be in binary format it is the least suitable column type. For more information refer to the Mysql documentation on string column types . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
]
} |
150,600 | I've heard a lot of good things about using Mylyn in eclipse. How could I set it up to give me a taste of how I could use it? | The seminal Developerworks article from the 2.0 release is a great introduction to Mylyn, and still relevant. Written by the Mik Kirsten who is the Mylyn project lead, it is a very clear explanation of something quite unique. Lots of pretty pictures showing it in action too. Mylyn Part one - Integrated Task Management Mylyn Part two - Automated Context Management | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
]
} |
150,638 | Sometimes it feels that my company is the only company in the world using Ruby but not Ruby on Rails, to the point that Rails has almost become synonymous with Ruby. I'm sure this isn't really true, but it'd be fun to hear some stories about non-Rails Ruby usage out there. | One of the huge benefits of Ruby is the ability to create DSLs very easily. Ruby allows you to create "business rules" in a natural language way that is usually easy enough for a business analyst to use. Many Ruby apps outside of web development exist for this purpose. I highly recommend Googling "ruby dsl" for some excellent reading, but I would like to leave you with one post in particular. Russ Olsen wrote a two part blog post on DSLs . I saw him give a presentation on DSLs and it was very good. I highly recommend reading these posts. I also found this excellent presentation on Ruby DSLs by Obie Fernandez . Highly recommended reading! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/150638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13051/"
]
} |
150,646 | I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online. | After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found: try { String fileName = "file.xls"; WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName)); workbook.createSheet("Sheet1", 0); workbook.createSheet("Sheet2", 1); workbook.createSheet("Sheet3", 2); workbook.write(); workbook.close();} catch (WriteException e) {} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
]
} |
150,695 | It seems like Sql Reporting Services Server logs information in several places including web server logs and logging tables in the database. Where are all the locations SSRS logs to, and what type of errors are logged in each place? | As far as I know SSRS logs to the Event Log, the filesystem and its own database. The database is typically the most easily available one. You just login to the ReportServer database and execute select * from executionlog This only logs the executions though. If you want more information you can go to the Trace Log files, which are usually available at (location may of course vary): C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\LogFiles These are quite verbose and not really fun to look through. But they do log a lot of stuff. If you're searching for an error you can go to the Windows Application Log (Under Administrative Tools in your control panel) Edit Found a nice link: https://learn.microsoft.com/en-us/sql/reporting-services/report-server/reporting-services-log-files-and-sources | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644/"
]
} |
150,726 | I was wondering how to use cin so that if the user does not enter in any value and just pushes ENTER that cin will recognize this as valid input. | You will probably want to try std::getline : #include <iostream>#include <string>std::string line;std::getline( std::cin, line );if( line.empty() ) ... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
150,731 | I would like to write some data to a file in Ruby. What is the best way to do that? | File.open("a_file", "w") do |f| f.write "some data"end You can also use f << "some data" or f.puts "some data" according to personal taste/necessity to have newlines. Change the "w" to "a" if you want to append to the file instead of truncating with each open. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
]
} |
150,741 | Apparently using the URL is no good - why is this the case, and how do you generate a good one? | Mark Pilgrim's article How to make a good ID in Atom is good. Here's part of it: Why you shouldn’t use your permalink as an Atom ID It’s valid to use your permalink URL as your <id>, but I discourage it because it can create confusion about which element should be treated as the permalink. Developers who don’t read specs will look at your Atom feed, and they see two identical pieces of information, and they pick one and use it as the permalink, and some of them will pick incorrectly. Then they go to another feed where the two elements are not identical, and they get confused. In Atom, <link rel="alternate"> is always the permalink of the entry. <id> is always a unique identifier for the entry. Both are required, but they serve different purposes. An entry ID should never change, even if the permalink changes. “Permalink changes”? Yes, permalinks are not as permanent as you might think. Here’s an example that happened to me. My permalink URLs were automatically generated from the title of my entry, but then I updated an entry and changed the title. Guess what, the “permanent” link just changed! If you’re clever, you can use an HTTP redirect to redirect visitors from the old permalink to the new one (and I did). But you can’t redirect an ID. The ID of an Atom entry must never change! Ideally, you should generate the ID of an entry once, and store it somewhere. If you’re auto-generating it time after time from data that changes over time, then the entry’s ID will change, which defeats the purpose. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
]
} |
150,750 | It's clear that a search performance of the generic HashSet<T> class is higher than of the generic List<T> class. Just compare the hash-based key with the linear approach in the List<T> class. However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the HashSet<T> . My question: where is the break-even? To simplify the scenario (and to be fair) let's assume that the List<T> class uses the element's Equals() method to identify an item. | A lot of people are saying that once you get to the size where speed is actually a concern that HashSet<T> will always beat List<T> , but that depends on what you are doing. Let's say you have a List<T> that will only ever have on average 5 items in it. Over a large number of cycles, if a single item is added or removed each cycle, you may well be better off using a List<T> . I did a test for this on my machine, and, well, it has to be very very small to get an advantage from List<T> . For a list of short strings, the advantage went away after size 5, for objects after size 20. 1 item LIST strs time: 617ms1 item HASHSET strs time: 1332ms2 item LIST strs time: 781ms2 item HASHSET strs time: 1354ms3 item LIST strs time: 950ms3 item HASHSET strs time: 1405ms4 item LIST strs time: 1126ms4 item HASHSET strs time: 1441ms5 item LIST strs time: 1370ms5 item HASHSET strs time: 1452ms6 item LIST strs time: 1481ms6 item HASHSET strs time: 1418ms7 item LIST strs time: 1581ms7 item HASHSET strs time: 1464ms8 item LIST strs time: 1726ms8 item HASHSET strs time: 1398ms9 item LIST strs time: 1901ms9 item HASHSET strs time: 1433ms1 item LIST objs time: 614ms1 item HASHSET objs time: 1993ms4 item LIST objs time: 837ms4 item HASHSET objs time: 1914ms7 item LIST objs time: 1070ms7 item HASHSET objs time: 1900ms10 item LIST objs time: 1267ms10 item HASHSET objs time: 1904ms13 item LIST objs time: 1494ms13 item HASHSET objs time: 1893ms16 item LIST objs time: 1695ms16 item HASHSET objs time: 1879ms19 item LIST objs time: 1902ms19 item HASHSET objs time: 1950ms22 item LIST objs time: 2136ms22 item HASHSET objs time: 1893ms25 item LIST objs time: 2357ms25 item HASHSET objs time: 1826ms28 item LIST objs time: 2555ms28 item HASHSET objs time: 1865ms31 item LIST objs time: 2755ms31 item HASHSET objs time: 1963ms34 item LIST objs time: 3025ms34 item HASHSET objs time: 1874ms37 item LIST objs time: 3195ms37 item HASHSET objs time: 1958ms40 item LIST objs time: 3401ms40 item HASHSET objs time: 1855ms43 item LIST objs time: 3618ms43 item HASHSET objs time: 1869ms46 item LIST objs time: 3883ms46 item HASHSET objs time: 2046ms49 item LIST objs time: 4218ms49 item HASHSET objs time: 1873ms Here is that data displayed as a graph: Here's the code: static void Main(string[] args){ int times = 10000000; for (int listSize = 1; listSize < 10; listSize++) { List<string> list = new List<string>(); HashSet<string> hashset = new HashSet<string>(); for (int i = 0; i < listSize; i++) { list.Add("string" + i.ToString()); hashset.Add("string" + i.ToString()); } Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < times; i++) { list.Remove("string0"); list.Add("string0"); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item LIST strs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); timer = new Stopwatch(); timer.Start(); for (int i = 0; i < times; i++) { hashset.Remove("string0"); hashset.Add("string0"); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item HASHSET strs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); Console.WriteLine(); } for (int listSize = 1; listSize < 50; listSize+=3) { List<object> list = new List<object>(); HashSet<object> hashset = new HashSet<object>(); for (int i = 0; i < listSize; i++) { list.Add(new object()); hashset.Add(new object()); } object objToAddRem = list[0]; Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i < times; i++) { list.Remove(objToAddRem); list.Add(objToAddRem); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item LIST objs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); timer = new Stopwatch(); timer.Start(); for (int i = 0; i < times; i++) { hashset.Remove(objToAddRem); hashset.Add(objToAddRem); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item HASHSET objs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); Console.WriteLine(); } Console.ReadLine();} | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/150750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23372/"
]
} |
150,753 | I'm currently working on a project for medical image processing, that needs a huge amount of memory. Is there anything I can do to avoid heap fragmentation and to speed up access of image data that has already been loaded into memory? The application has been written in C++ and runs on Windows XP. EDIT: The application does some preprocessing with the image data, like reformatting, calculating look-up-tables, extracting sub images of interest ... The application needs about 2 GB RAM during processing, of which about 1,5 GB may be used for the image data. | If you are doing medical image processing it is likely that you are allocating big blocks at a time (512x512, 2-byte per pixel images). Fragmentation will bite you if you allocate smaller objects between the allocations of image buffers. Writing a custom allocator is not necessarily hard for this particular use-case. You can use the standard C++ allocator for your Image object, but for the pixel buffer you can use custom allocation that is all managed within your Image object. Here's a quick and dirty outline: Use a static array of structs, each struct has: A solid chunk of memory that can hold N images -- the chunking will help control fragmentation -- try an initial N of 5 or so A parallel array of bools indicating whether the corresponding image is in use To allocate, search the array for an empty buffer and set its flag If none found, append a new struct to the end of the array To deallocate, find the corresponding buffer in the array(s) and clear the boolean flag This is just one simple idea with lots of room for variation. The main trick is to avoid freeing and reallocating the image pixel buffers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
]
} |
150,760 | Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates? Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file. I am thinking about a: Data Flow Task File source (with an associated file connection) A for loop container A script container that contains some logic to tell if another row exists Thak you, and everyone on this site is incredibly knowledgeable. Update: I have found this link, might help in answering this question | Use the Sort Component. Simply choose which fields you wish to sort your loaded rows by and in the bottom left corner you'll see a check box to remove duplicates. This box removes any rows which are duplicates based on the sort criteria onlyso in the example below the rows would be considered duplicate if we only sorted on the first field: 1 | sample A |1 | sample B | | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
]
} |
150,764 | Any code I've seen that uses Regexes tends to use them as a black box: Put in string Magic Regex Get out string This doesn't seem a particularly good idea to use in production code, as even a small change can often result in a completely different regex. Apart from cases where the standard is permanent and unchanging, are regexes the way to do things, or is it better to try different methods? | If regexes are long and impenetrable, making them hard to maintain then they should be commented. A lot of regex implementations allow you to pad regexes with whitespace and comments. See https://www.regular-expressions.info/freespacing.html#parenscomment and Coding Horror: Regular Expressions: Now You Have Two Problems Any code I've seen that uses Regexes tends to use them as a black box: If by black box you mean abstraction, that's what all programming is, trying to abstract away the difficult part (parsing strings) so that you can concentrate on the problem domain (what kind of strings do I want to match). even a small change can often result in a completely different regex. That's true of any code. As long as you are testing your regex to make sure it matches the strings you expect, ideally with unit tests , then you should be confident at changing them. Edit: please also read Jeff's comment to this answer about production code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/150764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
]
} |
150,781 | Does anyone know of any existing projects that aim to port Android's Java VM over to the iPhone? From what I understand, this wouldn't be too out of reach and would certainly make for some exciting developments. Edit : I should point out that I am aware this will not happen using the official iPhone SDK. However, a jailbroken platform would remove any Apple-imposed roadblocks. I imagine most that would be interested in integrating Android into the iPhone would also be the demographic that would typically have a jailbroken iphone. | There isn't currently an effort to port Dalvik to iPhone because Google hasn't released the source yet . As soon as the source is released (assuming all of it will be) I would think this will happen. It's also likely to be seen on other homebrew platforms such as PSP, Pandora , openmoko , etc. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
]
} |
150,814 | This is somewhat of a follow-up to an answer here . I have a custom ActiveX control that is raising an event ("ReceiveMessage" with a "msg" parameter) that needs to be handled by Javascript in the web browser. Historically we've been able to use the following IE-only syntax to accomplish this on different projects: function MyControl::ReceiveMessage(msg){ alert(msg);} However, when inside a layout in which the control is buried, the Javascript cannot find the control. Specifically, if we put this into a plain HTML page it works fine, but if we put it into an ASPX page wrapped by the <Form> tag, we get a "MyControl is undefined" error. We've tried variations on the following: var GetControl = document.getElementById("MyControl");function GetControl::ReceiveMessage(msg){ alert(msg);} ... but it results in the Javascript error "GetControl is undefined." What is the proper way to handle an event being sent from an ActiveX control? Right now we're only interested in getting this working in IE. This has to be a custom ActiveX control for what we're doing. Thanks. | I was able to get this working using the following script block format, but I'm still curious if this is the best way: <script for="MyControl" event="ReceiveMessage(msg)"> alert(msg);</script> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19678/"
]
} |
150,825 | My company is heavily invested in the MS BI Stack (SQL Server Reporting Services, -Analysis Services and -Integration Services), but I want to have a look at what the seemingly most talked about open-source alternative Pentaho is like. I've installed a version, and I got it up and running quite painlessly. So that's good. But I haven't really the time to start using it for actual work to get a thorough understanding of the package. Have any of you got any insights into what are the pros and cons of Pentaho vs MS BI, or any links to such comparisons? Much appreciated! | I reviewed multiple Bi stacks while on a path to get off of Business Objects. A lot of my comments are preference. Both tool sets are excellent. Some things are how I prefer chocolate fudge brownie ice cream over plain chocolate. Pentaho has some really smart guys working with them but Microsoft has been on a well funded and well planned path. Keep in mind MS are still the underdogs in the database market. Oracle is king here. To be competitive MS has been giving away a lot of goodies when you buy the database and have been forced to reinvent their platform a couple of times. I know this is not about the database, but the DB battle has cause MS to give away a lot in order to add value to their stack. 1.) Platform SQL server doesn't run on Unix or Linux so they are automatically excluded from this market. Windows is about the same price as some versions or Unix now. Windows is pretty cheap and runs faily well now. It gives me about as much trouble as Linux. 2.) OLAP Analysis services was reinvented in 2005 (current is 2008) over the 2000 version. It is an order of magnatude more powerful over 2000. The pentaho (Mondrian) is not as fast once you get big. It also has few features. It is pretty good but there are less in the way of tools. Both support Excel as the platform which is esscential. The MS version is more robust. 3.) ETL MS - DTS has been replaced with SSIS. Again, order of magnatude increase in speed, power, and ability. It controls any and all data movement or program control. If it can't do it you can write a script in Powershell. On par with Informatica in the 2008 release.Pentaho - Much better than is used to be. Not as fast as I would like but I can do just about everything I want to do. 4.) dashboard Pentaho has improved this. It is sort of uncomfortable and unfriendly to develop but there is really not a real equiv for MS. 5.) reports MS reports is really powerful but not all that hard to use. I like it now but hated it at first, until I got to know it a little better. I had been using crystal reports and the MS report builder is much more powerful. It is easy to do hard things in MS, but a little harder to do easy things.Pentaho is a little clumsy. I didn't like it at all but you might. I found it to be overly complex. I wish it was either more like the Crystal report builder or the MS report builder but it is jasper like. I find is to be hard. That may be a preference. 6.) ad hoc MS - this was the real winner for me. I tested it with my users an they instantly in love with the MS user report builder. What made the difference was how it was not just easy to use, but also productive.Pentaho - is good but pretty old school. It uses the more typical wizard based model and has powerful tools but I hate it. It is an excellent tool for what it is, but we have moved on from this style and no one wants to go back. Same problem I had with logiXML. The interface worked well for what it was but is not really much of a change from what we used 12 years. http://wiki.pentaho.com/display/PRESALESPORTAL/Methods+of+Interactive+Reporting There are some experienced people out there that can make Pentaho really run well, I just found the MS suite to be more productive. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/150825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23360/"
]
} |
150,977 | What is the best way to replace all '<' with < in a given database column? Basically perform s/<[^;]/</gi Notes: must work in MS SQL Server 2000 Must be repeatable (and not end up with <;;;;;;;;; ) | Some hacking required but we can do this with LIKE , PATINDEX , LEFT AND RIGHT and good old string concatenation. create table test( id int identity(1, 1) not null, val varchar(25) not null)insert into test values ('< <- ok, < <- nok')while 1 = 1begin update test set val = left(val, patindex('%<[^;]%', val) - 1) + '<' + right(val, len(val) - patindex('%<[^;]%', val) - 2) from test where val like '%<[^;]%' IF @@ROWCOUNT = 0 BREAKendselect * from test Better is that this is SQL Server version agnostic and should work just fine. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80/"
]
} |
150,998 | In my ActionScript3 class, can I have a property with a getter and setter? | Ok, well you can just use the basic getter/setter syntax for any property of your AS3 class. For example package { public class PropEG { private var _prop:String; public function get prop():String { return _prop; } public function set prop(value:String):void { _prop = value; } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/150998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14131/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.