Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
It is currently said that MD5 is partially unsafe. Taking this into consideration, I'd like to know which mechanism to use for password protection.
This question, [Is “double hashing” a password less secure than just hashing it once?](https://stackoverflow.com/questions/348109/is-double-hashing-a-password-less-secure-... | > **DISCLAIMER**: This answer was written in 2008.
>
> Since then, PHP has given us [`password_hash`](http://php.net/manual/en/function.password-hash.php) and [`password_verify`](http://php.net/manual/en/function.password-verify.php) and, since their introduction, they are the recommended password hashing & checking me... | A much simpler and safer answer - **don't write your own password mechanism at all**, use a tried and tested mechanism:
> For PHP 8 (current in 2023), use [password\_hash()](http://php.net/manual/en/function.password-hash.php) - good quality and part of PHP core since PHP 5.5.
Most programmers just don't have the exp... | Secure hash and salt for PHP passwords | [
"",
"php",
"security",
"hash",
"passwords",
""
] |
I have a wxPython application that relies on an external config file. I want provide friendly message dialogs that show up if there are any config errors. I've tried to make this work by wrapping my app.MainLoop() call in a try/except statement.
The code below works for the init code in my MainWindow frame class, but ... | I coded something like this for [Chandler](http://chandlerproject.org/), where any unhandled exceptions pop up a window with the stack and other info, and users can put in additional comments (what did they do when it happened etc.) and submit it for Chandler developers. A bit like the [Mozilla Talkback](https://wiki.m... | Don't know if this will work for a wxPython application, but in the sys module you can overwrite the excepthook attribute, which is a function called with 3 arguments, `(type, value, traceback)`, when an uncaugth exception is caught. You can install your own function in there that handles only the exceptions you want, ... | Catch MainLoop exceptions and displaying them in MessageDialogs | [
"",
"python",
"exception",
"wxpython",
"wxwidgets",
""
] |
I am working on code generation and ran into a snag with generics. Here is a "simplified" version of what is causing me issues.
```
Dictionary<string, DateTime> dictionary = new Dictionary<string, DateTime>();
string text = dictionary.GetType().FullName;
```
With the above code snippet the value of `text` is as follo... | There is no built-in way to get this representation in the .Net Framework. Namely because there is no way to get it correct. There are a good number of constructs that are not representable in C# style syntax. For instance "<>foo" is a valid type name in IL but cannot be represented in C#.
However, if you're looking f... | A good and clean alternative, thanks to [@LukeH's comment](https://stackoverflow.com/questions/6584263/whats-the-meaning-of-apostrophe-number-in-the-object-type-of-properties-with/6584285#6584285), is
```
using System;
using System.CodeDom;
using System.Collections.Generic;
using Microsoft.CSharp;
//...
private string... | How can I get the correct text definition of a generic type using reflection? | [
"",
"c#",
"generics",
"reflection",
""
] |
I'm porting a process which creates a MASSIVE `CROSS JOIN` of two tables. The resulting table contains 15m records (looks like the process makes a 30m cross join with a 2600 row table and a 12000 row table and then does some grouping which must split it in half). The rows are relatively narrow - just 6 columns. It's be... | Examining that query shows only one column used from one table, and only two columns used from the other table. Due to the very low numbers of columns used, this query can be easily enhanced with covering indexes:
```
CREATE INDEX COSTCENTCoverCross ON COSTCENT(COST_CTR_NUM)
CREATE INDEX JOINGLACCoverCross ON JOINGLAC... | Continuing on what others a saying, DB functions that contained queries which are used in a select always made my queries extremely slow. Off the top of my head, I believe i had a query run in 45 seconds, then I removed the function, and then result was 0 seconds :)
So check udf\_BUPDEF is not doing any queries. | Massive CROSS JOIN in SQL Server 2005 | [
"",
"sql",
"sql-server",
"sql-server-2005",
"performance",
"cross-join",
""
] |
Can someone please explain me what's the difference between Swing and AWT?
Are there any cases where AWT is more useful/advised to use than swing or vice-versa? | AWT is a Java interface to native system GUI code present in your OS. It will not work the same on every system, although it tries.
Swing is a more-or-less pure-Java GUI. It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, checkboxes, etc., into that window and responds ... | The base difference that which already everyone mentioned is that one is **heavy weight** and other is **light weight**. Let me explain, basically what the term heavy weight means is that when you're using the awt components the native code used for getting the view component **is generated by the Operating System**, t... | What is the difference between Swing and AWT? | [
"",
"java",
"swing",
"awt",
""
] |
My question is about one particular usage of static keyword. It is possible to use `static` keyword to cover a code block within a class which does not belong to any function. For example following code compiles:
```
public class Test {
private static final int a;
static {
a = 5;
doSomethin... | The code block with the static modifier signifies a *class* initializer; without the static modifier the code block is an *instance* initializer.
Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but ... | **Uff! what is static initializer?**
The static initializer is a `static {}` block of code inside java class, and run only one time before the constructor or main method is called.
**OK! Tell me more...**
* is a block of code `static { ... }` inside any java class. and executed by virtual machine when class is call... | What is the difference between a static and a non-static initialization code block | [
"",
"java",
"static",
"static-initializer",
""
] |
I have the following classes: Ingredients, Recipe and RecipeContent...
```
class Ingredient(models.Model):
name = models.CharField(max_length=30, primary_key=True)
qty_on_stock = models.IntegerField()
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(... | ```
class RecipeContent(models.Model):
...
def __unicode__(self):
# You can access ForeignKey properties through the field name!
return self.recipe.name
``` | If you only care about the name part of the Recipe, you can do:
```
class Recipe(models.Model):
name = models.CharField(max_length=30, primary_key=True)
comments = models.TextField(blank=True)
...
def __unicode__(self):
return self.name
class RecipeContent(models.Model):
recipe = models.F... | Can I use a ForeignKey in __unicode__ return? | [
"",
"python",
"django",
"django-models",
""
] |
I am curious to learn [Boost](http://www.boost.org/). But I wanted to ask:
* How important is it to make the effort to learn Boost?
* What prerequisites should one have before jumping on Boost?
Why I am curious to know about Boost is that many people are talking about Boost on IRC's channels and here in StackOverflow... | I think anyone that is seriously considering C++ development as a career should learn Boost, and learn it well. Once you get into serious programming you will realize how beneficial these libraries can be and how much more productive they can make you. Not only are they cross-platform, but once you get into data crunch... | As a game developer, I've been shocked by how many people don't know about Boost. I've mentioned it to contacts in various game studios and not only is it frequently not used (is licensing or porting it a problem?) but many people haven't even heard of it. This leads me to believe that from a career perspective, it's n... | How important is Boost to learn for C++ developers? | [
"",
"c++",
"boost",
"libraries",
""
] |
I'm downloading a collection of files, and I'd like to display progress in a progress bar. It's simple to display overall progress by setting the maximum value of the progress bar to the total size of all the files, and by setting the current position to the size downloaded so far.
What I'd like to do is separate the ... | If you know the total size of the files to be downloaded, and you know the total size of the files downloaded so far, then you can just set .Maximum to the total size of the files, and .Position to the total downloaded so far. No need to worry about how the size is split between the files.
Or did you mean that you wan... | I think the easiest way would be to make a UserControl, drop a ProgressBar on it, override the UserControl's OnPaint() and draw your lines.
I think a UserControl would be a little easier to deal with than drawing right on the form. The coordinates would be easier to handle plus it'd be easier to reuse it in another ap... | How do I display tick marks on a Progress Bar? | [
"",
"c#",
"winforms",
"progress-bar",
""
] |
I have a large legacy C++ project compiled under Visual Studio 2008. I know there is a reasonably amount of 'dead' code that is not accessed anywhere -- methods that are not called, whole classes that are not used.
I'm looking for a tool that will identify this by **static analysis**.
This question: [Dead code detect... | You'll want something along the lines of QA-C++ (<http://www.programmingresearch.com/QACPP_MAIN.html>), also see <http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis> for similar products.
You're looking for a static code analysis tool that detects unreachable code; many coding guidelines (such as MISR... | I know that Gimpel's Lint products ([PC-Lint](http://www.gimpel.com/html/pcl.htm) and [Flexelint](http://www.gimpel.com/html/flex.htm)) will identify unreachable code and unused / unreferenced modules.
They both fall in the category of static analysis tools.
I have no affiliation w/ Gimpel, just a satisfied long-term... | Dead code identification (C++) | [
"",
"c++",
"static-analysis",
"dead-code",
""
] |
Can anyone suggest a good reason to use web services instead of RPC (not xml-rpc) as a comms channel between two C++ processes both of which will be developed by the same team? Note: Web services do not guarantee ordered delivery! | When people have a hammer, they tend to see all problems as nails. That's why people tend to put webservices everywhere as if it were the only way for two processes to communicate.
In your case RPC seems to be a better choice, more performance, less memory usage, simpler to implement (in C++)... | Web services are great when you need:
* Support for many languages and platforms
* SOA based applications
* Distributed services
If you dont need any of these, or never will, then there's nothing wrong with RPC at all. If your application's processes all live on the same machine and you need to communicate between th... | Why use Web Services instead of RPC between two internal processes? | [
"",
"c++",
"web-services",
"rpc",
""
] |
I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.
For example:
```
object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
```
and so on.
Query parameter is a set on integers, lets try q(3,4,5)
```
object1 does not match ('1' not in '3,4,5')
obj... | You're making a common mistake in database design, by storing a comma-separated list of tag id's. It's not a surprise that performing efficient queries against this is a blocker for you.
What you need is to model the mapping between objects and tags in a separate table.
```
CREATE TABLE Tagged (
object_id INT NOT ... | Given that you are using PostgreSQL, you could use its [array](http://www.postgresql.org/docs/8.2/static/functions-array.html) datatype and its contains/overlaps operators.
Of course this would tie your app to PostgreSQL tightly, which may not be desired. On the other hand, it may save you coding for when it's really ... | How to compare and search list of integers efficiently? | [
"",
"python",
"postgresql",
""
] |
Can someone help me identify what the purpose of this unidentified syntax is. It is an extra little something in the constructor for this object. What I'm trying to figure out is what is the "< IdT >" at the end of the class declaration line? I think that this is something I would find useful, I just need to understand... | Read about Generics: [MSDN](http://msdn.microsoft.com/en-us/library/512aeb7t.aspx)
That is how you define a generic class.
Hence calling
```
new DomainObject<string>();
```
would create a domain object with an Id of type string.
The way you define the ID must be an int.
The way it is defined the id can be any type... | From the C# spec:
> A class type that is declared to take
> type parameters is called a generic
> class type. Struct, interface and
> delegate types can also be generic.
> When the generic class is used, type
> arguments must be provided for each of
> the type parameters | unidentified syntax in domain object constructor | [
"",
"c#",
"design-patterns",
"oop",
"dns",
""
] |
I'm building a .NET 3.5 application and have the need to evaluate JS code on the server - basically a user provided rule set that can work within a browser or on the server. Managed JS is not an option, because the JS code would be provided at runtime. Aptana's Jaxer is also not an option. So I was looking into using a... | *I realize that this may not be an exact answer to your question, but I figured I would put my 2 cents worth in as I doubt to many people have tried this.*
I got it to work by created a managed wrapper using mixed mode C++. There are other ways to do it, but I was going to attempt to make a full wrapper that could be ... | You can try Javascript .NET:
<http://javascriptdotnet.codeplex.com/>
It lets you create a V8 context from .NET and register CLI objects in it so you can manipulate them and call members from the Javascript code. It compiles the Javascript at runtime.
Check it out. | Referencing Google's V8 engine from a .NET app | [
"",
".net",
"javascript",
"interop",
"v8",
"serverside-javascript",
""
] |
I need to store Python structures made of lists / dictionaries, tuples into a human-readable format. The idea is like using something similar to [pickle](http://docs.python.org/library/pickle.html), but pickle is not human-friendly. Other options that come to my mind are [YAML](http://en.wikipedia.org/wiki/Yaml) (throu... | For simple cases pprint() and eval() come to mind.
Using your example:
```
>>> d = {'age': 27,
... 'name': 'Joe',
... 'numbers': [1,
... 2,
... 3,
... 4,
... 5],
... 'subdict': {
... 'first': 1,
... 'second': 2,
... 'thi... | If its **just** Python list, dictionary and tuple object. - **JSON** is the way to go. Its human readable, very easy to handle and language independent too.
Caution: Tuples will be converted to lists in simplejson.
```
In [109]: simplejson.loads(simplejson.dumps({'d':(12,3,4,4,5)}))
Out[109]: {u'd': [12, 3, 4, 4, 5]}... | How to serialize Python objects in a human-readable format? | [
"",
"python",
"serialization",
""
] |
We have a C++ library that we provide to several different clients. Recently we made the switch from using raw pointers in the public interface to using boost::sharedptr instead. This has provided an enormous benefit, as you might guess, in that now the clients no longer have to worry about who needs to delete what and... | shared\_ptr<> *is* part of the language, as of the release of TR1.
See: [(TR1)](http://msdn.microsoft.com/en-us/library/bb982729.aspx) | One possible solution is to ship boost::shared\_ptr with your project. As it all consists of headers, this would free your clients from having to install the boost libraries manually. You can use [bcp](http://www.boost.org/doc/libs/1_37_0/tools/bcp/bcp.html) to get all files needed by a particular boost library, includ... | Using boost::shared_ptr in a library's public interface | [
"",
"c++",
"api",
"boost",
"shared-ptr",
""
] |
I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful? | A functor is pretty much just a class which defines the `operator()`. That lets you create objects which "look like" a function:
```
// this is a functor
struct add_x {
add_x(int val) : x(val) {} // Constructor
int operator()(int y) const { return x + y; }
private:
int x;
};
// Now you can use it like this:
a... | Little addition. You can use [`boost::function`](http://www.boost.org/doc/libs/1_51_0/doc/html/boost/function.html), to create functors from functions and methods, like this:
```
class Foo
{
public:
void operator () (int i) { printf("Foo %d", i); }
};
void Bar(int i) { printf("Bar %d", i); }
Foo foo;
boost::functi... | What are C++ functors and their uses? | [
"",
"c++",
"functor",
"function-object",
"function-call-operator",
""
] |
Here's the basic idea:
There is a java window (main) that opens another java window (child). When the child is created, part of the initialization sets the focus in the appropriate text field in the child window:
```
childTextField.requestFocusInWindow();
childTextField.setCaretPosition(0);
```
The child is generall... | On first look, that sounds like it might be a bug in the implementation; the key should be in the same event queue as the mouse events. There's another issue possible though: the event queue is running in a thread separate from the program main; without knowing what's going on in the rest of the application, it's tempt... | I had an issue similar to this. try adding this after your `init()`
```
EventQueue.invokeLater(new Runnable() {
public void run() {
childtextfield.requestFocus();
childTextField.setCaretPosition(0);
}
});
```
It's worked for me. | Java window buffering keystrokes until the user clicks with the mouse | [
"",
"java",
"swing",
""
] |
Are there any preprocessor symbols which allow something like
```
#if CLR_AT_LEAST_3.5
// use ReaderWriterLockSlim
#else
// use ReaderWriterLock
#endif
```
or some other way to do this? | I don't think there are any predefined 'preprocessor' symbols. However you can achieve what you want like this:
1. Create different configurations of your project, one for every version of CLR you want to support.
2. Choose a symbol like `VERSION2`, `VERSION3` etc. per CLR version.
3. In every configuration, define th... | There aren't any built in, but you can supply your own.
For this specific scenario, you might want to encapsulate the logic in (for example) a wrapper (lock) class, so that you don't have `#if` scattered through all the code; of course, if you are only doing a little locking it might not be worth the trouble.
I use d... | Conditional compilation depending on the framework version in C# | [
"",
"c#",
"c-preprocessor",
"conditional-compilation",
""
] |
What would be the best way to do this.
The input string is
```
<133_3><135_3><116_2>The other system worked for about 1 month</116_2> got some good images <137_3>on it then it started doing the same thing as the first one</137_3> so then I quit using either camera now they are just sitting and collecting dust.</135_3... | Use expat or another XML parser; it's more explicit than anything else, considering you're dealing with XML data anyway.
However, note that XML element names can't start with a number as your example has them.
Here's a parser that will do what you need, although you'll need to tweak it to combine duplicate elements i... | Take an XML parser, make it generate a DOM (Document Object Model) and then build a recursive algorithm that traverses all the nodes, calls "text()" in each node (that should give you the text in the current node and all children) and puts that as a key in the dictionary. | Parsing a string for nested patterns | [
"",
"python",
"regex",
""
] |
I have a greasemonkey user script with this single line of code...
```
window.close();
```
but firefox does not allow a user script to close a window (as reported by an error message in the error console)
Is there a work around to this problem? | **You need to change configuration settings of Firefox (about:config) to allow this.**
## Steps:
1. Go to address bar and type **about:config**
2. Go to parameter **dom.allow\_scripts\_to\_close\_windows**
3. Set its value as **true**
Now your script can close the TAB with 'window.close()'
***eg.***
```
function c... | By now some of the *-monkies* allow the use of *@grant* option to officially unlock commands like *window.close()* without going to *about:config*. For example, in [Tampermonkey](https://tampermonkey.net/documentation.php):
```
// @grant window.close
// @grant window.focus
```
(The latter *grant* allows you to re-foc... | How do I close a firefox tab from a greasemonkey script? | [
"",
"javascript",
"firefox",
"greasemonkey",
""
] |
I plan to use a distributed cache in my load-balanced webapp.
So I'm going to try to abstract out the common functions between apache ehcache and memcached.
My goal is to be able to make a simple configuration switch to select the caching solution to use. Should I go the SPI route e.g. like how XML parsers are wired i... | From the top of my head...
* Create interface with common cache related methods (add(), remove(), refresh() comes to mind as the most obvious ones).
* Create implementations of that interface which use desired cache underneath ("MyEhCacheImplementation" and "MyMemCachedImplementation" or something like that).
* Create... | After fixing the interface, this is really a creational pattern problem. Dependency Injection is my favourite, if the cache-selection strategy is dynamic you can use spring bean factories to decide at runtime. Spring has support for "session" scopes on web-applications meaning you can let the factory decide per session... | How to abstract out 2 different implementations of cache | [
"",
"java",
"memcached",
"abstraction",
"ehcache",
"distributed-caching",
""
] |
I'm currently using SMO and C# to traverse databases to create a tree of settings representing various aspects of the two databases, then comparing these trees to see where and how they are different.
The problem is, for 2 reasonably sized database, it takes almost 10mins to crawl them locally and collect table/column... | Try to force SMO to read all the required fields at once, instead of querying on access.
See [this blog](http://davidhayden.com/blog/dave/archive/2006/03/29/2894.aspx) for more information
---
EDIT: Link is dead but I found [the page](http://web.archive.org/web/20100102060107/http://davidhayden.com/blog/dave/archive/... | Use the system views in each database and query conventionally.
<http://www.microsoft.com/downloads/details.aspx?familyid=2EC9E842-40BE-4321-9B56-92FD3860FB32&displaylang=en> | Is there anyway to speed up SQL Server Management Objects traversal of a existing database? | [
"",
"c#",
".net",
"sql-server",
"smo",
""
] |
I have inherited a Java application (servlets) that runs under Tomcat. For historical reasons, the code has different "look and feel" options based on where the application will be deployed (essentially a matter of branding).
There are several constants that control this branding process, which have different function... | Use the replace task in Ant to change the values.
* [Ant Replace](http://ant.apache.org/manual/Tasks/replace.html) | Put your values into a properties file, say "myapp.properties" and then load them into your constants from the classpath at startup (see below for how this fits into the build process):
```
public class Constants
{
private static final Properties props = new Properties();
public static final String MY_CONSTANT... | Best way to alter constants in Java build process | [
"",
"java",
"configuration",
"tomcat",
"ant",
"build-automation",
""
] |
I got some legacy code that has this:
```
<?PHP
if(isset($_GET['pagina'])=="homepage") {
?>
HtmlCode1
<?php
} else {
?>
HtmlCode2
<?php
}
?>
```
I don't know exactly why but this seems to be working. The htmlcode1 is loaded when I have ?pagina=homepage and the htmlcode2 is loaded when the pagina var doesn't e... | The problem is that "==" isn't a type-sensitive comparison. Any (non-empty) string is "equal" to boolean true, but not **identical** to it (for that you need to use the "===" operator).
A quick example, why you're seeing this behavior:
<http://codepad.org/aNh1ahu8>
And for more details about it from the documentati... | `isset()` returns true or false. In a boolean comparison, `"homepage"` would evaluate to `true`. So essentially you got here:
```
if ( isset($_GET['pagina']) == true )
```
If pagina equals anything, you will see HtmlCode1. If it is no set, you will see HtmlCode2.
I just tried it to confirm this, and going to `?pagin... | Did isset work differently in older versions | [
"",
"php",
"legacy-code",
""
] |
How do you make a field in a sql select statement all upper or lower case?
Example:
select firstname from Person
How do I make firstname always return upper case and likewise always return lower case? | ```
SELECT UPPER(firstname) FROM Person
SELECT LOWER(firstname) FROM Person
``` | LCASE or UCASE respectively.
Example:
```
SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable
``` | SQL changing a value to upper or lower case | [
"",
"sql",
"case",
"uppercase",
"lowercase",
""
] |
My first question on StackOverflow...
Does anybody know a way of viewing the reference/documentation manual of a language through CodeBlocks? Specifically for C/C++.
Example:
Say I want to look up the reference for strncpy(). In a very old Borland system (which we use at school) I would write the word and middle-cl... | Yes, it is possible. I'm not sure about the help files themselves though.
The procedure seems to be documented [here.](http://wiki.codeblocks.org/index.php?title=Using_devhelp_as_a_help_viewer)
from the forums.
Re: F1 - help and function reference
« Reply #1 on: September 15, 2008, 02:07:59 pm »
if you have the hel... | I found the complete answer. Based on your reply EvilTech.
Here's the setup procedure for different systems:
<http://wiki.codeblocks.org/index.php?title=Help_plugin>
And here are the help files for C++ compiled from an online source:
<http://onnerby.se/~daniel/chm/>
I find it strange though that I couldn't find any ... | Viewing language (C/C++) reference/documentation in CodeBlocks | [
"",
"c++",
"c",
"codeblocks",
""
] |
I recently wrote some javascript code that filled a drop down list based on some XML, pretty simple stuff. The problem was I had to write similar code to do almost the same thing on a different page.
Because the code was almost identical I named most of the functions the same, thinking that they would never be include... | Try the JavaScript [module pattern](http://yuiblog.com/blog/2007/06/12/module-pattern/) (or namespaces) used in various libraries.
Try to be DRY (don't repeat yourself) so you can avoid name collisions. If the code is almost the same you better avoid code duplication by creating a function which can handle both cases.... | I would look at how I could merge the two pieces of code (functions?) into a single function. If you need to populate a list box, then pass the list box id into the function, so you are not hard-coded to operate on one single control only...
I did this on my rocket business's web site where I sold rocket motors with d... | Whats the best way to resolve name conflicts in javascript? | [
"",
"javascript",
""
] |
I'm trying to parse some JSON using the JSon.Net library. The documentation seems a little sparse and I'm confused as to how to accomplish what I need. Here is the format for the JSON I need to parse through.
```
{
"displayFieldName" : "OBJECT_NAME",
"fieldAliases" : {
"OBJECT_NAME" : "OBJECT_NAME",
... | I don't know about JSON.NET, but it works fine with `JavaScriptSerializer` from `System.Web.Extensions.dll` (.NET 3.5 SP1):
```
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
public string OBJECT_NAME { get; set; }
public string OBJECT_TYPE { get; set; }
}
... | **Edit:** Thanks Marc, read up on the struct vs class issue and you're right, thank you!
I tend to use the following method for doing what you describe, using a static method of JSon.Net:
```
MyObject deserializedObject = JsonConvert.DeserializeObject<MyObject>(json);
```
Link: [Serializing and Deserializing JSON wi... | Parsing JSON using Json.net | [
"",
"c#",
"json",
"parsing",
"serialization",
"json.net",
""
] |
I've recently bumped into something called IOCP on the windows platform, to be more precise: Input/Output Control Ports. This seems to be *the* most efficient way to code your server software when it needs to hold thousands of users concurrently.
(Correct me if I'm wrong, but thread-per-socket, polling, and asynchronou... | Have you looked at boost::asio?
I'm not sure if it has all this functionality yet, but I believe that's one of the things it's intended for. | I know this is a late reply to this thread, but for those interested in a x-platform library supporting async IO on both Linux/UNIX and Windows, you might want to take a look at [libuv](https://github.com/joyent/libuv).
[libuv](https://github.com/joyent/libuv) was initially constructed as the foundational underpinning... | IOCP, Cross platform libraries? | [
"",
"c++",
"iocp",
""
] |
I am trying to do the following in a way or another:
```
const char EscapeChar = '\\';
const string EscapeString = EscapeChar.ToString(); // or ("" + EscapeChar)
```
This does't compile. Is there another way to make it work? | Starting from .net 6.0, with c# version 10 constant interpolated strings were introduced (<https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#constant-interpolated-strings>)
So from .net 6.0 on you can do this using:
```
const string EscapeString = $"{EscapeChar}";
``` | From the [C# Language Specification](http://guide.opendns.com/track/click.php?q=c%23+specification&curl=http%3A%2F%2Fwww.ecma-international.org%2Fpublications%2Fstandards%2FEcma-334.htm&search_grp=MAINRESULTS&search_pos=2) (§ 17.3 and 14.16):
> **17.3 Constants**
>
> A constant is a class member that
> represents a co... | Can I initialize a const string from a const char in C#? | [
"",
"c#",
"string",
"constants",
""
] |
I'm trying to find any JavaScript frameworks whose sole aim is to standardize the DOM and JavaScript across all browsers.
What I'm not looking for is frameworks which create their own API to solve these common problems. I want something that will allow me to call for example myElement.dispatchEvent("click") in Interne... | [Dean Edwards' Base2](http://code.google.com/p/base2/) might be what you're looking for. You might find [Diego Perini's NWEvents](http://code.google.com/p/nwevents/) interesting as well... | Although it has its own API, Prototype tries to do that (at least partially). If you use Firebug, you can notice a lot of methods added to the DOM, in order to make the DOM equally in all browsers.
I know it's not exactly what you were looking for, but it's a half-way solution.
Also, in some browsers, it might not be... | Any JavaScript Frameworks with the aim of standard based cross-platform JS and DOM? | [
"",
"javascript",
"dom",
"frameworks",
""
] |
I want to build a dialog in Java with a List and a couple of buttons underneath it.
The list ends up with the same height as the buttons (about one line) and the whole dialog is about two lines of height.
However, I'd like the dialog to be taller (maybe 10 lines) and the JList to take up most of the space .. I've play... | Found the problem .. and it has nothing to do with the layout code.
I was adding a null to ListModel, and that seemed to confuse the LayoutManager. Would close the question, but not yet enough mojo ... | For the list set weightY=1 instead of 3. The setting of 3 will make the space for the list larger than the list itself. 99.9% of the time GridBagLayout is used the weightX/Y values should always be either 0 or 1. Also the gridWidth should probably be 2 instead of 3. | Java(Swing): influence height of JList in GridBagLayout | [
"",
"java",
"swing",
""
] |
I'm trying to encode Cyrillic UTF-8 array to JSON string using php's function json\_encode. The sample code looks like this:
```
<?php
$arr = array(
'едно' => 'първи',
'две' => 'втори'
);
$str = json_encode($arr);
echo $str;
?>
```
It works fine but the result of the script is represented as:
```
{... | Can't you use [JSON\_UNESCAPED\_UNICODE](http://php.net/manual/en/function.json-encode.php) constant here? | ```
$str = json_encode($arr, JSON_UNESCAPED_UNICODE);
```
The use of this solution worked for me with the Latin and the Cyrillic alphabet, with PHP 5.5 | Cyrillic characters in PHP's json_encode | [
"",
"php",
"utf-8",
"json",
""
] |
In the upcoming Java7, there is a [new API](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isSameFile(java.nio.file.Path,%20java.nio.file.Path)) to check if two file object are same file reference.
Are there similar API provided in the .NET framework?
I've search it over MSDN but nothing enlighten ... | As far as I can see [(1)](http://hg.openjdk.java.net/nio/nio/jdk/file/d5e2831c01c4/src/windows/native/sun/nio/ch/FileKey.c) [(2)](http://hg.openjdk.java.net/nio/nio/jdk/file/d5e2831c01c4/src/windows/classes/sun/nio/fs/WindowsFileAttributes.java) [(3)](http://hg.openjdk.java.net/nio/nio/jdk/file/d5e2831c01c4/src/windows... | **Edit**: Note that [@Rasmus Faber](https://stackoverflow.com/users/5542/rasmus-faber) mentions the [GetFileInformationByHandle](http://msdn.microsoft.com/en-us/library/aa364952(VS.85%29.aspx) function in the Win32 api, and this does what you want, check and upvote his [answer](https://stackoverflow.com/questions/41070... | Best way to determine if two path reference to same file in C# | [
"",
"c#",
"api",
"filesystems",
""
] |
Is there a difference between having a `private const` variable or a `private static readonly` variable in C# (other than having to assign the `const` a compile-time expression)?
Since they are both private, there is no linking with other libraries. So would it make any difference? Can it make a performance difference... | Well, you can use consts in attributes, since they exist as compile time. You can't predict the value of a static readonly variable, since the `.cctor` could initialize it from configuration etc.
In terms of usage, constants are burnt into the calling code. This means that if you recompile a *library* dll to change a ... | Indeed, the two types cannot be changed after they were initialized, but there are some differences between them:
* 'const' must be initialized where they are declared(at compile time), whereas 'readonly' can be initialized where it is declared or inside the constructor (ar runtime).
For example const could be used i... | Is there a difference between private const and private readonly variables in C#? | [
"",
"c#",
"constants",
"readonly",
""
] |
I'm developing an application in C++ that's partially driven by touch-screen on Windows XP Embedded. Some text entry will be necessary for the user. So far we've been using the standard Windows On-Screen Keyboard (osk.exe), but there are two main problems:
1. It's rather small on a higher resolution screen which will ... | We are using [Click-N-Type](http://www.lakefolks.org/cnt/) for our systems. It is completely resizable. It has some customization possibilities, but I never tried them. We use it on "normal" Windows XP, but it should work on Windows XP embedded also. | I know this question is tagged 'c++', but here's an option for .Net that I found and integrated with less than 5 minutes work. (I've looked, and there isn't a .Net flavour of this question, and I guess it could be ported to C++ with very little effort too).
It uses the standard Windows On-Screen Keyboard (osk.exe), re... | Which On-Screen Keyboard for Touch Screen Application? | [
"",
"c++",
"user-interface",
"windows-xp",
"touchscreen",
""
] |
What is the proper way to cast from an 'OLE\_HANDLE' to an 'HICON' for an x64 target build?
In particular with a normal C-Style cast, I get this warning when compiling with an x64 config:
warning C4312: 'type cast' : conversion from 'OLE\_HANDLE' to 'HICON' of greater size
Here is the offending code:
```
imgList.Ad... | The H gives it away, in this case the library code has created a distinct type to give you a little more type safety (in the days of old C APIs).
They are actually both HANDLEs, which is a kernel object that doesn't really care what the resource is, just that you have a 'handle' to it. Remember the API is a C one, so ... | Assuming you're using Microsoft Visual Studio based on the question...
If you are developing only for 32-bit targets, you may choose to disable this (and some other similar warnings) by turning off the project option ["Detect 64-bit Portability Issues" (C++ compiler option /Wp64).](http://msdn.microsoft.com/en-us/libr... | What is the proper way to cast from an 'OLE_HANDLE' to an 'HICON'? | [
"",
"c++",
"windows",
"winapi",
"mfc",
"casting",
""
] |
Is it possible to browse the source code of OpenJDK online, just like I can do with SourceForge's projects? I never used Mercury before, so I felt confused.
(Note: I don't want to download the source. I just want to browse it online, to see how some methods are implemented.) | OpenJDK is now on GitHub: <https://github.com/openjdk/jdk>
It is a large project, but you will find the implementations of the core classes under [jdk/src/java.base/share/classes](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes).
For instance you can find [the implementation of `java.util.List`... | The latest **JDK 8** OpenJDK *Java Class Library* source code can be found here: <http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/tip/src/share/classes/> | Is it possible to browse the source of OpenJDK online? | [
"",
"mercurial",
"java",
""
] |
According to [MSDN: Array usage guidelines](<http://msdn.microsoft.com/en-us/library/k2604h5s(VS.71).aspx)>:
Array Valued Properties
> You should use collections to avoid code inefficiencies. In the following code example, each call to the myObj property creates a copy of the array. As a result, 2n+1 copies of the ar... | No, it isn't **leaking** memory - it is just making the garbage collector work harder than it might. Actually, the MSDN article is slightly misleading: if the property created a new **collection** every time it was called, it would be just as bad (memory wise) as with an array. Perhaps worse, due to the usual over-sizi... | Just as a hint for those who haven't use the ReadOnlyCollection mentioned in some of the answers:
```
[C#]
class XY
{
private X[] array;
public ReadOnlyCollection<X> myObj
{
get
{
return Array.AsReadOnly(array);
}
}
}
```
Hope this might help. | Avoiding array duplication | [
"",
"c#",
"performance",
"arrays",
"memory-leaks",
"memory-management",
""
] |
I'm working with a group of other programmers on an open source project built using C++ and Qt.
Now, we need a naming convention for widgets (and other variables generally) to use it as a standard in all of our code so that, the code gets better readability and we get better coordination between programmers.
Any advi... | As long as you are thinking along these lines, I'd start by reading this QtQuarterly article from start-to-finish.
[Designing Qt-Style C++ APIs](https://doc.qt.io/archives/qq/qq13-apis.html)
That said, one thing that we do is to put the "use" of the instance as the first part and the last full word of the class as th... | Since Qt is open to third party developers, they made available several documentation regarding the coding style and the API design principles.
These documents are really interesting. Here are a few links :
[Wiki : Qt Coding Style](http://qt-project.org/wiki/Qt_Coding_Style)
[Wiki : Api Design Principles](http://qt-... | Naming convention for Qt widgets | [
"",
"c++",
"qt",
"coding-style",
"widget",
""
] |
What optimization techniques do you use on extremely large databases? If our estimations are correct, our application will have billions of records stored in the db (MS SQL Server 2005), mostly logs that will be used for statistics. The data contains numbers (mostly integer) and text (error message texts, URLs) alike.
... | The question is a little big vague, but here are a few tips:
* Use appropriate hardware for your databases. I'd opt for 64-bit OS as well.
* Have dedicated machines for the DBs. Use fast disks configured for optimal performance. The more disks you can span over, the better the performance.
* Optimize the DB for the ty... | I don't use it myself but I have read that one can use Hadoop in combination with hbase for distributed storage and distributed analysing of data like logs. | Optimization techniques for large databases | [
"",
"sql",
"performance",
"optimization",
""
] |
Even better would be if `autoResize` in latest branch would work as intended, but till then the question is simple: **how to resize a dialog once it is created?** | The answer from is Soviut is correct for `v1.5. 1.6` adds an `option` method to each plugin:
```
$(document).ready(function(){
var d = $("#example").dialog();
d.dialog("option", "width", 700);
});
``` | ```
$('#dialog').dialog().animate({width: "700px"}, 400);
```
I've used this for dynamically resizing dialogs. | Resize jquery UI dialog with JS? | [
"",
"javascript",
"jquery-ui",
"modal-dialog",
"jquery-ui-dialog",
""
] |
I've got a blogging site hosted on Windows Sever, ASP.Net 3.5, ASP.Net AJAX, SQL Server in background.
I want to give bloggers a button like 'digg-it' which they can put on their blogs for the readers to click to thumb-up the post if they like it.
I know I'll be using Javascript to do that. What can I do to: -
1. Re... | You can look into using SCRIPT callbacks loading JSON data instead of using XmlHttpRequest to get around the crossdomain issues.
```
function dynScript(url){
var script=document.createElement('script');
script.src=url;
script.type="text/javascript";
document.getElementsByTagName('head')[0].appendChild(... | Okay, I got one answer and while I was trying that method I found something easier.
What I am going to use is an iframe. An iframe is like a browser window within the browser. The code I render in the iframe will internally access my website as if it's a regular webpage request. So I can use my web services, my backgr... | How can I make a button like 'Digg it' for my website? | [
"",
".net",
"javascript",
"web-services",
""
] |
I have the following code for "factory" design pattern implementation.
```
class Pen{
public:
virtual void Draw() = 0;
};
class RedPen : public Pen{
public:
virtual void Draw(){
cout << "Drawing with red pen" << endl;
}
};
class BluePen : public Pen{
public:
virtual void Draw(){
... | In the example you posted, neither a factory or a template approach makes sense to me.
My solution involves a data member in the Pen class.
```
class Pen {
public:
Pen() : m_color(0,0,0,0) /* the default colour is black */
{
}
Pen(const Color& c) : m_color(c)
{
}
Pen(const Pen... | Another way is to dynamically register a *creator* function to a dynamical Factory object.
```
BluePen *create_BluePen() { return new BluePen; }
static bool BluePen_creator_registered =
Factory::instance()->registerCreator("BluePen",
... | Factory method implementation - C++ | [
"",
"c++",
"templates",
"design-patterns",
"factory",
""
] |
Does anybody know why
```
vector<int> test(10);
int a=0;
for_each(test.begin(),test.end(),(_1+=var(a),++var(a)));
for_each(test.begin(),test.end(),(cout << _1 << " "));
cout << "\n"
```
Gives : "0 1 2 3 4 5 6 7 8 9"
but
```
transform(test.begin(),test.end(),test.begin(), (_1+=var(a),++var(a)));
...(... | Comma operator evaluates left to right, so the result of the
```
_1+=var(a), ++var(a)
```
is ++var(a), which you'll store using the transform version.
* for\_each:
\_1 += var(a) is evaluated, updating your sequence (via the lambda \_1), then ++var(a) is evaluated, but this has no effect on your sequence.
* transf... | Essentially, in the `for_each` you provide a function with a side-effect, while in the `transform`, your use the returnvalue of a function.
In your case, you reuse the same function. Since `operator +=` happens to have a return value, this is the one used as a result of the transformation. | boost lambda for_each / transform puzzle | [
"",
"c++",
"boost",
"lambda",
""
] |
I sometimes define Business Logic classes to "help" my ASPX code-behind classes. It makes the most sense to me to include them both in the code-behind file since they work together. However, I'd occasionally like to access the Business Logic classes from higher level classes defined in App\_Code but they aren't automat... | I assume you mean you are defining a separate class inside the codebehind .cs file? What access modifiers are you giving them?
As above though, I'd generally have a separate project in the solution for this kind of thing (usually in a different namespace like MyApp.Web and MyApp.), and just reference it from there. | Make sure you place your classes in a sensible namespace.
Place 'using' keyword in code behind files you would like to access them.
Or <%@ import if you are using them in inline code.
Put the dll that contains your classes in the /bin folder.
TBH I prefer to keep the separate library project in the same solution an... | Accessing a Class that is NOT declared in App_Code in ASP.NET | [
"",
"c#",
"asp.net",
""
] |
We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file an... | **“Damn the torpedoes! Full speed ahead!”**
Just download the file. If it is a large file then after the download completes wait as long as is reasonable for your scenario and continue the download from the point it stopped. Repeat until there is no more stuff to download. | You can't know when the OS copy is done. It could slow down or wait.
For absolute certainty, you really need two files.
* The massive file.
* And a tiny trigger file.
They can mess with the massive file all they want. But when they touch the trigger file, you're downloading both.
---
If you can't get a trigger, yo... | Prevent ftplib from Downloading a File in Progress? | [
"",
"python",
"ftp",
"ftplib",
""
] |
This could be a little off the ballpark, but a friend asked me about it and it's kind of bothering me. How do you figure out the current path in your address bar if the server redirects all requests to a default file, say, index.html.
Let's say you entered:
```
www.example.com/
```
And your server configuration auto... | The problem is that it's not actually a redirect. When you type `'www.example.com'` into your web browser, the browser generates an HTTP request like the following:
```
GET / HTTP/1.1
User-Agent: curl/7.16.3 (i686-pc-cygwin) libcurl/7.16.3 OpenSSL/
0.9.8h zlib/1.2.3 libssh2/0.15-CVS
Host: www.example.com
Accept: */*
`... | If the redirect happens on the server then the browser is not aware of it and you cannot access the actual resource in javascript. For example, a servlet might "forward" to another resource on the server.
If the server sends a redirect command to the browser and the browser requests the new url then the browser does k... | How do I get the URL path after a redirect -- with Javascript? | [
"",
"javascript",
"dom",
""
] |
I'm trying to develop an application that will use getImageData in javascript in Firefox 3, but I am getting a "`NS_ERROR_DOM_SECURITY_ERR`" on the getImageData call. The javascript and the image are both currently being served from by hard drive, which is apparently a security violation? When this is live they will bo... | You could try installing a local webserver such as Apache (on unix) or IIS (on Windows). That will ultimately give you the best local test bench for web-related stuff, because as you have found out browsers treat files from the filesystem quite differently than content served from a webserver. | You can tell the browser to bug off. The solution is better or worse depending on your circumstances. I wrap it in a try so no security dialog will be presented if it's not an issue.
```
var data;
try {
try {
data = context.getImageData(sx, sy, sw, sh).data;
} catch (e) {
netscape.security.Priv... | getImageData in Firefox 3 causing NS_ERROR_DOM_SECURITY_ERR | [
"",
"javascript",
"firefox",
"getimagedata",
""
] |
This is a bit of a crazy idea, but would there be a way to bootstrap all the functions that php have without using a helper function to call the functions.
What I mean is actually calling some code or function before and after every basic function call.
Example:
```
<?php
echo "Hello";
?>
```
But these functions wo... | "Bootstrapping" is not the correct term here - what you want to do is called [Aspect-oriented Programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming), and [yes, it can be done in PHP](http://sebastian-bergmann.de/archives/573-Current-State-of-AOP-for-PHP.html). However, it seems to require substantial ch... | Just as an FYI, your example picked something which isn't actually a function in the strictest sense, [echo](http://uk.php.net/echo) is a language construct and handled differently by the PHP internals.
I think there's only two ways to achieve what you are after though:
* Preprocess your PHP code to augment
it with... | Bootstraping all functions in PHP | [
"",
"php",
""
] |
In my programs infinity usually arises when a value is divided by zero. I get indeterminate when I divide zero by zero. How do you check for infinite and indeterminate values in C++?
In C++, infinity is represented by 1.#INF. Indeterminate is represented by -1.#IND. The problem is how to test if a variable is infinite... | For Visual Studio I would use [`_isnan`](http://msdn.microsoft.com/en-us/library/aa298428(VS.60).aspx) and [`_finite`](http://msdn.microsoft.com/en-us/library/aa246875(VS.60).aspx), or perhaps [`_fpclass`](http://msdn.microsoft.com/en-us/library/aa246882(VS.60).aspx).
But if you have access to a C++11-able standard li... | Although C++03 doesn't provide C99's [isnan](http://en.cppreference.com/w/c/numeric/math/isnan) and [isinf](http://en.cppreference.com/w/c/numeric/math/isinf) *macros*, C++11 standardizes them by providing them as [functions](http://en.cppreference.com/w/cpp/numeric/math). If you can use C++11, instead of strict C++03,... | How do you check for infinite and indeterminate values in C++? | [
"",
"c++",
"visual-c++",
"floating-point",
"nan",
"infinity",
""
] |
I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with... | I think that the [multiprocessing](http://docs.python.org/library/multiprocessing.html) framework has what might be applicable here - namely the shared ctypes module.
Multiprocessing is fairly new to Python, so it might have some oddities. I am not quite sure whether the solution works with processes not spawned via `... | Be cautious of premature optimization.
Addition: The "Python backend runs an algorithm whose state..." is the session in the web framework. That's it. Let the Django framework maintain session state in cache. Period.
"The algorithm's per-user state undergoes many small changes as a user works with the application." M... | How would one make Python objects persistent in a web-app? | [
"",
"python",
"web-applications",
"concurrency",
"persistence",
""
] |
Sorry, I thought this was an inheritance question: it was an ArrayList question all along!
Ok, my problem is more specific than I thought. So I have two families of classes. Cards, and Zones. Zones are boxes for holding card.
The first two subClasses of Zone, ZoneList and ZoneMap are meant to be two different ways of... | If I understand you correctly, you should probably declare:
```
public class ZoneList<T extends Card> {
protected List<T> cardBox;
}
public class PokerHand extends ZoneList<PokerCard> {
public PokerHand() {
cardBox = new ArrayList<PokerCard>();
}
}
``` | Marc and kolstae have given good answers in terms of how to get around the problem, but I think it's worth explaining *why* your original code doesn't work.
To simplify matters, I tend to put the problem in terms of fruit. Suppose we have:
```
List<Banana> bananaBunch = new ArrayList<Banana>();
List<Fruit> fruitBowl ... | Casting between ArrayLists in Java | [
"",
"java",
"casting",
"arraylist",
""
] |
I have a coworker looking for this, and I don't recall ever running into anything like that.
Is there a reasonable technique that would let you simulate it?
```
SELECT PRODUCT(X)
FROM
(
SELECT 3 X FROM DUAL
UNION ALL
SELECT 5 X FROM DUAL
UNION ALL
SELECT 2 X FROM DUAL
)
```
would yield 30 | ```
select exp(sum(ln(col)))
from table;
```
edit:
if col always > 0 | ```
DECLARE @a int
SET @a = 1
-- re-assign @a for each row in the result
-- as what @a was before * the value in the row
SELECT @a = @a * amount
FROM theTable
```
There's a way to do string concat that is similiar:
```
DECLARE @b varchar(max)
SET @b = ""
SELECT @b = @b + CustomerName
FROM Customers
``` | is there a PRODUCT function like there is a SUM function in Oracle SQL? | [
"",
"sql",
"oracle",
""
] |
I remember someone saying if you create a class through a lib you should destroy it through the library. So, does this mean I shouldn't call delete? I should call `myclass.deleteMe()` instead? Would overloading delete solve the problem? | A problem with your application's deleting something that was created within a lib is that the lib might use a different heap/memory manager.
Solutions include:
* Ensure that your application is built with the same heap manager as the library.
* Implement a (non-inline) deleteMe method in the class, whose implementat... | > I remember someone saying if you create a class through a lib you should destroy it through the lib.
That means if you call a function in a lib to create an object for you, you should read the documentation of that function, which must say how you free that object again. Often the function for free something is name... | To delete or to not delete (call func)? | [
"",
"c++",
""
] |
After asking [organising my Python project](https://stackoverflow.com/questions/391879/organising-my-python-project) and then [calling from a parent file in Python](https://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python) it's occurring to me that it'll be so much easier to put all my code in on... | If you are planning to use any kind of SCM then you are going to be screwed. Having one file is a guaranteed way to have lots of collisions and merges that will be painstaking to deal with over time.
Stick to conventions and break apart your files. If nothing more than to save the guy who will one day have to maintain... | If your code is going to work together all the time anyway, and isn't useful separately, there's nothing wrong with keeping everything in one file. I can think of at least popular package (BeautifulSoup) that does this. Sure makes installation easier.
Of course, if it seems, down the road, that you could use part of y... | All code in one file | [
"",
"python",
"version-control",
"project-management",
""
] |
I've run into an odd problem and I'm not sure how to fix it. I have several classes that are all PHP implementations of JSON objects. Here' an illustration of the issue
```
class A
{
protected $a;
public function __construct()
{
$this->a = array( new B, new B );
}
public function __toStri... | A late answers but might be useful for others with the same problem.
In *PHP < 5.4.0* **`json_encode`** doesn't call any method from the object. That is valid for getIterator, \_\_serialize, etc...
In PHP > v5.4.0, however, a new interface was introduced, called [**JsonSerializable**](http://php.net/manual/en/class.j... | Isn't your answer in the [PHP docs for json\_encode](https://www.php.net/manual/en/function.json-encode.php#84997)?
> For anyone who has run into the problem of private properties not being added, you can simply implement the IteratorAggregate interface with the getIterator() method. Add the properties you want to be ... | PHP: __toString() and json_encode() not playing well together | [
"",
"php",
"json",
"serialization",
""
] |
I am creating a jQuery plugin.
How do I get the real image width and height with Javascript in Safari?
The following works with Firefox 3, IE7 and Opera 9:
```
var pic = $("img")
// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real... | Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:
```
var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues... | Use the `naturalHeight` and `naturalWidth` attributes from [HTML5](http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element).
For example:
```
var h = document.querySelector('img').naturalHeight;
```
*Works in IE9+, Chrome, Firefox, Safari and Opera ([stats](http://caniuse.com/#feat=img-naturalwidth-natura... | Get the real width and height of an image with JavaScript? (in Safari/Chrome) | [
"",
"javascript",
"jquery",
"safari",
"google-chrome",
"webkit",
""
] |
When comparing two objects (of the same type), it makes sense to have a compare function which takes another instance of the same class. If I implement this as a virtual function in the base class, then the signature of the function has to reference the base class in derived classes also. What is the elegant way to tac... | It depends on the intended semantics of A, B, and C and the semantics of compare(). Comparison is an abstract concept that doesn't necessarily have a single correct meaning (or any meaning at all, for that matter). There is no single right answer to this question.
Here's two scenarios where compare means two completel... | I would implement it like this:
```
class A{
int a;
public:
virtual int Compare(A *other);
};
class B : A{
int b;
public:
/*override*/ int Compare(A *other);
};
int A::Compare(A *other){
if(!other)
return 1; /* let's just say that non-null > null */
if(a > other->a)
return... | Elegant Object comparison | [
"",
"c++",
"function",
"virtual",
""
] |
I'm a relatively new Java programmer coming from C++/STL, and am looking for a class with these characteristics (which the C++ std::deque has, as I understand it):
1. O(1) performance for insertion/removal at the beginning/end
2. O(1) performance for lookup by index
3. are growable collections (don't need fixed size b... | Primitive Collections for Java has an ArrayDeque with a get(int idx) method.
<http://sourceforge.net/projects/pcj>
I can't vouch for the quality of this project though.
An alternative would be to get the JDK ArrayDeque source and add the get(int idx) method yourself. Should be relatively easy.
EDIT: If you intend t... | My default approach would be to hack together my own class, with ArrayList as an underlying implementation (e.g. map my own class's indices to ArrayList indices)... but I hate reinventing the wheel especially when there's a good chance of screwing up... | Java equivalent of std::deque | [
"",
"java",
"collections",
"deque",
""
] |
I'm looking to build a query that will use the non-clustered indexing plan on a street address field that is built with a non-clustered index. The problem I'm having is that if I'm searching for a street address I will most likely be using the 'like' eval function. I'm thinking that using this function will cause a tab... | In theory the database will use whatever index is best. What database server are you using, what are you really trying to achieve, and what is your LIKE statement going to be like? For instance, where the wildcard characters are can make a difference to the query plan that is used.
Other possibilities depending on wha... | If your LIKE expression is doing a start-of-string search (`Address LIKE 'Blah%'`), I would expect the index to be used, most likely through an index seek.
If you search for `Address LIKE '%Blah%'`, a table scan/index scan will occur, depending on how many fields you return in your query and how selective the index is... | How do I write a string search query that uses the non-clustered indexing I have in place on the field? | [
"",
"sql",
"string",
"indexing",
"field",
""
] |
is there any difference between:
```
lock((IDictionary) _collection).SyncRoot)
```
or
```
lock(_collection)
``` | Yes, the Monitor is take out on a different object in each, so the two are not functional equivalents. The SyncRoot is exposed so you can lock on it for collection member access (and the collection internally uses the same for locking). This allows code in the collection and code external to it to agree upon a specific... | I believe there are two questions.
> Is it the same?
The answer to this is "it depends." It is only the same if SyncRoot is implemented by returing "this". IDictionary is an interface and there is no contract detailing what object should be returned for the SyncRoot property. The implementor is free to return "this" ... | Generics and locking on collections | [
"",
"c#",
"generics",
""
] |
I am getting back a "string[]" from a 3rd party library. I want to do a contains on it. what is the most efficient way of doing this? | Array.IndexOf:
```
bool contains = Array.IndexOf(arr, value) >= 0;
```
Or just use LINQ:
```
bool contains = arr.Contains(value);
```
LINQ should be "fast enough" for most purposes. | If you are only checking a single time, use `Array.IndexOf` or the LINQ Contains method like Marc proposed. If you are checking several times, it might be faster to first convert the string array into a `HashSet<string>`. | Fastest way to do a contains with string[] | [
"",
"c#",
""
] |
What is the worst SQL query you've ever seen? What made it bad? | ```
DELETE FROM table
```
Seen right after I typed and executed it, I had forgotten the WHERE clause. Now I always run a SELECT statement first and change the SELECT to DELETE after I am satisfied that the proper rows will be affected. | The classic [xkcd](http://xkcd.com/327/) of course:
```
WHERE name = ROBERT'); DROP TABLE students;--
``` | Worst SQL Ever? | [
"",
"sql",
"database",
""
] |
I am a .NET dev learning Java. As a result, I understand all the fundamentals of programming like loops, variables, functions, etc. My biggest bottleneck is that I don't know my way around Java's packages like I do with .NET's.
This is the reason for this thread - where do I find the following functionality in Java?:
... | [JAMon](http://jamonapi.sourceforge.net/) is one possible open-source Java Monitoring library that might fit your requirements.
In addition, any performance/management counters are exposed through [Java Management Extensions (JMX)](http://en.wikipedia.org/wiki/Java_Management_Extensions)
Then you have a number of mon... | A dictionary which uses weak keys only keeps a weak reference to each key, so if the key is otherwise eligible for garbage collection, it may be collected and the dictionary will effectively lose the entry. See the docs for [WeakReference](http://java.sun.com/javase/6/docs/api/java/lang/ref/WeakReference.html) for more... | Where can I find the following classes in Java | [
"",
"java",
""
] |
Normally when you update an object in linq2sql you get the object from a datacontext and use the same datacontext to save the object, right?
What's the best way to update a object that hasn't been retreived by that datacontext that you use to perform the save operation, i.e. I'm using flourinefx to pass data between f... | To update an existing but disconnected object, you need to "attach" it do the data context. This will re-use the existing primary key etc. You can control how to handle changes- i.e. treat as dirty, or treat as clean and track future changes, etc.
The Attach method is on the table - i.e.
```
ctx.Customers.Attach(cust... | I think you have 2 options here:
1) Attach the object to the DataContext on which you will do your save
2) Using the primary key on your object, grab an instance that is attached to your context (e.g. do a FirstOrDefault()), and then copy the data over from the modified object to the object that has a context (reflect... | Linq2SQL: Update object not created in datacontext | [
"",
"c#",
"asp.net",
"linq-to-sql",
""
] |
What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?
An example:
```
class A
{
public:
char s[1024];
char *p;
A::A()
{
p = s;
}
void changeS() const
{
p[0] = 'a';
}
};
```
Even know changeS is a const member function, it is changing the value... | I've liked this since the time i've discovered it in some code:
```
assert(condition || !"Something has gone wrong!");
```
or if you don't have a condition at hand, you can just do
```
assert(!"Something has gone wrong!");
```
The following is attributed to [@Josh](https://stackoverflow.com/users/8701/josh) (see co... | You don't need to know C++'s complicated function typedef declaration syntax. Here's a cute trick I found.
Quick, describe this typedef:
```
typedef C &(__cdecl C::* const CB )(const C &) const;
```
Easy! CB is a pointer to a member function of class C accepting a const reference to a C object and returning a non-co... | What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience? | [
"",
"c++",
"idioms",
""
] |
I have a byte array that represents a complete TCP/IP packet. For clarification, the byte array is ordered like this:
(IP Header - 20 bytes)(TCP Header - 20 bytes)(Payload - X bytes)
I have a `Parse` function that accepts a byte array and returns a `TCPHeader` object. It looks like this:
```
TCPHeader Parse( byte[] ... | A common practice you can see in the .NET framework, and that I recommend using here, is specifying the offset and length. So make your Parse function also accept the offset in the passed array, and the number of elements to use.
Of course, the same rules apply as if you were to pass a pointer like in C++ - the array ... | I would pass an [`ArraySegment<byte>`](http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx) in this case.
You would change your `Parse` method to this:
```
// Changed TCPHeader to TcpHeader to adhere to public naming conventions.
TcpHeader Parse(ArraySegment<byte> buffer)
```
And then you would change the call to ... | Working with byte arrays in C# | [
"",
"c#",
".net",
"networking",
".net-3.5",
"arrays",
""
] |
If I get a NullPointerException in a call like this:
```
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
```
I get a rather useless exception text like:
```
Exception in thread "main" java.lang.NullPointerException
at package.SomeClass.someMethod(SomeClass.java:1... | The answer depends on how you view (the contract of) your getters. If they may return `null` you should really check the return value each time. If the getter should not return `null`, the getter should contain a check and throw an exception (`IllegalStateException`?) instead of returning `null`, that you promised neve... | NPE is the most useless Exception in Java, period. It seems to be always lazily implemented and never tells exactly what caused it, even as simple as "class x.y.Z is null" would help a lot in debugging such cases.
Anyway, the only good way I've found to find the NPE thrower in these cases is the following kind of refa... | How to trace a NullPointerException in a chain of getters | [
"",
"java",
"debugging",
"nullpointerexception",
"getter",
""
] |
I have some markup like this:
```
<p><a id="1" href="#">Link 1</a></p>
<p id="1show" class="starthidden">Hi! I get shown when link 1 is clicked</p>
<p><a id="2" href="#">Link 2</a></p>
<p id="2show" class="starthidden">Hi! I get shown when link 2 is clicked</p>
<p><a id="3" href="#">Link 3</a></p>
<p id="3show" clas... | First off, numerical ID's are not valid HTML. ID attributes must start with a-z. I recommend changing your HTML like this:
```
<p><a href="#msg1">Link 1</a></p>
<p id="msg1" class="starthidden">Hi! I get shown when link 1 is clicked</p>
<p><a href="#msg2">Link 2</a></p>
<p id="msg2" class="starthidden">Hi! I get show... | Variables inside double strings aren't parsed as they are in PHP, so you must do `$(show)`. Also, the inner `click()` binding is unnecessary - you can just run the `slideToggle()`:
```
$(document).ready(function(){
$("#maincontent a").click(function () {
var id = '#' + $(this).attr("id");
var show... | Using jQuery for first time, simple problem! | [
"",
"javascript",
"jquery",
""
] |
I'm trying to create an overridden operator function using both const parameters, but I can't figure out how to do it. Here is a simple example:
```
class Number
{
Number()
{
value = 1;
};
inline Number operator + (const Number& n)
{
Number result;
result.value = value + n... | `inline` is understood in class declarations so you don't need to specify it.
Most idiomatically, you would make `operator+` a non-member function declared outside the class definition, like this:
```
Number operator+( const Number& left, const Number& right );
```
You might need to make it a `friend` of the class i... | ```
class Number
{
Number()
{
value = 1;
};
inline Number operator + (const Number& n) const
{
Number result;
result = value + n.value;
return result;
}
int value;
}
``` | Overriding an operator using const for both parameters in C++ | [
"",
"c++",
"operator-overloading",
"overriding",
"overloading",
""
] |
I've used some very large scale systems and never seen a required order, but came across it recently. Does the STL or STD library or even Boost have any cases where certain includes must come in a certain order? | > Does the STL or STD library or even Boost have any cases where certain includes must come in a certain order?
For the standard, the answer is emphatically, **no**. I imagine the same is true for Boost, though I haven't looked it up.
From the C standard:
> Standard headers may be included in any order; each may be ... | This definitely sounds like a bad design. If somehow a specific order was required, the library should provide *one* header that includes the other ones in the *correct* order.
As far as boost, and the STL, I'm pretty sure I haven't encountered this situation yet. | Is requiring a certain order for #includes in c++ a sign of bad library/header design? | [
"",
"c++",
"include",
"library-design",
""
] |
We have a (non-web app) Spring application that throws a NoSuchBeanDefinitionException when running tests on our CruiseControl continuous integration linux box. The test runs fine on Windows in Eclipse.
The exception is thrown on the getBean() method:
```
ApplicationContext context = new ClassPathXmlApplicationContex... | Solved. The instantiation of "myBean" in CONTEXT\_FILE occurred after another bean that depended on it. This really should not be an issue, but I suspect that the parser on the Linux box must be stricter. Anyway, changing the order of definitions made it work on both Windows and Linux. | Are you certain that there is a bean named "myBean" in the CONTEXT\_FILE? Are you using more than one context file? Have you turned up the Spring's logging to verify that the CONTEXT\_FILE is being loaded correctly, and furthermore, than the file Spring is loading from the classpath is the exact file you think it shoul... | How to Debug Spring NoSuchBeanDefinitionException | [
"",
"java",
"spring",
"testing",
""
] |
I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport.
I've decided on wxPython for the actual window since I'm fairly familiar with it already. However, I need to produce an OpenGL viewport that can respond... | Any reason you wouldn't use wx's [GLCanvas](http://wiki.wxpython.org/GLCanvas)? [Here's](http://code.activestate.com/recipes/325392/) an example that draws a sphere. | As a very basic 3D modelling tool I'd recommend [VPython](https://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program#50351). | Best modules to develop a simple windowed 3D modeling application? | [
"",
"python",
"opengl",
"3d",
"wxpython",
""
] |
I'm searching for a possibility to get a list of installed printers. I'm using JDK 1.6 with a Windows operating system. Does anyone know a solution?
Thank you in advance. | Just wanted to add a little snippet:
```
import javax.print.*;
class Test {
public static void main (String [] args)
{
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
System.out.println("Number of print services: " + printServices.length);
for (Prin... | I haven't used this myself, but maybe [`javax.print.PrintServiceLookup`](http://java.sun.com/javase/6/docs/api/javax/print/PrintServiceLookup.html) contains what you are looking for. | How do I get a list of installed printers? | [
"",
"java",
""
] |
What is the best way to integrate an external script into the Zend Framework? Let me explain because I may be asking this the wrong way. I have a script that downloads and parses an XML file. This script, which runs as a daily cron job, needs to dump its data into the database.
I am using Zend Framework for the site w... | In your library directory you should have your own library next to the Zend library folder. Whatever you call it (Mylib, Project, ...) you should include it into the Zend Autoloader and that's done as follows:
```
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->regi... | Yes, you should put your own classes that maybe inherit Zend Framework classes or add further classes into your own folder next to the Zend Framework folder in library.
When you have Zend\_Loader s auto-loading enabled, the class names will automatically map to the class you created, e.g.:
```
My_Db_Abstract will map... | Integrating external scripts with Zend Framework | [
"",
"php",
"zend-framework",
""
] |
I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results
```
missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]... | The trickier part about regular expressions isn't making them accept valid input, it's making them reject invalid input. For example, the second expression accepts input that is clearly wrong, including:
* `(1,2,3,4` -- one digit between each comma
* `(12,34,56` -- two digits between each comma
* `(1234......5` -- unl... | Are there nested parentheses (your regexps assume there are not)? If not:
```
whether_paren_is_missing = (astring[0] == '(' and not astring[-1] == ')')
```
To validate a dollar amount part:
```
import re
cents = r"(?:\.\d\d)" # cents
re_dollar_amount = re.compile(r"""(?x)
^ # match at the very be... | Need Help Understanding how to use less complex regex in Python | [
"",
"python",
"regex",
""
] |
What harm can come from defining BOOST\_DISABLE\_ABI\_HEADERS when compiling boost?
From the boost file: boost\_1\_37\_0\boost\config\user.hpp
```
// BOOST_DISABLE_ABI_HEADERS: Stops boost headers from including any
// prefix/suffix headers that normally control things like struct
// packing and alignment.
//#defi... | Here is a rundown of defining BOOST\_DISABLE\_ABI\_HEADERS:
* If you use some shared boost dlls, you will get undefined behavior
* If you statically link to your boost libraries, or you are sure you are only using your own dlls then you may be safe, keep reading for why I say may.
* If you use boost in several .libs i... | The define assures that the ABI ([application binary interface](http://en.wikipedia.org/wiki/Application_binary_interface)) stays compatible between versions and compilers.
Without that, your application could not use the boost dlls installed by another application (which might have been compiled with a different compi... | What harm can come from defining BOOST_DISABLE_ABI_HEADERS when compiling boost? | [
"",
"c++",
"boost",
"packing",
"bjam",
""
] |
Whenever I include boost in my project I get a million of these warnings. Does anyone know how I can get rid of the warnings?
> ../depends\boost/config/abi\_prefix.hpp(19)
> : warning C4103:
> 'depends\boost\config\abi\_prefix.hpp'
> : alignment changed after including
> header, may be due to missing #pragma
> pack(po... | The reason is that boost doesn't push/pop these pragmas in every file that needs data to be packed. They #include a separate file which does the push (abi\_prefix.hpp), and then another (abo\_suffix.hp) afterwards which does the pop.
That allows them to reuse the same #pragma pack code everywhere, which is handy as it... | Yes, you'd get that from the #pragma pack directive in config/abi/msvc\_prefix.hpp. It indicates that your project's default packing is not 8. That's pretty unusual, is this intentional? Bugs due to packing differences can be a bit tricky to diagnose. | Trying to get rid of a c++ boost warning | [
"",
"c++",
"boost",
""
] |
Did you know that :
```
Map<Object,Object> m1 = new HashMap<Object, Object>();
Map<Object,Object> m2 = new HashMap<Object, Object>();
System.out.println("m1.equals(m2) = "+m1.equals(m2));
System.out.println("m1.keySet().equals(m2.keySet()) = "
+m1.keySet().equals(m2.keySet()));
System.out.println("m1.entry... | Per the contract of [`Collection#equals()`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#equals(java.lang.Object)), there is no general-purpose equals() methods for `Collection`s, and thus `AbstractCollection` cannot provide one.
Note that `HashMap$Values` is neither a Set nor a List, thus the quand... | Both AbstractList and AbstractSet extend AbstractCollection, and they have different behaviors for their equals() methods, specified by the interfaces [List](http://java.sun.com/javase/6/docs/api/java/util/List.html#equals(java.lang.Object)) and [Set](http://java.sun.com/javase/6/docs/api/java/util/Set.html#equals(java... | Why AbstractCollection does not implement equals()? | [
"",
"java",
"collections",
"hashmap",
""
] |
As an example:
```
def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
... | I believe python decorators are just syntactic sugar.
```
@foo
def bar ():
pass
```
is the same thing as
```
def bar ():
pass
bar = foo(bar)
```
As you can see, *foo* is being called even though *bar* has not been called. This is why you see the output from your decorator function. Your output should contai... | Since you are starting with decorators, I think reading these will be helpful, so that you know the pitfalls and workarounds beforehand.
Here are two links to earlier discussions on decorators.
[Python decorator makes function forget that it belongs to a class](https://stackoverflow.com/questions/306130/python-decora... | Decorators run before function it is decorating is called? | [
"",
"python",
"django",
"decorator",
""
] |
I have this method:
```
public bool CanExecute()
```
And after 70 commits, I added an extra parameter
```
public bool CanExecute(IStation target)
```
Now the problem is I have 7 unit tests covering this CanExecute methods testing various nulls/property combinations.
Adding this simple parameter required a fix of t... | If you know that the method is likely to change yet again, I think the sensible thing to do is overload the method and *add* unit tests for the overloaded members, instead of changing old unit tests. If the stars align for you, you might even find that the overloaded methods call the original no-arg method, so you only... | Could you not keep both methods in the code? Unless it is mandatory for the IStation parameter to be non null then you could get away with it without changing any existing code.
Alternatively if the parameter has a sensible default (again, like null!), resharper can take care of changes like this very easily. To add a... | Refactoring parameters and unit tests | [
"",
"c#",
"unit-testing",
"parameters",
""
] |
The monthRegex regular expression always returns true, even if dateInput is something like "December 1, 2008" by my thoughts it should match a regular expression by whichever key I pass into it. But that isn't what happens, it just returns true, and detects "JAN" as the month.
```
function dateFormat(dateInput) {
... | Remove the "monthRegex.compile();" line and it works.
This is because monthRegex.compile(); complies "" as a regex and therefore everything matches it. | First remark: don't use Array as associative array! Use Object instead. Or use the Array in the reverse way.
Second remark: why do you use regexes for such simple search? Use indexOf instead:
```
function dateFormat(dateInput)
{
var formattedDate = "";
var the_date, month, year;
var months = new Array("",
... | Javascript Hashmap key compiled into a regular expression | [
"",
"javascript",
"regex",
""
] |
I just finished reading [this article](https://stackoverflow.com/questions/410558/why-are-exceptions-said-to-be-so-bad-for-input-validation) on the advantages and disadvantages of exceptions and I agree with the sentiment that Try-Catch blocks should not be used for "normal" control-flow management (don't use them like... | You don't need to avoid the try {} ... finally {} pattern of coding. But as far as your connections go, since they're IDisposable, use "using" instead, since it does the same thing for you as the longer and more cumbersome try/finally block. | The *bad* thing about using try-catch block everywhere is that in consuming the exception you potentially conceal bad code. Try-finally (without the catch) does not hide exceptions, but does provide code execution guarantees. In your case, you can expect certain types of exceptions even from well formed SQL commands (l... | Is Try-Finally to be used used sparingly for the same reasons as Try-Catch? | [
"",
"c#",
"asp.net",
"vb.net",
"exception",
"class",
""
] |
What is the difference between using Private Properties instead of Private Fields
```
private String MyValue { get; set; }
// instead of
private String _myValue;
public void DoSomething()
{
MyValue = "Test";
// Instead of
_myValue = "Test";
}
```
Is there any performance issue ? or just a naming convent... | Private properties allow you to abstract your internal data so that changes to the internal representation don't need to affect other parts of your implementation, even in the same class. Private fields do not offer this advantage. With automatic properties in C# 3.0, I rarely see a need to implement fields directly --... | The big gain you can get from a property (private, public, ...) is that it can produce a calculated value vs. a set value. For example
```
class Person {
private DateTime _birthday;
private int _age { get { return (DateTime.Now - _birthday).TotalYears; }
}
```
The advantage of this pattern is that only one value... | Differences between Private Fields and Private Properties | [
"",
"c#",
".net",
"properties",
""
] |
In java <1.5, constants would be implemented like this
```
public class MyClass {
public static int VERTICAL = 0;
public static int HORIZONTAL = 1;
private int orientation;
public MyClass(int orientation) {
this.orientation = orientation;
}
...
```
and you would use it like this:
```
My... | Don't know about Java, but in .NET the good practice is to put enums in parallel to the class that uses them, even if it is used by one class alone. That is, you would write:
```
namespace Whatever
{
enum MyEnum
{
}
class MyClass
{
}
}
```
Thus, you can use:
```
MyClass c = new MyClass(MyEnum... | You complicated it too much. Let's bring it all together.
Post Java 1.5 you should use the Java Enum class:
```
public enum Color
{
BLACK, WHITE;
}
```
Pre Java 1.5 you should use the type-safe Enum pattern:
```
public class Color
{
public static Color WHITE = new Color("white");
public static Color BLA... | Should you always use enums instead of constants in Java | [
"",
"java",
"coding-style",
"enums",
""
] |
This is an extension of a question I had yesterday.
I am trying to make a little php calculator that will show how much people can save on their phone bills if they switch to VoIP, and how much they can save with each service.
I have a form that will spit out the right amount for a monthly bill here:
<http://www.nex... | > I want each of the seven rows of the
> table to have one of the
> offercalcsavings values subtracted
> from the monthlybill value.
You need to do the math somewhere. Presumably you would do this before the echo statement where you output your row.
```
$offerwithsavings = $monthlybill - $offercalcsavings
```
Then j... | You can include the values.php file like this:
```
include 'path/to/values.php';
```
If you put the values in values.php in an array you can easily loop through them using a foreach loop:
in values.php;
```
$values['1calsavings'] = 24.99;
$values['2calsavings'] = 20.00;
etc;
```
Then in the other file:
```
inclu... | Basic php form help (2) | [
"",
"php",
"forms",
""
] |
What is the correct way of iterating over a vector in C++?
Consider these two code fragments, this one works fine:
```
for (unsigned i=0; i < polygon.size(); i++) {
sum += polygon[i];
}
```
and this one:
```
for (int i=0; i < polygon.size(); i++) {
sum += polygon[i];
}
```
which generates `warning: compari... | For iterating backwards see [this answer](https://stackoverflow.com/questions/275994/whats-the-best-way-to-do-a-backwards-loop-in-c-c-c#276053).
Iterating forwards is almost identical. Just change the iterators / swap decrement by increment. You should prefer iterators. Some people tell you to use `std::size_t` as the... | Four years passed, *Google* gave me this answer. With the [standard *C++11*](http://en.wikipedia.org/wiki/C++11) (aka *C++0x*) there is actually a new pleasant way of doing this (at the price of breaking backward compatibility): the new `auto` keyword. It saves you the pain of having to explicitly specify the type of t... | Iteration over std::vector: unsigned vs signed index variable | [
"",
"c++",
"stl",
"unsigned",
"signed",
""
] |
Some guy called one of my Snipplr submissions "crap" because I used `if ($_SERVER['REQUEST_METHOD'] == 'POST')` instead of `if ($_POST)`
Checking the request method seems more correct to me because that's what I really want to do. Is there some operational difference between the two or is this just a code clarity issu... | Well, they don't do the same thing, really.
`$_SERVER['REQUEST_METHOD']` contains the request method (surprise).
`$_POST` contains any post data.
It's possible for a POST request to contain no POST data.
I check the request method — I actually never thought about testing the `$_POST` array. I check the required pos... | `if ($_SERVER['REQUEST_METHOD'] == 'POST')` is the correct way, you can send a post request without any post data. | $_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST' | [
"",
"php",
""
] |
Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?
I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expec... | If you have control of both the client and server, and you can limit the client to OS X only, I second Marc's answer. Cocoa's distributed objects are an amazing technology and make RPC-style client-server apps very easy.
If the requirements above are too restrictive for you, you still have many options available to yo... | Cocoa has [Portable Distributed Objects](http://en.wikipedia.org/wiki/Portable_Distributed_Objects), which let you build a client / server application in pure Objective-C and Cocoa which can communicate across processes or across a network.
Unfortunately it's one of the harder things to learn in Cocoa. Distributed obj... | Cocoa client/server application | [
"",
"python",
"cocoa",
"web-services",
"client-server",
"pyobjc",
""
] |
I have the following data structure (a list of lists)
```
[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:... | For the first question, the first thing you should do is sort the list by the second field using [itemgetter](https://docs.python.org/3/library/operator.html#operator.itemgetter) from the operator module:
```
x = [
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ... | If you assigned it to var "a"...
python 2.x:
#1:
```
a.sort(lambda x,y: cmp(x[1], y[1]))
```
#2:
```
filter(lambda x: x[3]=="2somename", a)
```
python 3:
#1:
```
a.sort(key=lambda x: x[1])
``` | Sorting and Grouping Nested Lists in Python | [
"",
"python",
""
] |
I have a VB6 application that I am converting to .net. I am doing this in phases so clients will have both VB6 and .net applications at the same. Part of the application caches ADO 2.8 COM recordsets to a table in SQL Server and retrieves them as needed. The .net application uses that same persisted recordsets. I have ... | Generally speaking, you aren't taking enough advantage of the using statement and handling it all yourself. Unfortunately, you are doing it the wrong way, in that if you have an implementation of IDisposable which throws an exception on the call to Dispose, the other calls to Dispose do not take place. If you use the u... | If you are saying that the entire COM recordset is being persisted to a single column in the database table as a binary object (byte array), then I don't see any way around the complexity. You have to convert the byte array into the same concrete object it was serialized from (a COM recordset), before you can manipulat... | Convert persisted ADO 2.8 COM recordset to ADO.Net DataSet | [
"",
"c#",
"vb6",
"performance",
""
] |
I'm used to thinking of member functions as just being a special case of normal functions, where member functions have an extra parameter at the beginning of their parameter list for the 'this' pointer, that is, the object on which the member function is supposed to act. I've used boost::function this way in the past a... | The standard says next to nothing about where the `this` pointer should be placed, and in fact it is fairly common to use a different calling convention for member functions. (So the 'this' pointer is not just an extra first argument, it's actually stored in a different location than the first arg usually is)
In parti... | The `this` pointer is not stored along a pointer to member (member function pointers are a special case of this). If you just do
```
void (MyObject::*f)( int, int ) = &MyObject::method_that_takes_two_ints;
```
then what is stored is just the information which member function should be called on a objet which you late... | C++, equivalence between pointer-to-functions and pointer-to-member-functions? | [
"",
"c++",
"boost",
"function-pointers",
""
] |
I am developing a PHP-based login system.
Each user has an ID(a number) and a password, which is stored as a salted hash.
I am able to figure out if a login is sucessful or not, but now I need to store that information somewhere(so that the user is not permanently logged out).
In the past, I've played with $\_SESSION... | I want to reiterate Eran's point **never** store the users password or even a hash of the password in session or cookie data.
In general I've implemented the remember me functionality in web apps using Cookies. A good place to start for information on building a "secure" persistent login system is this [blog post on t... | For sensitive information (ie, authentication results) use only sessions. Sessions are stored server side and are much less likely to be compromised.
Regarding session lifetime, the default is the lifetime of the browser session - but you can control that. There are several settings that affect that:
session.gc\_maxl... | PHP Login system using Cookies and Salted Hashes | [
"",
"php",
"session",
"authentication",
"cookies",
""
] |
In Visual Studio (C++), is there a way to easily find duplicate headers that are defined in .cpp files?
I'm also trying to find ways to detect this situation:
* A includes B includes C
* A includes C
* => A doesn't need to include C | If you want to detect this situation you could add this macro to the top of every file. Substitute A for the name of the file
```
#if A_H
#error "Duplicate include"
#else
#define A_H
#endif
``` | Generally, you mark them with #pragma once, or the equivalent macro guard and stop caring about it.
If you're using MS compiler, you can put a #pragma message (IIRC, it might be a #pragma warning or #pragma error instead) with the name of the header file at the very top of each header file and your build output will s... | How can I find duplicate headers in a large solution in MSVC++ 2005 or 2008? | [
"",
"c++",
"visual-c++",
"header",
"include",
""
] |
Is it possible to make the text in a TextBox unselectable without disabling the TextBox?
It's a RichTextBox and I need it's formatting and selection features.
I can't disable it because I want to handle MouseMove and MouseDown events.
So far I've thought about disabling the Text box and putting a panel on top of it wh... | What about dealing with the .Enter or .GotFocus events to clear any selection made?
You can see the opposite of what you wanted in [Automatically select all text on focus in WinForms TextBox](https://stackoverflow.com/questions/97459/automatically-select-all-text-on-focus-in-winforms-textbox). | How about handling selection change event like this:
```
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
this.richTextBox1.SelectionStart = this.richTextBox1.Text.Length;
}
``` | How to make text in a WinForms TextBox unselectable without disabling it? | [
"",
"c#",
"winforms",
"textbox",
""
] |
Could anyone explain me why:
```
function doAjax() {
var xmlHttpReq = false;
try { // Firefox, Opera 8.0+ and Safari
xmlHttpReq = new XMLHttpRequest();
}
catch (e) { // Internet Explorer
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
... | It would be more sensible to use framework like jQuery (especially if you seriously want to support older versions of IE (pre v6) ) but I'll assume there is a reason you're not doing that.
It would be better if a) you don't nest try-catches and b) you factored out a set of functions namely one to get an Xhr object, an... | Regarding the **first error**, here is an [exerpt from the JSLint Documentation](http://www.jslint.com/lint.html):
> **Undefined Variables and Functions**
>
> JavaScript's biggest problem is its
> dependence on global variables,
> particularly implied global variables.
> If a variable is not explicitly
> declared (usu... | What's causing these javascript validation errors (Implied global and already defined var)? | [
"",
"javascript",
"ajax",
"validation",
""
] |
I've been a web developer for some time now, and have recently started learning some functional programming. Like others, I've had some significant trouble applying many of these concepts to my professional work. For me, the primary reason for this is that FP's goal of remaining stateless seems quite at odds with the f... | First of all, I would not say that CLOS (Common Lisp Object System) is "pseudo-OO". It is first class OO.
Second, I believe that you should use the paradigm that fits your needs.
You cannot statelessly store data, while a function is flow of data and does not really need state.
If you have several needs intermixed, ... | Coming at this from the perspective of a database person, I find that front-end developers try too hard to find ways to make databases fit their model rather than considering the most effective ways to use databases which are not object oriented or functional but relational and using set-theory. I have seen this genera... | Are Databases and Functional Programming at odds? | [
"",
"sql",
"database",
"functional-programming",
"lisp",
""
] |
Has anyone used [Hudson](http://hudson.dev.java.net/) as a Continuous-Integration server for a C++ project using [UnitTest++](http://unittest-cpp.sourceforge.net/) as a testing library?
How exactly did you set it up?
I know there have been several questions on Continuous Integration before, but I hope this one has a ... | We are actively doing this at my workplace.
Currently, we use a free-style software project to:
* Check our Subversion repository for updates every 15 minutes
* Call a windows batch file to clean and build a solution file
+ Project files build and run unit tests as a post-build event
+ Unit test failures are retu... | I checked the [xUnit](http://wiki.hudson-ci.org/display/HUDSON/xUnit+Plugin) plugin, as Patrick Johnmeyer suggested in the accepted answer. For completeness sakes, here is the driver code:
```
#include <fstream>
#include "UnitTest++.h"
#include "XmlTestReporter.h"
int main( int argc, char *argc[] ) {
std::ofstrea... | Hudson, C++ and UnitTest++ | [
"",
"c++",
"unit-testing",
"continuous-integration",
"hudson",
"jenkins",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.