Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm a complete beginner when it comes to programming. I'm taking a stab at PHP, and have seen how powerful the frameworks can be. But should I even consider trying to work with a framework until I have a strong grasp of PHP itself? Note: I'd most likely be using CodeIgnitor, but the question applies to any of the fram...
Preferably, you should have a strong grasp of the language (and programming in general) before you start using frameworks. Frameworks can and will save you a lot of work, but you they also introduce advanced concepts and implementations. After you gain some experience and start to wonder what's the best way to solve s...
Personally I would stick to learning PHP and creating some projects without the assistance of a framework. While frameworks can abstract a lot of the messy, boring parts of a project away, it's important to still know how they work, especially when debugging. Frameworks can be also be very complicated, and learning ho...
Should a beginning PHP programmer consider frameworks?
[ "", "php", "frameworks", "" ]
I have an application, written in C++ using MFC and Stingray libraries. The application works with a wide variety of large data types, which are all currently serialized based on MFC Document/View serialize derived functionality. I have also added options for XML serialization based on the Stingray libraries, which imp...
The [Boost Serialization](http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html) library supports XML. This library basically consists in: 1. Start from the principles of MFC serialization and take all the good things it provides. 2. Solve every single issue of MFC serialization! Among the improvemen...
This is an age old problem. I was the team lead of the development team with the most critical path dependencies on the largest software project in the world during 1999 and 2000 and this very issue was the focus of my work during that time. I am convinced that the wheel was invented by multiple engineers who were unaw...
Best XML serialization library for a MFC C++ app
[ "", "c++", "xml", "mfc", "" ]
I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and ...
There are several common techniques including using semaphores. The one I see used most often is to create a "pid lock file" on startup that contains the pid of the running process. If the file already exists when the program starts up, open it up and grab the pid inside, check to see if a process with that pid is runn...
The Right Thing is advisory locking using `flock(LOCK_EX)`; in Python, this is found in the [`fcntl` module](http://docs.python.org/3/library/fcntl.html). Unlike pidfiles, these locks are always automatically released when your process dies for any reason, have no race conditions exist relating to file deletion (as th...
Ensure a single instance of an application in Linux
[ "", "python", "linux", "single-instance", "" ]
This one is a case of not doing your homework.:-) Apart from dynamic loading advantage, does it make sense to include a JavaScript library(jQuery in my case ) from a Google server when I can load it from my server as a single file comprised of the 19kb jQuery zip file + the additional JavaScript code I have written – ...
Consider that a jQuery script downloaded from the google CDN might well already be cached on a visitor's browser, since it has consistent headers and cache control no matter where it is downloaded from. Hence, on average most users will only have to download your site-specific javascript scripts. Also, CDN generally ha...
Are you sure scripts would be downloaded in parallel? [This example from Cuzillion](http://stevesouders.com/cuzillion/?c0=hj1hfff2_0&c1=hj1hfff2_0&t=1227551978929) seems to be saying that only IE8 can do that. Also worth finding out is how many of your pageviews are first time visitors and how many have visited the si...
Streaming jquery(JS files) from a CDN (Google)
[ "", "javascript", "jquery", "performance", "http", "" ]
We're writing a records management product for schools and one of the requirements is the ability to manage course schedules. I haven't looked at the code for how we deal with this (I'm on a different project at the moment), but nonetheless I started wondering how best to handle one particular part of this requirement,...
I would avoid the string option for the sense of purity: it adds an extra layer of encoding/decoding that you do not need. It may also mess you up in the case of internationalization. Since the number of days in a week is 7, I would keep seven columns, perhaps boolean. This will also facilitate subsequent queries. Thi...
I don't think it's hard to write queries if we use the bit option. Just use simple binary math. I think it's the most efficient method. Personally, I do it all the time. Take a look: ``` sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64. ``` Now, say the course is held on mon, wed and fri. the value to save in data...
What's the best way to store the days of the week an event takes place on in a relational database?
[ "", "sql", "database-design", "" ]
(This is related to [Floor a date in SQL server](https://stackoverflow.com/questions/85373/floor-a-date-in-sql-server).) Does a deterministic expression exist to floor a DATETIME? When I use this as a computed column formula: ``` DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0) ``` the I get an error when I place ...
My guess is that this is a bug of some sorts. In SQL 2005 I was able to create such an indexed view without a problem (code is below). When I tried to run it on SQL 2000 though I got the same error as you are getting. The following seems to work on SQL 2000, but I get a warning that the index will be ignored AND you w...
Does your column [datetime\_column] have a default value set to "getDate()" ?? If so, since getdate() function is non-deterministic, this will cause this error... Whether a user-defined function is deterministic or nondeterministic depends on how the function is coded. User-defined functions are deterministic if: 1....
SQL Server: Floor a date in SQL server, but stay deterministic
[ "", "sql", "sql-server", "indexing", "sql-server-2000", "deterministic", "" ]
I'm a C/Python programmer in C++ land working with the STL for the first time. In Python, extending a list with another list uses the `.extend` method: ``` >>> v = [1, 2, 3] >>> v_prime = [4, 5, 6] >>> v.extend(v_prime) >>> print(v) [1, 2, 3, 4, 5, 6] ``` I currently use this algorithmic approach to extend vectors i...
From [here](https://cplusplus.com/reference/vector/vector/insert/) ``` // reserve() is optional - just to improve performance v.reserve(v.size() + distance(v_prime.begin(),v_prime.end())); v.insert(v.end(),v_prime.begin(),v_prime.end()); ```
``` copy(v_prime.begin(), v_prime.end(), back_inserter(v)); ```
C++ extend a vector with another vector
[ "", "c++", "vector", "" ]
GWT seems like a really nice technology for Java developers who don't like (or don't know) HTML/JS/CSS to build rich web interfaces. On the server-side Grails also looks really nice, it's often described as "Rails for Java developers". I've read that Grails' "convention over configuration" approach, together with the b...
Grails already has a gwt plugin: [check it out](http://grails.org/GWT+Plugin).
You did mention on the server side - GWT and grails actually doesn't integrate well on the serverside (not as well as you might expect given how well grails domain objects work). For RPC, the plugin it works really well. The problem is that domain objects cannot be serialized and tranfered across the wire - after all,...
integrating Grails and GWT
[ "", "java", "gwt", "grails", "groovy", "" ]
I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these? What would the Pros and Cons be ...
You could just declare a private constructor that does nothing. The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.
Don't bother making them abstract, but include a private parameterless constructor to prevent them from ever being instantiated. Point of comparison for those interested: in C# you would declare the class to be static, making it abstract *and* sealed (Java's final) in the compiled form, and without any instance constr...
Should Helper/Utility Classes be abstract?
[ "", "java", "abstract-class", "" ]
Is `yield return` a shortcut for implementing `IEnumerable` and `IEnumerator`?
Yes, it is. You can find out a lot more about it in chapter 6 of my book, C# in Depth. Fortunately chapter 6 is [available for free](http://www.manning-source.com/books/skeet/Chapter6sample.pdf) from [Manning's web site](http://manning.com/skeet/). I also have two [other](http://csharpindepth.com/Articles/Chapter6/It...
To add to the link-fest, Raymond Chen did a nice little series on C# iterators a few months ago: * <http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx> * <http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx> * <http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx> * <http://bl...
Is Yield Return == IEnumerable & IEnumerator?
[ "", "c#", "ienumerable", "yield", "iterator", "ienumerator", "" ]
What is the difference between a `const_iterator` and an `iterator` and where would you use one over the other?
`const_iterator`s don't allow you to change the values that they point to, regular `iterator`s do. As with all things in C++, always prefer `const`, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not `const` to change the pointed-to value).
They should pretty much be self-explanatory. If iterator points to an element of type T, then const\_iterator points to an element of type 'const T'. It's basically equivalent to the pointer types: ``` T* // A non-const iterator to a non-const element. Corresponds to std::vector<T>::iterator T* const // A const itera...
What is the difference between const_iterator and non-const iterator in the C++ STL?
[ "", "c++", "stl", "iterator", "constants", "" ]
I'd like to establish an ssh tunnel over ssh to my mysql server. Ideally I'd return a mysqli db pointer just like I was connecting directly. I'm on a shared host that doesn't have the [SSH2](http://ca.php.net/ssh2) libraries but I might be able to get them installed locally using PECL. If there's a way that uses nat...
Eric, I think you are out of luck on this one. You can either use the ssh extension in your PHP code, or if you have access to the server, you could try to create a ssh tunnel on the command-line. You probably need special permissions to do that, though. It also looks like you don't have ssh access to this hosting ac...
I would use the [autossh](http://www.harding.motd.ca/autossh/) tool to create a persistent ssh tunnel to your mysql database. Then all you have to do in your PHP code is point it to localhost. You can test this (without automatic restart) by doing: ``` ssh -L 3306:localhost:3306 user@domain.com ``` Setup a ssh key s...
Connect to a MySQL server over SSH in PHP
[ "", "php", "mysql", "ssh", "" ]
I am not that hot at regular expressions and it has made my little mind melt some what. I am trying to find all the tables names in a query. So say I have the query: ``` SELECT one, two, three FROM table1, table2 WHERE X=Y ``` I would like to pull out "table1, table2" or "table1" and "table2" But what if there is n...
RegEx isn't very good at this, as it's a lot more complicated than it appears: * What if they use LEFT/RIGHT INNER/OUTER/CROSS/MERGE/NATURAL joins instead of the a,b syntax? The a,b syntax should be avoided anyway. * What about nested queries? * What if there is no table (selecting a constant) * What about line breaks...
Everything said about the usefulness of such a regex in the SQL context. If you insist on a regex and your SQL statements always look like the one you showed (that means no subqueries, joins, and so on), you could use ``` FROM\s+([^ ,]+)(?:\s*,\s*([^ ,]+))*\s+ ```
Regular expression to find all table names in a query
[ "", ".net", "sql", "regex", "" ]
In what cases is it necessary to synchronize access to instance members? I understand that access to static members of a class always needs to be synchronized- because they are shared across all object instances of the class. My question is when would I be incorrect if I do not synchronize instance members? for examp...
It depends on whether you want your class to be thread-safe. Most classes shouldn't be thread-safe (for simplicity) in which case you don't need synchronization. If you need it to be thread-safe, you should synchronize access *or* make the variable volatile. (It avoids other threads getting "stale" data.)
The `synchronized` modifier is really a *bad* idea and should be avoided at all costs. I think it is commendable that Sun tried to make locking a little easier to acheive, but `synchronized` just causes more trouble than it is worth. The issue is that a `synchronized` method is actually just syntax sugar for getting t...
What Cases Require Synchronized Method Access in Java?
[ "", "java", "concurrency", "synchronization", "methods", "non-static", "" ]
I am trying to improve the performance of the threaded application with real-time deadlines. It is running on Windows Mobile and written in C / C++. I have a suspicion that high frequency of thread switching might be causing tangible overhead, but can neither prove it or disprove it. As everybody knows, lack of proof i...
While you said you don't want to write a test application, I did this for a previous test on an ARM9 Linux platform to find out what the overhead is. It was just two threads that would boost::thread::yield() (or, you know) and increment some variable, and after a minute or so (without other running processes, at least ...
I doubt you can find this overhead somewhere on the web for any existing platform. There exists just too many different platforms. The overhead depends on two factors: * The CPU, as the necessary operations may be easier or harder on different CPU types * The system kernel, as different kernels will have to perform di...
How to estimate the thread context switching overhead?
[ "", "c++", "c", "multithreading", "windows-mobile", "" ]
The following questions are about XML serialization/deserialization and schema validation for a .net library of types which are to be used for data exchange. --- First question, if I have a custom xml namespace say "<http://mydomain/mynamespace>" do I have to add a ``` [XmlRoot(Namespace = "http://mydomain/mynamespa...
Just to add - the "xsi" etc is there to support things like xsi:nil on values later on - a well-known pattern for nullable values. It has to write the stream "forwards only", and it doesn't know (when it writes the first bit) whether it will need nil or not, so it assumes that writing it unnecessarily once is better th...
1) XmlRoot can only be set at the class/struct/interface level (or on return values). So you can't use it on the assembly level. What you're looking for is the [XmlnsDefinitionAttribute](http://msdn.microsoft.com/en-us/library/system.windows.markup.xmlnsdefinitionattribute.aspx), but I believe that only is used by the ...
Xml Serialization and Schemas in .net (C#)
[ "", "c#", ".net", "xml", "serialization", "" ]
Is it possible to use [CPython](http://www.python.org/) to develop Adobe Flash based applications?
You can try [ming](http://www.libming.org/), a library for generating Macromedia Flash files (.swf). It's written in C but it has wrappers that allow it to be used in C++, PHP, Python, Ruby, and Perl.
take a look at Flex PyPy: <http://code.google.com/p/flex-pypy/>
Adobe Flash and Python
[ "", "python", "flash", "flashdevelop", "" ]
Does anyone have any experience with running C++ applications that use the boost libraries on uclibc-based systems? Is it even possible? Which C++ standard library would you use? Is uclibc++ usable with boost?
We use Boost together with GCC 2.95.3, libstdc++ and STLport on an ARMv4 platform running uClinux. Some parts of Boost are not compatible with GCC 2.x but the ones that are works well in our particular case. The libraries that we use the most are *date\_time*, *bind*, *function*, *tuple* and *thread*. Some of the libr...
We are using many of the Boost libraries (thread, filesystem, signals, function, bind, any, asio, smart\_ptr, tuple) on an [Arcom Vulcan](http://www.arcom.com/pc104-ixp425-vulcan.htm) which is admittedly pretty powerful for an embedded device (64M RAM, 533MHz XScale). Everything works beautifully. GCC 3.4 but we're no...
Can I use boost on uclibc linux?
[ "", "c++", "linux", "boost", "uclinux", "uclibc", "" ]
I am looking for a good menu to use in an ASP.NET. I am currently using the asp menu. I need it to work in IE 6,7,8, Firefox and Safari. I also need it to not add a lot of overhead to the page client-side. I need to be able to load it from the database.
Write your own Server Control which implements the asp.net menu control but go one step further and implement the CSS friendly adapters which will give you standards compliant code instead of the usual garbage html tables that asp:menu creates. You can read more here: <http://www.asp.net/cssadapters/Whitepaper.aspx>
You can use this code as inspiration: <http://trac2.assembla.com/GiusCms/browser/trunk/Controls/Controls/Menu.cs> This control is able to use any SiteMapDataSource. Or you can simply customize it as you want. Use CSS to hide and show inner submenus.
Need a good ASP.NET menu
[ "", "c#", "asp.net", "menu", "" ]
I am creating an touch screen application using Swing and have a request to change one of buttons so that it will behave like a keyboard when the button is held down. (First of all, I am not sure that the touch screen will allow the user to "hold down" the button, but pretend that they can for now) I was going to go...
[javax.swing.Timer](http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html) is your friend. And [here's an article](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) with some more info.
I would do it like this: * Listen to mousePressed and schedule a java.util.Timer to be launched at a later time. * The Timer does the action and set itself to schedule again. * Listen to mouseReleased to cancel the Timer.
How can I make a swing JButton repeat its action when it is held down?
[ "", "java", "swing", "event-listener", "" ]
What's the best way to get a regular anchor (`<a href="...">`) to submit the form it is embedded in when clicked? ``` <form> <ul> <li> <p> The link could be <span>embedded <a href="" onclick="?">at any level</a></span> in the form, so "this.parentNode.parentNode....
loop through parent nodes until you find an element with tagname that indicates it's a form! ``` <form> <ul> <li> <p> The link could be <span>embedded <a href="" onclick="get_form(this).submit(); return false">at any level</a></span> in the form, so "this.parentN...
Why don't you use an `<input>` or `<button>` element and just tweak it with CSS? Then it works without Javascript and is therefore more reliable.
How best to make a link submit a form
[ "", "javascript", "html", "forms", "" ]
I have the following code that creates two objects (ProfileManager and EmployerManager) where the object EmployerManager is supposed to inherit from the object ProfileManager. However, when I do alert(pm instanceof ProfileManager); it returns false. ``` function ProfileFactory(profileType) { switch(profileType) ...
Thanks for all of the comments. However, the solution to the problem was found in making this change to the declaration of the EmployerManager: ``` function EmployerManager() { this.controller = 'eprofile.php'; this.anchors = new Array('Industries', 'Employer Profiles', 'Employer Profile'); this.actions =...
I've been using something similar to Dean Edward's Base.js model. <http://dean.edwards.name/weblog/2006/03/base/>
How to Establish Inheritance Between Objects in JavaScript?
[ "", "javascript", "oop", "inheritance", "" ]
Clearly the following is incorrect. ``` INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name'); ``` I get the value: SQL query: ``` INSERT INTO `aTable` (`A`, `B` ) VALUES ( ( SELECT MAX(`A`) FROM `aTable` ) *2 , 'name' ) ``` MySQL said: 1093 - You can't specify target table ...
try: ``` insert into aTable select max(a)^2, 'name' from aTable; ``` or ``` insert into aTable select max(a)^2, 'name' from aTable group by B; ``` If you need a join, you can do this: ``` insert into aTable select max(a)^2, 'name' from aTable, bTable; ``` My "Server version" is "5.0.51b-community-nt MySQL Communi...
Actually, you can alias the table on the insert. I've seen this question all over the place, but no one seems to have tried that. Use a subquery to get the max from the table, but alias the table in the subquery. ``` INSERT INTO tableA SET fieldA = (SELECT max(x.fieldA) FROM tableA x)+1; ``` A more complex example, w...
Select from same table as an Insert or Update
[ "", "mysql", "sql", "mysql-error-1093", "" ]
Edit: This code is fine. I found a logic bug somewhere that doesn't exist in my pseudo code. I was blaming it on my lack of Java experience. In the **pseudo code** below, I'm trying to parse the XML shown. A silly example maybe but my code was too large/specific for anyone to get any real value out of seeing it and le...
The code looks fine to me. I say set breakpoints at the start of each function and watch it in the debugger or add some print statements. My gut tells me that either `characters()` is not being called or `setColor()` and `setAge()` don't work correctly, but that's just a guess.
When you say that the Cows are uninitialized, are the String properties initialized to null? Or empty Strings? I know you mentioned that this is pseudo-code, but I just wanted to point out a few potential problems: ``` public void startElement(...tag...) { if(tag == pluralcow){ // rule: there is only 1 ...
Java Vector Field (private member) accumulator doesn't store my Cows!
[ "", "java", "vector", "field", "" ]
In C++, is (int) ch equivalent to int(ch). If not, what's the difference?
They are the same thing, and also the same as `(int)(ch)`. In C++, it's generally preferred to use a named cast to clarify your intentions: * Use `static_cast` to cast between primitive types of different sizes or signednesses, e.g. `static_cast<char>(anInteger)`. * Use `dynamic_cast` to downcast a base class to a der...
`int(x)` is called function-style cast by the standard and is the same as the C-style cast in every regard (for POD) [5.2.3]: > If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).
(int) ch vs. int(ch): Are they different syntaxes for the same thing?
[ "", "c++", "casting", "" ]
I know that in JavaScript, creating a for loop like this: `for(int i = 0; i < arr.length; i++)` is costly as it computes the array length each time. Is this behavior costly in c# for lists and arrays as well. Or at compile-time is it optimized? Also what about other languages such as Java, how is this handled?
It is *not* costly in C#. For one thing, there is no “calculation“: querying the length is basically an elementary operation thanks to inlining. And secondly, because ([according to its developers](http://blogs.msdn.com/ericgu/archive/2004/04/18/115566.aspx)), the compiler recognizes this pattern of access and will in ...
1. All .Net arrays have a field containing the length of the array, so the length is not computed at usage but at creation time. 2. The .Net virtual machine is very good at eliminating bounds checks whenever possible, this is one of those cases, where the bounds check is moved outside the loop (in most situations, and ...
Is it costly to do array.length or list.count in a loop
[ "", "c#", "compiler-construction", "performance", "language-features", "" ]
I have seen samples of closure from - [What is a 'Closure'?](https://stackoverflow.com/questions/36636/what-is-a-closure) Can anyone provide simple example of when to use closure? **Specifically, scenarios in which closure makes sense?** Lets assume that the language doesn't have closure support, how would one still...
Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do: ``` string name = // blah int ...
I agree with a previous answer of "all the time". When you program in a functional language or any language where lambdas and closures are common, you use them without even noticing. It's like asking "what is the scenario for a function?" or "what is the scenario for a loop?" This isn't to make the original question so...
When to use closure?
[ "", "c#", "functional-programming", "closures", "" ]
I’m starting a project where I need to implement a light-weight interpreter. The interpreter is used to execute simple scientific algorithms. The programming language that this interpreter will use should be simple, since it is targeting non- software developers (for example, mathematicians.) The interpreter should su...
I would write it in [ANTLR](http://www.antlr.org/). Write the grammar, let ANTLR generate a C# parser. You can ANTLR ask for a parse tree, and possibly the interpreter can already operate on the parse tree. Perhaps you'll have to convert the parse tree to some more abstract internal representation (although ANTLR alrea...
It might sound odd, but Game Scripting Mastery is a great resource for learning about parsing, compiling and interpreting code. You should really check it out: [http://www.amazon.com/Scripting-Mastery-Premier-Press-Development/dp/1931841578](https://rads.stackoverflow.com/amzn/click/com/1931841578)
Constructing a simple interpreter
[ "", "c#", "architecture", "compiler-construction", "programming-languages", "" ]
What is JDBC and where can I start learning about? I know it's a way to access databases with Java, but what problems does it solve? Is it an ORM (or does it try to be)? Does it abstract away differences between databases, at the syntax level? What does it do? and what does it not do?
JDBC is a driver that allows you to access database. It provides you with a very raw way to access the database using SQL. Its primary function is to allow you (the user) to run SQL commands on the database. It is not an ORM and never will be. The sun website <http://java.sun.com/docs/books/tutorial/jdbc/> has a nice t...
No, JDBC isn't an ORM. It's the [Java Database Connectivity](http://java.sun.com/javase/technologies/database/index.jsp) API and basically it provides a database-agnostic access layer with a provider model (so that new database drivers can be added easily). Vendors can add more functionality for specific database featu...
What is JDBC (Java DataBase Connectivity)?
[ "", "java", "jdbc", "" ]
What is the difference between using system() to execute a binary and using the combination of fork/execvp. Is there any security/portablility/performance difference.
System also uses a `fork`/`exec`... combination. If you do `fork`/`exec` yourself you can execute parallel to your running process, while `system` is blocking (includes the `wait`). Also `system` executes the command not direct, but via a shell (which makes problems with setuid bit) and `system` blocks/ignores certain ...
Yes, `system()` runs the command through a shell, while `exec()` runs the command directly. Of course, introducing a shell opens up for bugs and exploits. Edit: of course, [the man page](http://linux.die.net/man/3/system) provides more detail.
Difference between using fork/execvp and system call
[ "", "c++", "c", "linux", "unix", "" ]
I've looked into and considered many JavaScript unit tests and testing tools, but have been unable to find a suitable option to remain fully TDD compliant. So, is there a JavaScript unit test tool that is fully TDD compliant?
## [Karma](http://karma-runner.github.io) or [Protractor](http://angular.github.io/protractor/#/) Karma is a JavaScript test-runner built with Node.js and meant for unit testing. The Protractor is for end-to-end testing and uses Selenium Web Driver to drive tests. Both have been made by the Angular team. You can use...
Take a look at [the Dojo Object Harness (DOH) unit test framework](http://www.dojotoolkit.org/reference-guide/util/doh.html) which is pretty much framework independent harness for JavaScript unit testing and doesn't have any Dojo dependencies. There is a very good description of it at [Unit testing Web 2.0 applications...
JavaScript unit test tools for TDD
[ "", "javascript", "unit-testing", "tdd", "" ]
Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript? I have a hidden form in HTML that is updated based on a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean...
# Do: ``` var isTrueSet = (myValue === 'true'); ``` using the identity operator (`===`), which doesn't make any implicit type conversions when the compared variables have different types. This will set `isTrueSet` to a boolean `true` if the string is "true" and boolean `false` if it is string "false" or not set at a...
# Warning This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY `"true"` or `"false"`. An invalid json string passed into these functions below **WILL throw an exception**. --- **Original answer:** How about? ``` JSON.parse("True".toLo...
How can I convert a string to boolean in JavaScript?
[ "", "javascript", "boolean-expression", "boolean-operations", "string-conversion", "" ]
I want to let the user draw on an image in a browser. In other words, I need *both* bitmapped graphics and drawing capabilities, whether vector or bitmapped. Canvas looks good, but is not supported by IE, and though there is ExCanvas, I wonder if ExCanvas is stable enough for consistent use in IE6 through 8. Or best ...
Even though you said you'd like to avoid it I'd suggest Flash. You could easily use Flash 6 or 7 and these have a > 90% adoption rate. I'd be surprised if you could get that level of support with JavaScript. Flash is truly write once run anywhere, which will cut down on your development time.
Take a look at [RaphaelJS](http://raphaeljs.com/)... it's a cross browser implementation of drawing functions, using Canvas, VML or SVG where available. I'm not sure if it lets users draw for themselves out of the box, but it might be worth a look.
Drawing on top of an image in Javascript
[ "", "javascript", "image", "browser", "graphics", "draw", "" ]
What is the best way to encode URL strings such that they are rfc2396 compliant and to decode a rfc2396 compliant string such that for example %20 is replaced with a space character? edit: URLEncoder and URLDecoder classes do **not** encode/decode rfc2396 compliant URLs, they encode to a MIME type of application/x-www...
Use the URI class as follows: ``` URI uri = new URI("http", "//www.someurl.com/has spaces in url", null); URL url = uri.toURL(); ``` or if you want a String: ``` String urlString = uri.toASCIIString(); ```
Your component parts, potentially containing characters that must be escaped, should already have been escaped using URLEncoder before being concatenated into a URI. If you have a URI with out-of-band characters in (like space, "<>[]{}\|^`, and non-ASCII bytes), it's not really a URI. You can try to fix them up by man...
Encode and Decode rfc2396 URLs
[ "", "java", "rfc2396", "" ]
I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don't initially know the final number of samples I will actually retrieve. What is the most efficient way to concatenate these arrays together in C# as I pull them out of the system?
You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a `List<T>` which can grow as it needs to. Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything. See [Eric Lippert's blog post on arrays](https://learn.microsoft.com/en-us/a...
Concatenating arrays is simple using linq extensions which come standard with .Net 4 Biggest thing to remember is that linq works with `IEnumerable<T>` objects, so in order to get an array back as your result then you must use the `.ToArray()` method at the end Example of concatenating two byte arrays: ``` byte[] fi...
Most efficient way to append arrays in C#?
[ "", "c#", "arrays", "memory-management", "" ]
I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example: ``` import org.apache.commons.lang.builder.EqualsBuilder; public class Foo { public class Bar { private Bar() {} public Foo getMyFoo() { return Foo.this } ...
No. The best way is probably what you suggested: add a getFoo() method to your inner class.
No, not possible without a getter. The 'this' keyword will always point to the current instance. I'm quite curious why you would want to do this... seems like you are doing composition in the wrong way. ``` public class Foo { public Bar createBar(){ Bar bar = new Bar(this) return bar; } } public class Ba...
How to refer to the outer class in another instance of a non-static inner class?
[ "", "java", "syntax", "reference", "inner-classes", "" ]
I'm writing this question in the spirit of answering your own questions, since I found a solution to the problem, but if anyone has a better solution I would gladly listen to it. In the application I am currently working on I am subclassing the ListView control to add some functionality of which some interacts with th...
The problem seems to be that the SelectedIndices and SelectedItems does not update properly if the ListView has not been drawn, as is stated in this comment from the MSDN documentation of the [ListViewItem.Selected property](http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.selected(VS.85).aspx)...
I found a trick you can use to get those properties populated: listView.AccessibilityObject.ToString(); //workaround to get selecteditems properties refreshed
Why do SelectedIndices and SelectedItems not work when ListView is instantiated in unit test?
[ "", "c#", ".net", "winforms", "unit-testing", "listview", "" ]
I wish to set a usererror string before leaving a function, depending on the return code and variable in the function. I currently have: ``` Dim RetVal as RetType try ... if ... then RetVal = RetType.FailedParse end try endif ... finally select case RetVal case ... UserStr = ... ...
The only real way of doing this in C# would be to declare a variable at the start of the method to hold the value - i.e. ``` SomeType result = default(SomeType); // for "definite assignment" try { // ... return result; } finally { // inspect "result" } ``` In VB, you *might* be able to access the result dir...
Declare the variable out of the try block, and check in the finally block if it has been set.
Is it legal and possible to access the return value in a finally block?
[ "", "c#", ".net", "vb.net", "try-catch", "seh", "" ]
I'm looking for a good lightweight Java docking framework. I know that Netbeans and Eclipse can be used as RCP, but I'm looking for something a little bit more lightweight.
Swing / AWT frameworks: * [Raven Docking](http://raven.java.net/ravenDocking/download.html) Apache 2; 0.2 MB * [MyDoggy](http://mydoggy.sourceforge.net/) LGPL; only JARs: 0.7 MB; Dec 2010 * [VLDocking](http://code.google.com/archive/p/vldocking/) LGPL; 0.4 MB * [NetBeans](http://netbeans.org/features/platform/index.ht...
I once evaluated several docking frameworks (including the already mentioned [flexdock](https://flexdock.dev.java.net/) and [mydoggy](http://mydoggy.sourceforge.net/) and [jdocking](https://jdocking.dev.java.net/). Finaly I came to [Docking Frames](http://dock.javaforge.com/index.html), which I can really recommend. I...
What are good docking frameworks for Java/Swing?
[ "", "java", "swing", "frameworks", "docking", "" ]
Is there any way to set an event handler without doing it manually in the classname.designer.cs file other than double clicking the UI element?
Click on the lightning bolt icon in the Properties window. Double-click the event you want to implement.
If I follow your question correctly, you can just do it in your code-behind like this: ``` myButton.Click += myHandler; ``` Or you could use an anonymous delegate: ``` myButton.Click += delegate { MessageBox.Show("Clicked!"); }; ```
Setting an Event handler without doing it manually in the classname.designer.cs file
[ "", "c#", "winforms", "events", "" ]
Is there any Java library that supports hierarchical column? For example (the first three row are columns) : ``` ------------------------------------------------ 2008 | ------------------------------------------------ January | February | ---------...
May be a [JXTree](http://javadesktop.org/swinglabs/build/weekly/latest/swingx-HEAD/javadoc/org/jdesktop/swingx/JXTree.html) from [SwingLab](https://swinglabs.dev.java.net/) could approach what you are looking for. Illustration [here](http://avatar21.superihost.com/index.php?entry=entry060514-170809), from the [Swingx]...
[Infragistics WebGrid for JSF](http://www.infragistics.com/java/netadvantage/jsf/webgridoverview.aspx): [alt text http://www.infragistics.com/uploadedImages/Products/NetAdvantage\_for\_JSF/Features/WebGrid/Gallery/WebGrid\_Hierarchical.png](http://www.infragistics.com/uploadedImages/Products/NetAdvantage_for_JSF/Featu...
Hierarchical table column in Java
[ "", "java", "grid", "hierarchical", "" ]
I have a N-Ary non sorted in any way tree and each node can have 0-N children. Given the data structure below, how can I fill the tree view assuming you have an array of TermNodes and that array is the first level of the TreeView? I have not been able to come up with a recursive way to do this. ``` class TermNode { ...
Thanks All I was getting confused because I did not realize that for a given TreeNode tn, tn.Nodes.Add would return the added TreeNode Once you know that the solution is straight forward like so ``` private void /*TreeNode*/ RecursiveAdd(OntologyNode on, TreeNode tn) { if (on.Children.Count == 0) { ret...
Here is a bit of code to get you started with the recursion. It's not tested (I can't right now), but you should get the idea: ``` public static void BuildTreeView(TreeNodeCollection Parent, List<TermNode> TermNodeList) { foreach (TermNode n in TermNodeList) { TreeNode CurrentNode = Parent.Add(n.Name); // ...
Filling up a TreeView control
[ "", "c#", "data-structures", "treeview", "" ]
What is the concept of erasure in generics in Java?
It's basically the way that generics are implemented in Java via compiler trickery. The compiled generic code *actually* just uses `java.lang.Object` wherever you talk about `T` (or some other type parameter) - and there's some metadata to tell the compiler that it really is a generic type. When you compile some code ...
Just as a side-note, it is an interesting exercise to actually see what the compiler is doing when it performs erasure -- makes the whole concept a little easier to grasp. There is a special flag you can pass the compiler to output java files that have had the generics erased and casts inserted. An example: ``` javac ...
What is the concept of erasure in generics in Java?
[ "", "java", "generics", "" ]
I have a read query that I execute within a transaction so that I can specify the isolation level. Once the query is complete, what should I do? * Commit the transaction * Rollback the transaction * Do nothing (which will cause the transaction to be rolled back at the end of the using block) What are the implications...
You commit. Period. There's no other sensible alternative. If you started a transaction, you should close it. Committing releases any locks you may have had, and is equally sensible with ReadUncommitted or Serializable isolation levels. Relying on implicit rollback - while perhaps technically equivalent - is just poor ...
If you haven't changed anything, then you can use either a COMMIT or a ROLLBACK. Either one will release any read locks you have acquired and since you haven't made any other changes, they will be equivalent.
Should I commit or rollback a read transaction?
[ "", "sql", "database", "transactions", "" ]
I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.
Just put this in the first line of your script : ``` #!/usr/bin/env python ``` Make the file executable with ``` chmod +x myfile.py ``` Execute with ``` ./myfile.py ```
If you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or [PyInstaller](http://www.pyinstaller.org/).
What do I use on linux to make a python program executable
[ "", "python", "linux", "file-permissions", "" ]
At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)
I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be han...
Reason one: Need to catch specific stuff. If calling code needs to deal with a specific exceptional condition, you need to differentiate your Exception, and Java differentiates exceptions with different types, so you need to write your own. Basically, if someone has to write: ``` catch(ExistingException e) { if({c...
java.lang.Exception vs. rolling your own exception
[ "", "java", "exception", "class", "packaging", "" ]
I have a suspicion that I'm using the `finally` block incorrectly, and that I don't understand the fundamentals of its purpose... ``` function myFunc() { try { if (true) { throw "An error"; } } catch (e) { alert (e); return false; } finally...
> The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles...
Finally blocks execute when you leave the try block. In your code this happens when you return false. That sets the return value to false and attempts to exit the function. But first it has to exit the try block which triggers the finally and overwrites the return value to true. It is considered by many to be a good p...
Javascript error handling with try .. catch .. finally
[ "", "javascript", "error-handling", "finally", "" ]
MS SQL has a convenient workaround for concatenating a column value from multiple rows into one value: ``` SELECT col1 FROM table1 WHERE col2 = 'x' ORDER by col3 FOR XML path('') ``` and that returns a nice recordset: ``` XML_F52E2B61-18A1-11d1-B105-00805F49916B -------------...
That should do: ``` select( SELECT col1 FROM table1 WHERE col2 = 'x' ORDER by col3 FOR XML path('') ) as myName ``` Not pretty but should give the result that you need
Try this... ``` select ( select '@greeting' = 'hello', '@where' = 'there', '@who' = 'world' for xml path ('salutation'), type ) as 'MyName' ``` Note: If you omit the "type" after the "for xml", you get *(I think)* a string.
How to choose returned column name in a SELECT FOR XML query?
[ "", "sql", "sql-server", "xml", "sql-server-2005", "" ]
## Background I am working on a legacy small-business automation system (inventory, sales, procurement, etc.) that has a single database hosted by SQL Server 2005 and a bunch of client applications. The main client (used by all users) is an MS Access 2003 application (ADP), and other clients include various VB/VBA app...
When designing a database, I prefer the following: * no direct table access by the code (but is ok from stored procedures and views and functions) * a base view for each table that includes all columns * an extended view for each table that includes lookup columns (types, statuses, etc.) * stored procedures for all up...
You won't notice any performance impact for one-table views; SQL Server will use the underlying table when building the execution plans for any code using those views. I recommend you schema-bind those views, to avoid accidentally changing the underlying table without changing the view (think of the poor next guy.) > ...
SQL Server 2005: Wrapping Tables by Views - Pros and Cons
[ "", "sql", "sql-server", "database", "refactoring", "" ]
Since there is no `finally` in C++ [you have to use the RAII](http://www.research.att.com/~bs/bs_faq2.html#finally) design pattern instead, if you want your code to be exception safe. One way to do this is by using the destructor of a local class like this: ``` void foo() { struct Finally { ~Finally() { /*...
Instead of defining `struct Finally`, you could extract your cleanup code in a function of the class `Task` and use Loki's [ScopeGuard](http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer). ``` ScopeGuard guard = MakeGuard(&Task::cleanup, task); ``` See also this [DrDobb's article](http://www.ddj.com...
I don't think there is a cleaner way to achieve what you're trying to do, but I think the main problem with the 'finally approach' in your example is an improper [separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns). E.g. the function foo() is responsible for the Task object's consistency, this...
Proper replacement for the missing 'finally' in C++
[ "", "c++", "exception", "finally", "c++-faq", "" ]
I have some function to find a value: ``` struct FindPredicate { FindPredicate(const SomeType& t) : _t(t) { } bool operator()(SomeType& t) { return t == _t; } private: const SomeType& _t; }; bool ContainsValue(std::vector<SomeType>& v, SomeType& valueToFind) { return find_if(v.begin(),...
The best solution is to use the [STL functional library](http://www.keithschwarz.com/cs106l/fall2007/handouts/200_STL_Functional_Library.pdf). By deriving your predicate from `unary_function<SomeType, bool>` , you'll then be able to use the `not1` function, which does precisely what you need (i.e. negating a unary pred...
See the std library functor [not1](http://www.cplusplus.com/reference/misc/functional/not1.html), it returns a functor that is the logical not of whatever the functor you give it would return. You should be able to do something like: ``` bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind) { return fi...
How can I negate a functor in C++ (STL)?
[ "", "algorithm", "stl", "c++", "" ]
I ran into an interesting behavior recently. It seems that if I override .equals() to take a parameter other than Object, it doesn't get called. Can anyone explain to me why this is happening? It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something. Here's much simpler code that sh...
You're mixing up "overriding" and "overloading". Overriding -- adding a replacement definition of an existing method for purposes of polymorphism. The method must have the same signature. The signature consists of the name and argument types. Overridden methods are selected at runtime based on the runtime type of the ...
equals(Object) is overriding a super method; you can *not* override a super method without using the exact same signature (Well, there are some exceptions like covariant returntypes and exception).
When overriding equals in Java, why does it not work to use a parameter other than Object?
[ "", "java", "overloading", "" ]
Recently I was trying to make a calendar application that will display the current year-month-date to the user. The problem is, if the user is gonna keep my application running even for the next day, how do I get notified ?? How shall I change the date displayed ? I don't wanna poll the current date to update it. Is th...
Can you simply work out the number of seconds until midnight, and then sleep for that long?
@OddThinking's answer will work (you could set a timer for the interval instead of sleeping). Another way would be to set a timer with a 1 minute interval and simply check if the system date has changed. Since you are only executing some lightweight code once a minute, I doubt the overhead would be noticable.
Getting notified when the datetime changes in c#
[ "", "c#", "events", "datetime", "systemevent", "" ]
When editing really long code blocks (which should definitely be refactored anyway, but that's beyond the scope of this question), I often long for the ability to collapse statement blocks like one can collapse function blocks. That is to say, it would be great if the minus icon appeared on the code outline for everyth...
Starting with Visual Studio 2017, statement collapsing is built-in. There are several extensions that perform this task for pre-2017 versions of VS, starting with VS 2010 version: * [C# outline](http://visualstudiogallery.msdn.microsoft.com/4d7e74d7-3d71-4ee5-9ac8-04b76e411ea8) * [C# outline 2012 (@MSDN)](https://v...
I'm not aware of add-ins, but you mentioned regions and I see nothing wrong with doing something like this... ``` foreach (Item i in Items) { #region something big happening here ... #endregion #region something big happening here too ... #endregion #region something big happening here also ... #en...
Visual Studio C# statement collapsing
[ "", "c#", "visual-studio", "" ]
I have a `vector` that I want to insert into a `set`. This is one of three different calls (the other two are more complex, involving `boost::lambda::if_()`), but solving this simple case will help me solve the others. ``` std::vector<std::string> s_vector; std::set<std::string> s_set; std::for_each(s_vector.begin(), ...
> The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads. You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use: ``` typedef std::set<std::string> s_type; typedef std::pai...
I would use a for-loop :-D
Boost.Lambda: Insert into a different data structure
[ "", "c++", "boost-lambda", "" ]
I am trying to make the [Validation plugin](http://docs.jquery.com/Plugins/Validation) work. It works fine for individual fields, but when I try to include the demo code for the error container that contains all of the errors, I have an issue. The problem is that it shows the container with all errors when I am in all ...
You will find the documentation for the meta option in <http://docs.jquery.com/Plugins/Validation/validate#toptions> If you want to display the errors beside the inputs **AND** in a separate error container you will need to override the `errorPlacement` callback. From your example: ``` ... courri...
First your container should be using an ID instead of a class.. (I'm going to assume that ID is 'containererreurtotal') Then Try this.. ``` $().ready(function() { $('div#containererreurtotal').hide(); // validate signup form on keyup and submit $("#frmEnregistrer").validate({ ...
How to display jQuery Validation error container only on submit
[ "", "javascript", "jquery", "" ]
Lists in C# have the `.ToArray()` method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back. I am using the `String.Split` method in the .NET 2.0 environment, so LINQ, etc. is not available to me.
``` string s = ... new List<string>(s.Split(....)); ```
In .Net 3.5, the `System.Linq` namespace includes an extension method called `ToList<>()`.
string.split returns a string[] I want a List<string> is there a one liner to convert an array to a list?
[ "", "c#", "arrays", "generics", "list", "" ]
I have two PHP files that I need to link. How can I link the files together using PHP? The effect I want is to have the user click a button, some information is proccessed on the page, and then the result is displayed in a different page, depending on the button the user clicked.Thanks
I've interpreted your question differently to the others. It sounds to me like you want to create a page with two buttons on it and execute one of your two existing PHP files, depending on which button was pressed. If that's right, then here's a simple skeleton to achieve that. In this example, page\_1.php and page\_...
It sounds like you might want an HTML form: ``` <form method="post" action="other_file.php"> <input name="foo" type="..."... /> ... </form> ``` Then `$_POST["foo"]` will contain the value of that input in other\_file.php.
How do I link files in PHP?
[ "", "php", "" ]
This is a question that was sparked by [Rob Walker](https://stackoverflow.com/users/3631/rob-walker)'s answer [here](https://stackoverflow.com/questions/36455/alignment-restrictions-for-mallocfree#36466). Suppose I declare a class/struct like so: ``` struct { char A; int B; char C; int D; }; ``` Is ...
C99 §6.7.2.1 clause 13 states: > Within a structure object, the > non-bit-field members and the units in > which bit-fields reside have addresses > that increase in the order in which > they are declared. and goes on to say a bit more about padding and addresses. The C89 equivalent section is §6.5.2.1. C++ is a bit mo...
The data members are arranged in the order declared. The compiler is free to intersperse padding to arrange the memory alignment it likes (and you'll find that many compilers have a boatload a alignment specification options---useful if mixing bits compiled by different programs.). See also [Why doesn't GCC optimize s...
Do class/struct members always get created in memory in the order they were declared?
[ "", "c++", "memory", "memory-alignment", "" ]
I've got a question about references between projects in a solution. Most of my previous applications have just had one or two projects in the Solution, but this time I want to divide the application further. I'm starting a new Solution in Visual Studio 2008 now, and have created several underlying projects to divide ...
Indeed you can't have circular references, but to be honest what would be the benefit of splitting the solution into small project if you had interdependencies between all of them? Usually before I even open Visual Studio I take a piece of paper and split my problem into logical functional areas. You can draw a Utilit...
It's a bit old-fashioned, but for help in deciding how to split into projects, you could look up "Coupling" and "Cohesion" in wikipedia. Also, while we sometimes think of these decisions as "style" rather than "substance", we should remember that assembly boundaries do have meaning, both to the compiler and to the run...
Rules of thumb for adding references between C# projects?
[ "", "c#", "visual-studio", "" ]
I have following situation: I have loged user, standard authentication with DB table ``` $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter()); $authAdapter->setTableName('users'); $authAdapter->setIdentityColumn('user_name'); $authAdapter->setCredentialColumn('password'); ``` When user ...
Your best bet would be to not use Zend\_Auth's storage to hold information that's likely to change - by default it only holds the identity (for good reason). I'd probably make a User class that wrapped all the Auth, ACL (and probably profile) functionality that uses a static get\_current() method to load the user stash...
``` $user = Zend_Auth::getInstance()->getIdentity(); $user->newValue = 'new value'; ``` Assuming you are updating the session data in the same statement you are updating the database in there is no need to call the db again.
Updating Zend_Auth_Storage after edit users profile
[ "", "php", "zend-framework", "authentication", "zend-auth", "" ]
I'm trying to read the data in a Win32 ListView owned by another process. Unfortunately, my WriteProcessMemory() call fails with the error "This function is not supported on this system." when I specify "NULL" for the base address in my VirtualAlloc() call. If, however, I offset that VirtualAlloc() address by some "mag...
Instead of trying to allocate memory in another process, why not use named shared memory instead. This article will take you through the basic setup of [shared memory](http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx), and I did a quick check to make sure these functions are supported by [Windows Mobile 5](...
VirtualAlloc allocates memory in **YOUR** address space. It is absolutely not valid to use that address when writing the memory space of another process. You should be using [VirualAllocEx](http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx) instead and passing in the hProcess. You are just getting lucky and...
Win32 WriteProcessMemory() magical offset value
[ "", "c++", "winapi", "visual-c++", "virtualalloc", "" ]
In my application I have a number of panes from m\_wndspliter classes. What I want to do is at run time show and hide one of these panes. Whilst with the following code I can show and hide the view associated with the pane, I can't temporarily remove the pane itself. ``` CWnd * pCurView = m_wndSplitter2.GetPane(2, 0);...
Does this help? <http://www.codeguru.com/cpp/w-d/splitter/article.php/c1543> I have used something very similar myself,
You need to call CSplitterWnd::DeleteView to do this, which basically means that you have to save your CView elsewhere if you intend to restore it. Usually this is not a problem as all data should be stored in the CDocument rather than CView, but in practice this may not be the case. The way I have handled this in the...
MFC: Showing / Hiding Splitter Panes
[ "", "c++", "windows", "winapi", "mfc", "csplitterwnd", "" ]
I'm looking for a script or application that tidies up and reformats SQL queries. I've found some good online SQL formatters (see [here](http://www.wangz.net/gsqlparser/sqlpp/sqlformat.htm)) , as well as some downloadable commercial applications. I'm cautious about using an online service as I don't want to risk copies...
Some things to try out (SQLinForm is free until 2009). It's weird how some niches totally lack good open source tools. <http://www.trialpay.com/checkout/?c=bb7014d&tid=6rGUpGo> <http://www.sqlinform.com> <http://www.fileheap.com/software-universal-sql-editor-download-11096.html> An Emacs macro: <http://www.emacswi...
Something else... this freeware tool works for PL/SQL, so maybe there's a use for that in there. PL/SQL Tidy (Broken Link)
Free Software or Scripts for Formatting SQL Queries
[ "", "sql", "code-formatting", "" ]
I'm in javascript, running this in the console ``` d = new Date(); d.setMonth(1); d.setFullYear(2009); d.setDate(15); d.toString(); ``` outputs this: ``` "Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)" ``` Why would this be happening? It seems like a browser bug.
That's because when you initialize a new Date, it comes with today's date, so today is Oct 30 2008, then you set the month to February, so there is no February 30, so set first the day, then the month, and then the year: ``` d = new Date(); d.setDate(15); d.setMonth(1); d.setFullYear(2009); ``` Bu...
It's probably best to construct a Date object in one step to avoid the Date object being in an ambiguous or invalid state: ``` d = new Date(2009, 1, 15); ```
The fifteenth of February isn't found
[ "", "javascript", "date", "" ]
I've got a database with three tables: Books (with book details, PK is CopyID), Keywords (list of keywords, PK is ID) and KeywordsLink which is the many-many link table between Books and Keywords with the fields ID, BookID and KeywordID. I'm trying to make an advanced search form in my app where you can search on vari...
What you've done here is made a cartesian result set by having the tables joined with the commas but not having any join criteria. Switch your statements to use outer join statements and that should allow you to reference the keywords. I don't know your schema, but maybe something like this would work: ``` SELECT *...
You need to join the 3 tables together, which gives you a tablular resultset. You can then check any columns you like, and make sure you get *distinct* results (i.e. no duplicates). Like this: ``` select distinct b.* from books b left join keywordslink kl on kl.bookid = b.bookid left join keywords k on kl.keywordid =...
SELECT with ORs including table joins
[ "", "sql", "" ]
We are logging any exceptions that happen in our system by writing the Exception.Message to a file. However, they are written in the culture of the client. And Turkish errors don't mean a lot to me. So how can we log any error messages in English without changing the users culture?
This issue can be partially worked around. The Framework exception code loads the error messages from its resources, based on the current thread locale. In the case of some exceptions, this happens at the time the Message property is accessed. For those exceptions, you can obtain the full US English version of the mes...
A contentious point perhaps, but instead of setting the culture to `en-US`, you can set it to `Invariant`. In the `Invariant` culture, the error messages are in English. ``` Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; ``` It...
Exception messages in English?
[ "", "c#", ".net", "exception", "localization", "" ]
I have a class library with all my database logic. My DAL/BLL. I have a few web projects which will use the same database and classes, so I thought it was a good idea to abstract the data layer into its own project. However, when it comes to adding functionality to classes for certain projects I want to add methods t...
You can't write a partial class across projects. A partial class is a compile-time-only piece of syntactic sugar - the whole type ends up in a single assembly, i.e. one project. (Your original DAL file would have to declare the class to be partial as well, by the way.)
Using Visual Studio 2015 and later **it is possible** to split partial classes across projects: use [shared projects](https://stackoverflow.com/q/30634753/814206 "What is the difference between a Shared Project and a Class Library in Visual Studio 2015? - Stack Overflow") (see also [this MSDN blog](https://blogs.msdn.m...
Should you use a partial class across projects?
[ "", "c#", "partial-classes", "" ]
Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails): ``` jQuery.ajax({ type: "GET", ...
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design. After searching their bug tracker, there's [a patch](http://dev.jquery.com/attachment/ticket/3442/jsonabort.patch) which may be a possible solution using ...
[Here](https://stackoverflow.com/a/19075640/2314737)'s my extensive answer to a similar question. Here's the code: ``` jQuery.getJSON(handlerURL + "&callback=?", function(jsonResult){ alert("Success!"); }) .done(function() { alert('getJSON request succeeded!'); }) .fail(function(jqXHR, textStatus, er...
How do I catch jQuery $.getJSON (or $.ajax with datatype set to 'jsonp') error when using JSONP?
[ "", "javascript", "jquery", "jsonp", "" ]
What on earth is a caret in the context of a CSplitterWnd class? I can't find any documentation relating explicitly to CSplitterWnds... EDIT: Specifically, what do these functions *actually* do: ``` CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); pCurView->ShowCaret() pCurView->HideCaret() ``` EDIT2: Please note, I ...
Any CWnd can have a caret, but only CWnd inheritors that CreateCaret first actually display one. @DannySmurf gives you one example - CEditView - of a CView that creates a caret that you can show and hide. Depending on the specific kind of CView you've got on your pane, ShowCaret is probably irrelevant. It has nothing ...
Specifically; ``` CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); ``` Get a pane, as in a CView derived class, surrounded by your splitter window ``` pCurView->ShowCaret() ``` Show the littler vertical bar at the text editing position in that view. This is the cursor used in any text editing control such as a CEdit...
MFC: What on earth is a CSplitterWnd Caret?
[ "", "c++", "mfc", "caret", "cwnd", "" ]
I need to avoid being vulnerable to SQL injection in my ASP.NET application. How might I accomplish this?
Even though your question is very generic, a few rules always apply: * Use parameterized queries (`SqlCommand` with `SqlParameter`) and put user input into parameters. * Don't build SQL strings out of unchecked user input. * Don't assume you can build a sanitizing routine that can check user input for every kind of ma...
Use parameters! It really is that simple :-) Create your queries like this (for MS Sql server with C#): ``` SqlCommand getPersons = new SqlCommand("SELECT * FROM Table WHERE Name = @Name", conn); ``` Here @Name is the parameter where you want to avoid sql injection and conn is an SqlConnection object. Then to add th...
How can I avoid SQL injection attacks in my ASP.NET application?
[ "", ".net", "asp.net", "sql", "security", "sql-injection", "" ]
In C#, I am using a library that defines an enum. I would like to allow consumers of my code (in a different assembly) to pass in an enum value as a parameter to one of my functions without having to reference the underlying library themselves. Is there a way for me to expose the library's enumeration to my consumers?
You could define your own enum with the values you want to support, expose that to your consumers, and simply convert it to the library's enum before you call into it. Since enums are just numbers behind the scenes, it's easy to convert one enum's values to another's.
You can offer an overload that takes an int, describe which values are valid, then perform the cast yourself. Alternatively, you can offer a different enumeration in your library, then convert it before calling into the second library.
Exposing an enum from a library class
[ "", "c#", ".net", "oop", "enums", "" ]
I have to call ping from c++ code.I'd like to easily read the output for further utilizations. I have come up with two solutions: * use a fork and a pipe, redirect ping output to the pipe and then parse it * find a library suited for the purpose to use a ping(ip\_addresss) function directly I'd like the latter but i...
I would go with your first option. Linux is built around the concept of having small, specialized apps which do one thing really well, communicating with pipes. Your app shouldn't include a library to implement ping, since there is already a built-in command to do it, and it works very well!
From the educational point of view invoking an external binary is very **inadvisable**. Especially for a simple task such as sending an ICMP echo request, you should learn a bit of socket.
What is the best method to ping in c++ under linux?
[ "", "c++", "linux", "" ]
While working on an existing project I suddenly got the following error when trying to compile the solution: *error MSB3105: The item "[filename]" was specified more than once in the "Resources" parameter. Duplicate items are not supported by the "Resources" parameter.* Now, as far as I'm aware, I did not make any ch...
Did you try showing all files in the Solution Explorer? You could have a duplicate .rsx file somewhere in there.
I found the answer in [.NET forum posting](http://archives.devshed.com/forums/net-206/main-form-and-partial-class-1918921.html) by Roy Green, and Theresa was right after all, though I did not recognize it. If you have your main form class split up into partial classes, the partial sections end up in the solution expl...
What could cause Visual Studio / C# error MSB3105: Duplicate resources
[ "", "c#", "visual-studio", "" ]
What regex pattern would need I to pass to `java.lang.String.split()` to split a String into an Array of substrings using all whitespace characters (`' '`, `'\t'`, `'\n'`, etc.) as delimiters?
Something in the lines of ``` myString.split("\\s+"); ``` This groups all white spaces as a delimiter. So if I have the string: ``` "Hello[space character][tab character]World" ``` This should yield the strings `"Hello"` and `"World"` and omit the empty space between the `[space]` and the `[tab]`. As VonC pointed...
In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember: `\w` - Matches any word character. `\W` - Matches any nonword character. `\s` - Matches any white-space character. `\S` - Matches anything but white-space characters. `\d` ...
How to split a string with any whitespace chars as delimiters
[ "", "java", "string", "whitespace", "split", "" ]
I'm trying to build a console application without using the CRT, or any other imports than kernel32.lib in any case. I get my code to compile, but can't wrap the linker around a few problems: ``` unresolved external symbol @__security_check_cookie@4 unresolved external symbol "int __cdecl FreeLibrary(void *)" (?FreeLi...
\_wmainCRTStartup is the function that calls wmain() IIRC it should be available in some .o file that you can link with, look in your lib directory. Maybe this is useful reading too: [Reduce EXE and DLL Size with LIBCTINY.LIB](http://msdn.microsoft.com/en-us/magazine/cc301696.aspx) (and Matt Pietrek rocks :-)
Well, answering myself here to sum up, in case someone else finds this page looking for info. As MSalters advised, the security cookie code can be stolen from the CRT source, but doing that I found that the `/GS-` compiler flag can be used to avoid the security stuff altogether. As SoapBox said, the API functions nee...
Building console apps without CRT & default headers?
[ "", "c++", "windows", "visual-studio-2008", "visual-c++", "" ]
So lets say I'm using Python's [ftplib](http://www.python.org/doc/2.5.2/lib/module-ftplib.html) to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.
Using retrlines() probably isn't the best idea there, since it just prints to the console and so you'd have to do tricky things to even get at that output. A likely better bet would be to use the nlst() method, which returns exactly what you want: a list of the file names.
## This best answer You may want to use `ftp.nlst()` instead of `ftp.retrlines()`. It will give you exactly what you want. If you can't, read the following : ## Generators for sysadmin processes In his now famous review, [Generator Tricks For Systems Programmers An Introduction](http://www.dabeaz.com/generators/Gen...
How do I parse a listing of files to get just the filenames in Python?
[ "", "python", "parsing", "scripting", "ftp", "ftplib", "" ]
Here's the scenario. I'm debugging my own app (C/C++) which is using some library developed by another team in the company. An assertion fails when my code generates some edge case. Its a pain because the assertion is not formulated correctly so the library function is working OK but I get all these interruptions where...
If the code is triggering breakpoints on its own (by \_\_debugbreak or int 3), you cannot use conditional breakpoints, as the breakpoints are not know to Visual Studio at all. However, you may be able to disable any such breakpoints you are not interested in by modifying the code from the debugger. Probably not what yo...
There's no good way to automatically ignore ASSERT() failures in a debug library. If that's the one you have to use, you're just going to have to convince the other team that this needs fixed now, or if you have the source for this library, you could fix or remove the assertions yourself just to get your work done in t...
Can I set Visual Studio 2005 to ignore assertions in a specific region of code while debugging
[ "", "c++", "c", "debugging", "visual-studio-2005", "assert", "" ]
We are experiencing some slowdowns on our web-app deployed on a Tomcat 5.5.17 running on a Sun VM 1.5.0\_06-b05 and our hosting company doesn't gives enough data to find the problem. We are considering installing [lambda probe](http://www.lambdaprobe.org) on the production server but it requires to enable JMX (com.sun...
You can cross out security flaws by using secure authentication. Just keeping the JMX service ready does not incur any significant overhead and is generally a good idea. There's a benchmark [here](http://weblogs.java.net/blog/emcmanus/archive/2006/07/how_much_does_i.html) about this.
The overhead from JMX is low and you can fix the security by úsing SSL and authentication. Set -Dcom.sun.management.jmxremote.ssl=true and -Dcom.sun.management.jmxremote.authenticate=true See here for [here](http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html) for more information about setting up certific...
Is a good idea to enable jmx (lambda probe) on a production server?
[ "", "java", "performance", "security", "tomcat", "jmx", "" ]
I have a incoming stream of bytes (unsigned char) from either a file or network. I need this data placed in a class, and is looking for a NET-way of doing this. I bet some does this all the time, so I guess there is a better method to do this than using BitConverter. I realize I supplied too litle information. Let me...
As Jon mentioned, it's not clear, what you need. Maybe you are talking about maybe it is [Binary serialization](http://msdn.microsoft.com/en-us/library/72hyey7b(VS.71).aspx) what you are looking for?
It's not entirely clear what you mean, but if you're basically looking for a way to buffer the data so you can get at it later, [MemoryStream](http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx) is probably your best bet. Write all your data to it, then set [Position](http://msdn.microsoft.com/en-us/li...
Char array to a class
[ "", ".net", "c++", "managed", "" ]
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following: ``` import os os.environ["FOO"] = "A_Value" ``` When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way...
No process can change its parent process (or any other existing process' environment). You can, however, create a new environment by creating a new interactive shell with the modified environment. You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout...
I would use the bash eval statement, and have the python script output the shell code child.py: ``` #!/usr/bin/env python print 'FOO="A_Value"' ``` parent.sh ``` #!/bin/bash eval `./child.py` ```
Is it possible to change the Environment of a parent process in Python?
[ "", "python", "linux", "environment", "" ]
I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?
[GNU make](https://make.mad-scientist.net/papers/advanced-auto-dependency-generation/#combine)'s documentation provides a good solution. Absolutely. `g++ -MM <your file>` will generate a GMake compatible list of dependencies. I use something like this: ``` # Add .d to Make's recognized suffixes. SUFFIXES += .d #We d...
Having now read [this portion in particular](http://make.paulandlesley.org/autodep.html#combine) I think there is a much easier solution out there, as long as you have a reasonably up to date version of gcc/g++. If you just add `-MMD` to your `CFLAGS`, define a variable `OBJS` representing all your object files, and th...
generate dependencies for a makefile for a project in C/C++
[ "", "c++", "c", "makefile", "dependencies", "" ]
I am working on localization for an app where custom patterns are used to format the date-time. one example is: dd-MM HH:mm I need to get localized versions of this custom format for dates, so that I get the date using numbers, and the time, basically using the local order (dd MM or MM dd) and the local seperator for...
Look at the DateTimeFormatInfo class (CultureInfo.DateTimeFormat property), in particular the properties DateSeparator, TimeSeparator, ShortDatePattern.
Perhaps you could try this: ``` DateTime.Now.ToString(new System.Globalization.CultureInfo(Thread.CurrentThread.CurrentCulture.Name)); ``` If i want for example to display the time for a particular culture, i would do this: ``` DateTime.Now.ToString(new System.Globalization.CultureInfo("ES-es")) ``` The cultureinfo...
Localization of date-time using custom patterns
[ "", "c#", "datetime", "localization", "" ]
I've been a Delphi (D7) developer for many sometime already, I've always been wondering about the .NET + C# stuffs. What I mean are about not the "Delphi for .NET" or "Oxygene" tech/plugin, but clean .NET/C#. How much different is it from Delphi? And some other questions... * Is Mono/SharpDevelop (any others that I s...
Re the first point: have you tried the (free) [VIsual Studio Express Edition](http://www.microsoft.com/Express/)? For a lot of things, this is perfectly capable. You just don't get as many helpers / designers, and no plug-in support (for IDE extensions). Re the second: excluding some [nasty tricks](http://www.yoda.ara...
As an addition to Marc's answer, these were the minor pleasant surprises during my transition from D6 to C#: * better OOP, no global variables ("var MainForm: TMainForm" and the like) * everything is strongly typed (in general, you can have no pointer types) * with Windows Forms, the "textual .dfm file" (here YourForm...
Delphi to .NET + C#
[ "", "c#", ".net", "delphi", "" ]
std::next\_permutation (and std::prev\_permutation) permute all values in the range `[first, last)` given for a total of n! permutations (assuming that all elements are unique). is it possible to write a function like this: ``` template<class Iter> bool next_permutation(Iter first, Iter last, Iter choice_last); ``` ...
To iterate over nPk permutations, I've used the `for_each_permutation()` algorithm presented in [this old CUJ article](http://www.ddj.com/cpp/184401912) before. It uses a nice algorithm from Knuth which rotates the elements in situ, leaving them in the original order at the end. Therefore, it meets your no external mem...
Source code for a Java combination generator is at **<http://www.merriampark.com/comb.htm>**. Strip out the Java idioms, and it's almost exactly what you're looking for, implemented as a generator to keep a lid on your memory usage. --- This problem is from the mathematical field known as **Combinatorics**, which is ...
Is it possible to write a function like next_permutation but that only permutes r values, instead of n?
[ "", "c++", "algorithm", "" ]
I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints o...
Assuming that the file type is registered with Excel, you could call ShellExecute() on the file, using the "open" verb. This will cause the file to be opened as if double clicked by the user in Explorer and will invoke Excel. If that isn't the case, and you can assume that Excel is installed, you could instead pass "e...
Thanks, Andy. I am using ShellExecute() as you suggested, giving Excel as the application and the path of the file as the parameter. It works to open Excel, however, it cannot seem to find the file. I have tried moving the file around, typing in the entire path, part of the path with no change. Here is the code I use: ...
Open a Specified File in Excel from a GUI - Borland C++
[ "", "c++", "excel", "c++builder", "" ]
I want to be replace any occurrence of more than one space with a single space, but take no action in text between quotes. Is there any way of doing this with a Java regex? If so, can you please attempt it or give me a hint?
Here's another approach, that uses a lookahead to determine that all quotation marks after the current position come in matched pairs. ``` text = text.replaceAll(" ++(?=(?:[^\"]*+\"[^\"]*+\")*+[^\"]*+$)", " "); ``` If needed, the lookahead can be adapted to handle escaped quotation marks inside the quoted sections.
When trying to match something that can be contained within something else, it can be helpful to construct a regular expression that matches both, like this: ``` ("[^"\\]*(?:\\.[^"\\]*)*")|( +) ``` This will match a quoted string or two or more spaces. Because the two expressions are combined, it will match a quoted...
Regex Question - One or more spaces outside of a quote enclosed block of text
[ "", "java", "regex", "quotes", "" ]
A problem I've encountered a few time in my career is in a tiered service architecture a single downstream system can bring down the entire client application if it gets into a state where all its threads are consumed on a deadlock or some sort of infinite loop bug in that system. Under these conditions the server sock...
You are correct in that the MDB case is the normal solution, and it typically supports timeouts as well which will help keep from hanging requests. That being said, it may not really fix the problem but just shift the backup to your JMS queue without responses ever being sent back to the client. Of course if only 1 of ...
We use MDBs where the queue is persisted in a database which has the benefit of messages not being lost if the system goes down. You may also want to establish an asynchronous contract between the participating parties. What I mean by this is that a client will send you a message and rather than you doing a lot of hea...
Long Transaction Time Solution for Java EE?
[ "", "java", "web-services", "multithreading", "jakarta-ee", "transactions", "" ]
I have an application that needs to hit the ActiveDirectory to get user permission/roles on startup of the app, and persist throughout. I don't want to hit AD on every form to recheck the user's permissions, so I'd like the user's role and possibly other data on the logged-in user to be globally available on any form ...
Set [Thread.CurrentPrincipal](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx) with either the [WindowsPrincipal](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal.aspx), a [GenericPrincipal](http://msdn.microsoft.com/en-us/library/system.security.p...
Maybe my judgement is clouded by my frequent use of javascript, but I think that if you have something that is **meant** to be global, then using global variables is okay. Global is bad when you are exposing things globally that shouldn't be. Global is okay if it is semantically correct for the intended use of the dat...
Storing static user data in a C# windows application
[ "", "c#", "singleton", "global-variables", "" ]
**Problem Statement:** I would like to create an offline database to lookup prices/info on the n most useful books to sell in the United States (where n is probably 3 million or so). **Question:** So, my question is (and I am open to other approaches here as well), I am trying to figure out how to use Amazon AWS to do...
Amazon has a data feed service you can use which contains GZipped xml files of all their products based on top level categories. It's updated once a day and totals about 20GB/110GB of compressed/uncompressed data. Since you only need books it's more in the area of 4GB/31GB. The only thing is I'm not sure who's able to ...
Take a look at [AWS Zone](http://www.awszone.com/index.aws), in the `Amazon E-Commerce Service` section.
Using Amazon AWS to create an offline database
[ "", "c#", ".net", "ruby", "amazon-web-services", "" ]
Simple yes or no question, and I'm 90% sure that it is no... but I'm not sure. Can a Base64 string contain tabs?
It depends on what you're asking. If you are asking whether or not tabs can be base-64 encoded, then the answer is "yes" since they can be treated the same as any other ASCII character. However, if you are asking whether or not base-64 output can contain tabs, then the answer is no. The following link is for an articl...
The short answer is no - but Base64 cannot contain carriage returns either. That is why, if you have multiple lines of Base64, you strip out any carriage returns, line feeds, and anything else that is not in the Base64 alphabet That includes tabs.
Can a Base64 String contain tabs?
[ "", "c#", ".net", "base64", "" ]
I've got a Windows Forms application with two ListBox controls on the same form. They both have their SelectionMode set to 'MultiExtended'. When I change the selection of one the selection of the other changes. Now I thought I'd done something stupid with my SelectedIndexChanged handlers so I removed them and re-wrot...
It isn't the *list* that stores the current position - it is the `CurrencyManager`. Any controls (with the same `BindingContext`) with the *same reference* as a `DataSource` will share a `CurrencyManager`. By using different list instances you get different `CurrencyManager` instances, and thus separate position. You ...
I believe that your two controls are sharing a CurrencyManager. I'm not sure exactly why. As a workaround, you could try just populating your listboxes with simple strings. Or you may want to try creating separate instances of the BindingSource component, and bind to those.
Changing a ListBox selection changes other ListBox's selection. What's going on?
[ "", "c#", ".net", "winforms", "data-binding", "" ]
We are seeing this error in a Winform application. Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening. ``` System.ComponentModel.Win32Exception: Error creating window handle. at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp) at System.W...
Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large....
The windows handle limit for your application is 10,000 handles. You're getting the error because your program is creating too many handles. You'll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you're calling the dispose metho...
Winforms issue - Error creating window handle
[ "", "c#", "windows", "winforms", "window-handles", "" ]
How do you modify a propertygrid at runtime in every way? I want to be able to add and remove properties and add "dynamic types", what I mean with that is a type that result in a runtime generated dropdown in the propertygrid using a TypeConverter. I have actually been able to do both those things (add/remove properti...
What you do, is adding StatesList (a TypeConverter) as a property. What you should do, is adding a property with StatesList as its TypeConverter.
Ah, of course! ``` myProperties.Add(new CustomProperty("Custom", "", typeof(States), false, true)); [TypeConverter(typeof(StatesList))] public class States { } ``` Works like a charm, thank you! I have updated my project, hope it can be helpful to others, it can be found [here](http://helgo.net/salle/misc/DynamicPr...
How to modify PropertyGrid at runtime (add/remove property and dynamic types/enums)
[ "", "c#", ".net", "winforms", "propertygrid", "" ]
I am doing 2^1000 and I am getting this: 1.07151e+301 Is there any way to actually turn this into a proper number without the e+301, or at least can anyone show me where I can see how to turn this in to a real number, by some way working with the e+301 part?
So, I'm thinking that what you really want is just the ability to print it without scientific notation. If you're using `printf`, what you want is: ``` printf( "%f1000.0", value ); // note that 1000 is way larger than need be, // I'm just too lazy to count the digits ``` With `cout`, try something like: ``` cout.set...
There is a practical limit to how large a number that can be directly manipulated in machine registers can be. if you are using double precision floats there are a total of 64 bits, some of which are devoted to the mantissa, some to the exponent, and 1 to the sign bit. 2^1000 needs a 1001 bit integer to be represented...
How do I avoid scientific notation for large numbers?
[ "", "c++", "math", "" ]
Consider the following two alternatives: * `console.log("double");` * `console.log('single');` The former uses double quotes around the string, whereas the latter uses single quotes around the string. I see more and more JavaScript libraries out there using single quotes when handling strings. Are these two usages ...
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string. Using the other type of quote as a literal: ``` alert('Say "Hello"'); alert("Say 'Hello'"); ``` This can get complicated: ``` ...
If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.
Are double and single quotes interchangeable in JavaScript?
[ "", "javascript", "string", "" ]
If you create a class library that uses things from other assemblies, is it possible to embed those other assemblies inside the class library as some kind of resource? I.e. instead of having *MyAssembly.dll*, *SomeAssembly1.dll* and *SomeAssembly2.dll* sitting on the file system, those other two files get bundled in t...
Take a look at **[ILMerge](http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-b4ad-4eae-87cf-b14ae6a939b0&displaylang=en)** for merging assemblies. > I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET? Yes. > Are all .NET assemblies DLLs, Either ...
ILMerge does merge assemblies, which is nice, but sometimes not quite what you want. For example, when the assembly in question is a strongly-named assembly, and you don't have the key for it, then you cannot do ILMerge without breaking that signature. Which means you have to deploy multiple assemblies. As an alternat...
Embedding assemblies inside another assembly
[ "", "c#", ".net", "dll", "assemblies", "" ]
I want to do something like this : ``` myYear = record.GetValueOrNull<int?>("myYear"), ``` Notice the nullable type as the generic parameter. Since the `GetValueOrNull` function could return null my first attempt was this: ``` public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName) where T ...
Change the return type to `Nullable<T>`, and call the method with the non nullable parameter ``` static void Main(string[] args) { int? i = GetValueOrNull<int>(null, string.Empty); } public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct { object columnValue = re...
``` public static T GetValueOrDefault<T>(this IDataRecord rdr, int index) { object val = rdr[index]; if (!(val is DBNull)) return (T)val; return default(T); } ``` Just use it like this: ``` decimal? Quantity = rdr.GetValueOrDefault<decimal?>(1); string Unit = rdr.GetValueOrDefault<string>(2); ``...
Nullable type as a generic parameter possible?
[ "", "c#", "generics", "" ]
I'm talking about this: If we have the letter 'A' which is 77 in decimal and 4D in Hex. I am looking for the fastest way to get D. I thought about two ways: Given x is a byte. 1. `x << 4; x >> 4` 2. `x %= 16` Any other ways? Which one is faster?
I always use `x &= 0x0f`
Brevity is nice - explanations are better :) * `x &= 0x0f` > is, of course, the right answer. It exactly expresses the intent of what you're trying to achieve, and on any sane architecture will always compile down to the minimum number of instructions (i.e. 1). Do use hex rather than decimal whenever you put constant...
What is the fastest way to get the 4 least significant bits in a byte (C++)?
[ "", "c++", "optimization", "operators", "bit-shift", "modulo", "" ]
Is there any way to 'hide' the name of a class, whose sole purpose is to provide extension methods, from Intellisense? I would like to remove the class name from the Intellisense list but need the extension methods of the class to be available to external assemblies via Intellisense in the usual way.
Ok, I have the answer to this. Hallgrim's suggestion of marking the class with.. ``` [EditorBrowsable(EditorBrowsableState.Never)] ``` ..does actually work but only where the **assembly** is being referenced, rather than the project, as would be the case in my own VS solution whilst writing the assembly that provides...
I expected that you could to this with the EditorBrowsable attribute: ``` [EditorBrowsable(EditorBrowsableState.Never)] static class MyExtensions { } ``` Unfortunately this did not seem to work.
How can I prevent a public class that provides extension methods from appearing in Intellisense?
[ "", "c#", "extension-methods", "intellisense", "" ]