Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
private IEnumerable<string> Tables
{
get
{
yield return "Foo";
yield return "Bar";
}
}
```
Let's say I want iterate on those and write something like processing #n of #m.
Is there a way I can find out the value of m without iterating before my main iteration?
I hope I made myself clea... | `IEnumerable` doesn't support this. This is by design. `IEnumerable` uses lazy evaluation to get the elements you ask for just before you need them.
If you want to know the number of items without iterating over them you can use `ICollection<T>`, it has a `Count` property. | The `System.Linq.Enumerable.Count` extension method on `IEnumerable<T>` has the following implementation:
```
ICollection<T> c = source as ICollection<TSource>;
if (c != null)
return c.Count;
int result = 0;
using (IEnumerator<T> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
res... | Count the items from a IEnumerable<T> without iterating? | [
"",
"c#",
".net",
"ienumerable",
""
] |
I need to show only one element at a time when a link is clicked on. Right now I'm cheating by hiding everything again and then toggling the element clicked on. This works, unless i want EVERYTHING to disappear again. Short of adding a "Hide All" button/link what can i do? I would like to be able to click on the link a... | ```
$("#linkgarykhit").click(function(){
if($("#infogarykhit").css('display') != 'none'){
$("#infogarykhit").hide();
}else{
$("#infocontent *").hide();
$("#infogarykhit").show();
}
return false;
});
```
---
We could also [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) this up... | If your markup "naming scheme" is accurate, you can avoid a lot of repetitious code by using a RegEx for your selector, and judicious use of jQuery's "not".
You can attach a click event one time to a jQuery collection that should do what you want so you don't need to add any JavaScript as you add more Jim's or John's,... | Show Only One Element with JQuery | [
"",
"javascript",
"jquery",
""
] |
What is the best way to check for the existence of a session variable in ASP.NET C#?
I like to use `String.IsNullOrEmpty()` works for strings and wondered if there was a similar method for `Session`. Currently the only way I know of is:
```
var session;
if (Session["variable"] != null)
{
session = Session["va... | To follow on from what others have said. I tend to have two layers:
**The core layer. This is within a DLL that is added to nearly all web app projects**. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following:
```
public class SessionVar
{
... | That is pretty much how you do it. However, there is a shorter syntax you can use.
```
sSession = (string)Session["variable"] ?? "set this";
```
This is saying if the session variables is null, set sSession to "set this" | What is the best way to determine a session variable is null or empty in C#? | [
"",
"c#",
"asp.net",
"session",
""
] |
I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead.
I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as:
```
vector<vector<double> > matrix(n,vector<double>(n));
```
and accessed through `matrix[i... | If you're using GCC the compiler can analyze your matrix accesses and change the order in memory in certain cases. The magic compiler flag is defined as:
```
-fipa-matrix-reorg
```
> Perform matrix flattening and
> transposing. Matrix flattening tries
> to replace a m-dimensional matrix with
> its equivalent n-dimens... | My guess would be the fastest is, for a matrix, to use 1D STL array and override the () operator to use it as 2D matrix.
However, the STL also defines a type specifically for non-resizeable numerical arrays: valarray. You also have various optimisations for in-place operations.
valarray accept as argument a numerical... | Optimising C++ 2-D arrays | [
"",
"c++",
"linux",
"optimization",
"gcc",
"stl",
""
] |
Ok, I'm using the term "Progressive Enhancement" kind of loosely here but basically I have a Flash-based website that supports deep linking and loads content dynamically - what I'd like to do is provide alternate content (text) for those either not having Flash and for search engine bots. So, for a user with flash they... | There's an inherent problem with what you're trying to achieve.
The URL hash (or anchor) is client-side only - that token is not sent to the server. This means the only way (that I know of) to load the content you need for example.com/#some\_page is to use AJAX, which can read the hash and then request the page-specif... | Well, according to [OSFlash](http://osflash.org/open_source_flash_projects) (the open source flash people) both [CakePHP](http://cakephp.org/) and [PHPWCMS](http://www.phpwcms.de/) can do what you need, although from a first glance at their sites' feature list, it is not entirely obvious.
Let us know if they ***do*** ... | Does anyone know of a php framework that would handle progressive enhancement for Flash/Flex content? | [
"",
"php",
"apache-flex",
"flash",
"actionscript-3",
"progressive-enhancement",
""
] |
Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?
The methods that I have identified thus far are:
* `save()`
* `update()`
... | Here's my understanding of the methods. Mainly these are based on the [API](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html) though as I don't use all of these in practice.
**saveOrUpdate**
Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise... | ```
╔══════════════╦═══════════════════════════════╦════════════════════════════════╗
║ METHOD ║ TRANSIENT ║ DETACHED ║
╠══════════════╬═══════════════════════════════╬════════════════════════════════╣
║ ║ sets id if doesn't ║ sets new id even if... | What are the differences between the different saving methods in Hibernate? | [
"",
"java",
"hibernate",
"persistence",
""
] |
---
**The [HttpRequestPool](http://docs.php.net/manual/en/class.httprequestpool.php) class provides a solution. Many thanks to those who pointed this out.**
A brief tutorial can be found at: <http://www.phptutorial.info/?HttpRequestPool-construct>
---
**Problem**
I'd like to make concurrent/parallel/simultaneous H... | I'm pretty sure [HttpRequestPool](http://docs.php.net/manual/en/class.httprequestpool.php) is what you're looking for.
To elaborate a little, you can use forking to achieve what you're looking for, but that seems unnecessarily complex and not very useful in a HTML context. While I haven't tested, this code should be i... | Did you try [HttpRequestPool](http://www.php.net/manual/en/class.httprequestpool.php) (it's part of Http)? It looks like it would pool up the request objects and work them. I know I read somewhere that Http would support simultaneous requests and aside from *pool* I can't find anything either. | Parallel HTTP requests in PHP using PECL HTTP classes [Answer: HttpRequestPool class] | [
"",
"php",
"http",
"parallel-processing",
"pecl",
"simultaneous",
""
] |
I need a (php) regex to match Yahoo's username rules:
> Use 4 to 32 characters and start with a letter. You may use letters, numbers, underscores, and one dot (.). | ```
/^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/
```
Or a little shorter:
```
/^[a-z](?=[\w.]{3,31}$)\w*\.?\w*$/i
``` | ```
/[a-zA-Z][a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*/
```
And check if strlen($username) >= 4 and <= 32. | Yahoo Username Regex | [
"",
"php",
"regex",
"validation",
"yahoo",
""
] |
I need to get just the first item (actually, just the first key) off a rather large associative array in JavaScript. Here's how I'm doing it currently (using jQuery):
```
getKey = function (data) {
var firstKey;
$.each(data, function (key, val) {
firstKey = key;
return false;
});
return... | There isn't really a **first** or **last** element in associative arrays (i.e. objects). The only order you can hope to acquire is the order the elements were saved by the parser -- and no guarantees for consistency with that.
But, if you want ***the first to come up***, the classic manner might actually be a bit easi... | You can avoid having to create a function by referencing the first entry returned from `Object.keys()`:
```
var firstKey = Object.keys(data)[0];
```
For the first entry from a sorted key list, simply add a call to the `.sort()` method:
```
var firstKey = Object.keys(data).sort()[0];
``` | What is the most efficient way to get the first item from an associative array in JavaScript? | [
"",
"javascript",
"jquery",
"arrays",
"associative",
""
] |
If I switch on the generating of debug info with Javac then the class files are 20-25% larger. Has this any performance effects on running the Java program? If yes on which conditions and how many. I expect a little impact on loading the classes because the files are larger but this should be minimal. | In any language, debugging information is meta information. It by its nature increases the size of the object files, thus increasing load time. During execution outside a debugger, this information is actually completely ignored. As outlined (although not clearly) in the [JVM spec](http://java.sun.com/docs/books/jvms/s... | Turning off debugging alone should not make a difference at all. But once you turn off debugging and turn on optimization, you should see a difference, as this makes some static optimizations at compile time. This way even your hot-spot optimized code gets faster at runtime.
But so far, the tradeoff between getting me... | Is there a performance difference between Javac debug on and off? | [
"",
"java",
"performance",
"debugging",
"javac",
""
] |
Similar to [this question](https://stackoverflow.com/questions/233030/worst-php-practice-found-in-your-experience)...
What are the worst practices you actually found in Java code?
Mine are:
* using instance variables in servlets (it's not just bad practice but bug, actually)
* using Collection implementations like H... | I had to maintain java code, where most of the Exception handling was like:
```
catch( Exception e ) {}
``` | Once I encountered 'singleton' exception:
```
class Singletons {
public static final MyException myException = new MyException();
}
class Test {
public void doSomething() throws MyException {
throw Singletons.myException;
}
}
```
**Same instance of exception** was thrown each time ... with exact ... | Worst Java practice found in your experience? | [
"",
"java",
""
] |
I need the "Select Data Source" dialog added to my application so that the user can manually select a range (or ranges) in Excel and the range is pasted in my text box. This functionality is everywhere in Excel (most notably when selecting a range for a chart). How can I easily do this? | have you tried using the refedit control?
[How to Use the RefEdit Control with a UserForm](http://support.microsoft.com/kb/213776) | ```
Dim myRange As Range
On Error Resume Next
Set myRange = Application.InputBox(prompt:="Select the cells you want", Type:=8)
On Error GoTo 0
If myRange Is Nothing Then
MsgBox "User cancelled"
Else
MsgBox "User selected " & myRange.Address
End If
```
This will show an input dialog. Don't type anyt... | How to add "Select Data Source" to my Excel application? | [
"",
"c#",
"excel",
"user-interface",
""
] |
I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:
```
t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
```
In [my markup language](http://freehg.org/u/cheery/aml/) parser I match unicode characters by allowing a... | the [re](http://docs.python.org/library/re#regular-expression-syntax) module supports the \w syntax which:
> If UNICODE is set, this will match the
> characters [0-9\_] plus whatever is
> classified as alphanumeric in the
> Unicode character properties database.
therefore the following examples shows how to match uni... | You need pass pass parameter reflags in lex.lex:
```
lex.lex(reflags=re.UNICODE)
``` | Match unicode in ply's regexes | [
"",
"python",
"regex",
"unicode",
"ply",
"character-properties",
""
] |
I have seen various rules for naming stored procedures.
Some people prefix the sproc name with usp\_, others with an abbreviation for the app name, and still others with an owner name. You shouldn't use sp\_ in SQL Server unless you really mean it.
Some start the proc name with a verb (Get, Add, Save, Remove). Others... | For my last project i used usp\_[Action][Object][Process] so for example, usp\_AddProduct or usp\_GetProductList, usp\_GetProductDetail. However now the database is at 700 procedures plus, it becomes a lot harder to find all procedures on a specific object. For example i now have to search 50 odd Add procedures for the... | **Here's some clarification about the sp\_ prefix issue in SQL Server.**
Stored procedures named with the prefix sp\_ are system sprocs stored in the Master database.
If you give your sproc this prefix, SQL Server looks for them in the Master database first, then the context database, thus unnecessarily wasting resou... | What is your naming convention for stored procedures? | [
"",
"sql",
"stored-procedures",
"naming-conventions",
""
] |
What is the difference between UTF and UCS.
What are the best ways to represent not European character sets (using UTF) in C++ strings. I would like to know your recommendations for:
* Internal representation inside the code
+ For string manipulation at run-time
+ For using the string for display purposes.
* Best... | > What is the difference between UTF and UCS.
UCS encodings are fixed width, and are marked by how many bytes are used for each character. For example, UCS-2 requires 2 bytes per character. Characters with code points outside the available range can't be encoded in a UCS encoding.
UTF encodings are variable width, an... | Have you read Joel Spolsky's article on [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)? | UTF usage in C++ code | [
"",
"c++",
"unicode",
"locale",
"utf",
"ucs",
""
] |
In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)".
Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top?
For the moment I use thi... | **Edit**: Since jQuery 1.3, this has been built in as the [`closest()`](http://api.jquery.com/closest) function. eg: `$('#foo').closest('.bar');`
---
yep - parents() traverses up the tree.
```
<div id="a">
<div id="b">
<p id="c">
<a id="d"></a>
</p>
</div>
</div>
```
`$('#d').par... | *Adding to @[nickf](https://stackoverflow.com/users/9021/nickf)'s answer:*
jQuery 1.3 simplifyed this task with `closest`.
Given a DOM:
```
<div id="a">
<div id="b">
<p id="c">
<a id="d"></a>
</p>
</div>
</div>
```
You can do:
```
$('#d').closest("div"); // returns [ div#b ]
```... | nearest ancestor node in jQuery | [
"",
"javascript",
"jquery",
"dom",
""
] |
Let's say I have the following ruby code :
```
def use_object(object)
puts object.some_method
end
```
and , this will work on any object that responds to **some\_method**,right?
Assuming that the following java interface exists :
```
interface TestInterface {
public String some_method();
}
```
Am I right to p... | You are right except that you can not define the body of a function in Java Interfaces, only prototypes.
Interfaces are the only way to implemente a pseudo multi-derivation in Java, since normal class derivation is only simple (just one parent). | No, interfaces in are not implemented. You can have multiple implementations of it though.
An interface would look more like:
```
interface TestInterface {
public String some_method();
}
```
And it could be implemented in a class:
```
public class TestClass implements TestInterface {
public String some_method... | question about java interfaces | [
"",
"java",
"ruby",
""
] |
I am trying to place a big number in a C++ variable. The number is 600851475143
I tried unsigned long long int but got an error saying it the constant was too big.
I then tried a bigInt library called BigInt -> <http://mattmccutchen.net/bigint/>
The problem is I can't compile the code as I get many errors regarding t... | You can specify an integer literal as long by the suffix L.
You can specify an integer literal as long long by the suffix LL.
```
#include <iostream>
int main()
{
long long num = 600851475143LL;
std::cout << num;
}
``` | The number is 600851475143 isn't too large for a long long int but you need to use the LL suffix when using a long long constants (ULL for unsigned long long int):
```
unsigned long long int num = 600851475143ULL;
``` | Big number in C++ | [
"",
"c++",
"biginteger",
""
] |
I'm trying to get authentication working to my liking in a CakePHP app and running into a snag.
I want to let the user login from either the home page or from a dedicated login page. I'm using the Auth component to manage login and right now the login itself works. I am submitting the form on the home page to /Users/L... | in the AppController
```
public function beforeFilter( )
{
$this->Auth->autoRedirect = false;
}
```
in UsersController
```
public function login( )
{
if( $this->Auth->user( ) )
{
$this->redirect( array(
'controller' => 'users' ,
'action' => 'index' ,
))... | Yes auth has a feature where it will redirect you to the page you tried to access before logging in. If setting the loging redirect did not work, you can try to set the loginRedirect to false and do a manual ($this->redirect([..] ) in the UsersController::login action. | How do I get the loginRedirect from multiple login locations in CakePHP? | [
"",
"php",
"cakephp",
""
] |
I am writing my own Joomla component (MVC), its based heavily on the newsflash module, because I want to display the latest 5 content items in a sliding tabbed interface, all the hard work is done, but I am having real difficult getting content out of the for loop.
Here is the code I have so far
default.php
```
<ul i... | You said, you tried `if $i = 0`, the [comparison operator](http://www.php.net/operators.comparison) in PHP is `==`, with your if you have an endless loop, because in each iteration you assign 0 to $i, and it never reaches $n, you should do inside your loop:
```
if ($i == 0){
// First Item here...
}else{
// Other ... | I think @CMS is correct.
You might also want to think about handling the first item outside the loop and letting the loop handle the rest of the items. This way you don't have to make the check on each pass through the loop. | Getting the first item out of a For loop | [
"",
"php",
"joomla",
"for-loop",
""
] |
I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand.
If I pass in a lambda expression like:
```
p => p.Title == "title"
```
everything works.
However, if my lambda expression looks like:
```
p => p.Title == myaspdropdown.SelectedValue
``... | Remember that when you're dealing with the lambda expression as an expression tree, you don't have executable code. Rather you have a tree of expression elements, that make up the expression you wrote.
Charlie Calvert has [a good post](https://learn.microsoft.com/en-us/archive/blogs/charlie/expression-tree-basics) tha... | To get the actual value, you need to apply the logic of the expression tree to whatever context you've got.
The whole point of expression trees is that they represent the *logic* as data rather than evaluating the expression. You'll need to work out what the lambda expression truly means. That may mean evaluating some... | Lambda Expression Tree Parsing | [
"",
"c#",
"lambda",
"expression-trees",
""
] |
I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had:
```
void func()
{
char c;
int i;
short s;
...
}
```
We would reorder this to be:
```
void func()
{... | As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that.
It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment.
IIRC newer MSVC compilers use that freedo... | Not only can the compiler reorder the stack layout of the local variables, it can assign them to registers, assign them to live sometimes in registers and sometimes on the stack, it can assign two locals to the same slot in memory (if their live ranges do not overlap) and it can even completely eliminate variables. | Can a C compiler rearrange stack variables? | [
"",
"c++",
"c",
"compiler-construction",
"alignment",
"callstack",
""
] |
I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a `java.util.HashMap<java.awt.Point, Segment>`. However, I keep getting an OutOfMemory exception. (`Segment` is my own class - very light weight - one `String` field, and 3 `int` fields).
```
Exception in thread "main" java.lang.OutOfMemoryErr... | You can increase the maximum heap size by passing -Xmx128m (where 128 is the number of megabytes) to java. I can't remember the default size, but it strikes me that it was something rather small.
You can programmatically check how much memory is available by using the [Runtime](http://java.sun.com/javase/6/docs/api/ja... | Some people are suggesting changing the parameters of the HashMap to tighten up the memory requirements. I would suggest to **measure instead of guessing**; it might be something else causing the OOME. In particular, I'd suggest using either [NetBeans Profiler](http://profiler.netbeans.org/) or [VisualVM](https://visua... | Why do I get an OutOfMemoryError when inserting 50,000 objects into HashMap? | [
"",
"java",
"hashmap",
"out-of-memory",
""
] |
Back in the 90s when I first started out with MFC I used to dynamically link my apps and shipped the relevant MFC DLLs. This caused me a few issues (DLL hell!) and I switched to statically linking instead - not just for MFC, but for the CRT and ATL. Other than larger EXE files, statically linking has never caused me an... | There are some downsides:
* Bigger exe size (esp if you ship multiple exe's)
* Problems using other DLL's which rely on or assume dynamic linking (eg: 3rd party DLL's which you cannot get as static libraries)
* Different c-runtimes between DLL's with independent static linkage (no cross-module allocate/deallocate)
* N... | Most of the answers I hear about this involve sharing your dll's with other programs, or having those dll's be updated without the need to patch your software.
Frankly I consider those to be downsides, not upsides. When a third party dll is updated, it can change enough to break your software. And these days, hard dri... | Static or dynamic linking the CRT, MFC, ATL, etc | [
"",
"c++",
"mfc",
"linker",
""
] |
I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multi... | Use a Tracer object. Something like this:
```
class Tracer
{
public:
Tracer(const char *functionName) : functionName_(functionName)
{
cout << "Entering function " << functionName_ << endl;
}
~Tracer()
{
cout << "Exiting function " << functionName_ << endl;
}
const char *functionName_;
};
```
N... | While the debugger is attached to a process, you can rightclick in the source code and select "breakpoint->add TracePoint", with the text you want (even some macro's are supplied).
The Tracepoint is in fact a BreakPoint with the "When Hit" field on some message printer functionality, and it doesn't actually break the ... | What's a quick way to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program? | [
"",
"c++",
"visual-studio-2005",
"trace",
"activemq-classic",
"visual-c++-2005",
""
] |
Accidentally I may forget to describe some parameters or exception throwing (or something else) when documenting methods or classes, etc.
Is it possible to run javadoc in such a way that it warns me about missing documentation items?
(I use ant script for generating documentation) | Use [Checkstyle](http://checkstyle.sourceforge.net/)! It has awesome Ant integration and supports 100s of other important checks to your source code too.
The [JavadocType checker](http://checkstyle.sourceforge.net/config_javadoc.html) is what you'll need though. | I do not know of any javadoc option that will issue a warning about non-documented items.
However, if You happen to use Eclipse, take a look at the settings in
Window -> Preferences -> Java -> Compiler -> Javadoc
There, You can tell Eclipse to issue warnings on undocumented items. | Is it possible to obtain warnings from javadoc when something missed in javadoc-comments? | [
"",
"java",
"documentation",
"javadoc",
""
] |
While developing a C++ application, I had to use a third-party library which produced a huge amount of warnings related with a harmless #pragma directive being used.
```
../File.hpp:1: warning: ignoring #pragma ident
In file included from ../File2.hpp:47,
from ../File3.hpp:57,
from Fi... | I believe you can compile with
```
-Wno-unknown-pragmas
```
to suppress these. | In GCC, compile with -Wno-unknown-pragmas
In MS Visual Studio 2005 (this question isn't tagged with gcc, so I'm adding this for reference), you can disable globally in Project Settings->C/C++->Advanced. Enter 4068 in "Disable Specific Warnings"
or you can add this to any file to disable warnings locally
```
#pragma ... | How can I disable #pragma warnings? | [
"",
"c++",
"warnings",
"pragma",
""
] |
I've been running the built-in [Ant](http://ant.apache.org/) from the command line on a Macintosh (10.5.5) and have run into some trouble with the **Mail** task. Running the Mail task produces the following message:
```
[mail] Failed to initialise MIME mail: org.apache.tools.ant.taskdefs.email.MimeMailer
```
This is ... | Here's what I ended up doing to resolve the problem:
1. Downloaded the latest version of Ant from <http://ant.apache.org/>
2. The "built-in" Ant is installed in /usr/share/ant; I didn't want to overwrite that version so I extracted the new, full version into /usr/***local***/share/apache-ant-1.7.1/
3. As [npellow](htt... | Download the Java Mail libraries from: <http://java.sun.com/products/javamail/> .
You will also need <http://java.sun.com/products/javabeans/glasgow/jaf.html>
A list of all external dependencies required by Ant's optional tasks are outlined here <http://ant.apache.org/manual/index.html> .
Another way to get dependenc... | Missing ant-javamail.jar file on Macintosh | [
"",
"java",
"macos",
"ant",
""
] |
Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables tha... | Executive summary: In virtually all scenarios, it doesn't matter, but there is a slight advantage for local variables.
Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond.
Warning: In your scenario, performance shouldn't be the question, but... | I'd prefer the local variables on general principles, because they minimize evil mutable state in your program. As for performance, your profiler will tell you all you need to know. Locals should be faster for ints and perhaps other builtins, because they can be put in registers. | C++ performance of accessing member variables versus local variables | [
"",
"c++",
"performance",
""
] |
Does the C++ compiler optimize the multiply by two operation `x*2` to a bitshift operation `x<<1`?
I would love to believe that yes. | Actually VS2008 optimizes this to x+x:
```
01391000 push ecx
int x = 0;
scanf("%d", &x);
01391001 lea eax,[esp]
01391004 push eax
01391005 push offset string "%d" (13920F4h)
0139100A mov dword ptr [esp+8],0
01391012 call dword ptr [__imp__scanf (13920A4... | This article from Raymond Chen could be interesting:
**When is x/2 different from x>>1?** :
<http://blogs.msdn.com/oldnewthing/archive/2005/05/27/422551.aspx>
Quoting Raymond:
> > Of course, the compiler is free to recognize this and rewrite your multiplication or shift operation. In fact, it is very likely to do th... | Do modern compilers optimize the x * 2 operation to x << 1? | [
"",
"c++",
"optimization",
"compiler-construction",
""
] |
I would like to be able to fetch a web page's html and save it to a `String`, so I can do some processing on it. Also, how could I handle various types of compression.
How would I go about doing that using Java? | Here's some tested code using Java's [URL](http://java.sun.com/javase/6/docs/api/java/net/URL.html) class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.
```
public static void main(String[] args) {
URL url;
InputStream is = null;
Buffered... | I'd use a decent HTML parser like [Jsoup](http://jsoup.org). It's then as easy as:
```
String html = Jsoup.connect("http://stackoverflow.com").get().html();
```
It handles GZIP and chunked responses and character encoding fully transparently. It offers more advantages as well, like HTML [traversing](http://jsoup.org/... | How do you Programmatically Download a Webpage in Java | [
"",
"java",
"http",
"compression",
""
] |
What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row... | ```
SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n
``` | Actually the right way to get last n rows in order is to use a subquery:
```
(SELECT id, title, description FROM my_table ORDER BY id DESC LIMIT 5)
ORDER BY tbl.id ASC
```
As this way is the only I know that will return them in right order. The accepted answer is actually a solution for "*Select first 5 rows from a ... | What's the most efficient way to select the last n rows in a table without changing the table's structure? | [
"",
"mysql",
"sql",
""
] |
I'm trying to learn about catamorphisms and I've read [the Wikipedia article](http://en.wikipedia.org/wiki/Catamorphism) and the first couple posts in [the series of the topic for F#](http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!256.entry) on the *Inside F#* blog.
I understand that it's a generalization... | LINQ's `Aggregate()` is just for `IEnumerables`. Catamorphisms in general refer to the pattern of folding for an arbitrary data type. So `Aggregate()` is to `IEnumerables` what `FoldTree` (below) is to `Trees` (below); both are catamorphisms for their respective data types.
I translated some of the code in [part 4 of ... | I've been doing more reading, including a Micorosft Research paper on [functional programming with catamorphisms ("bananas")](http://research.microsoft.com/~emeijer/Papers/fpca91.pdf), and it seems that ***catamorphism*** just refers to any function that takes a list and typically breaks it down to a single value (`IEn... | What is a catamorphism and can it be implemented in C# 3.0? | [
"",
"c#",
"f#",
"functional-programming",
"catamorphism",
"recursion-schemes",
""
] |
What would you recommend for class that needs to keep a list of unique integers?
I'm going to want to Add() integers to the collection and also check for existence e.g. Contains().
Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21". | [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx):
> The `HashSet<T>` class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...
>
> The capacity of a `HashSet<T>` object is the number of elements that the o... | In my testing, I have found that a Dictionary with a dummy value is faster than a HashSet, when dealing with very large sets of data (100,000+ in my case). I expect this is because the Dictionary allows you to set an initial capacity, but I don't really know. In the case you're describing, I would probably use the Dict... | Recommended .NET Class for a collection of unique integers? | [
"",
"c#",
".net",
""
] |
We all know you can't do the following because of `ConcurrentModificationException`:
```
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
```
But this apparently works sometimes, but not always. Here's some specific code:
```
public static void main(String[] args) {
Collection<Integer> l... | [`Iterator.remove()`](https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--) is safe, you can use it like this:
```
List<String> list = new ArrayList<>();
// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing... | This works:
```
Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
if (iter.next() == 5) {
iter.remove();
}
}
```
I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this `.remove()` functionality. | Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop | [
"",
"java",
"collections",
"iteration",
""
] |
I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files.
Here is how I have the library and application folders set up. (I'm not sure if this is right)
```
AppFolder
App.sln
App.ncb
*.h
*.cpp
Debug
... | On the project properties:
Configuration Properties -> Linker -> Input -> Additional Dependancies
Add it in there.
Or, in your .h file for the library, add:
```
#pragma comment(lib, "Library")
```
This will do it automatically for you. | The VC++ directories is the list of directory locations to searched during linking. It is not a list of libraries to be linked in.
You need to add the lib file to the ***Additional Dependencies*** field of the ***Project Linker*** settings. | Having trouble linking a static library C++ | [
"",
"c++",
"static",
"linker",
""
] |
I have the following code:
```
class IncidentTag:
def __init__(self,tag):
self.tag = tag
def equals(self,obj):
return self.tag.equals(obj.tag)
def hashCode(self):
return self.tag.hashCode()
from java.lang import String
from java.util import HashMap
from java.util import HashSet
... | You shouldn't implemented the Java-Style equals and hashCode method, but instead the Python equivaltents `__eq__` and `__hash__`. Adding
```
def __hash__(self):
return self.hashCode()
def __eq__(self, o):
return self.equals(o)
```
helps.
These python methods are - as far as I know - dynamically bound to hashC... | I wrote equivalent code in Java and it does produce true for all three contains() calls. So I think this must be an oddity in Jython. Maybe the underlying Java objects are not exactly what you see them as in Python. | HashSet problem -- equals and hashCode with contains working differently than I'd expect | [
"",
"java",
"collections",
"jython",
"hashset",
""
] |
I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method'
```
List<MyType> myList = GetMyList();
myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } );
```
What am I missing?
Here are some references I found... | I think you want:
```
myList.Sort( delegate (MyType t1, MyType t2)
{ return (t1.ID.CompareTo(t2.ID)); }
);
```
To sort you need something other than "true/false", you need to know if its equal to, greater than, or less than. | The Sort doesn't take a binary predicate, it takes a `Comparison<T>` delegate which returns an `int` not a `bool`.
The return values are `0` for when the items are equal, `<0` for when the first item is less than the second, and `>0` for when the first item is greater than the second. | Problem sorting lists using delegates | [
"",
"c#",
".net",
"closures",
""
] |
Here's the XML code I'm working with:
```
<inventory>
<drink>
<lemonade supplier="mother" id="1">
<price>$2.50</price>
<amount>20</amount>
</lemonade>
<lemonade supplier="mike" id="4">
<price>$3.00</price>
<amount>20</amount>
</lemonad... | Try this:
```
//lemonade[@id="1"]/price
```
or
```
//lemonade[@supplier="mother"]/price
```
Without the "@" it looks for child elements with that name instead of attributes. | This is only tangentially related, but when you use XPath on a document for which you know the structure, *don't* use "//some-element-name". It's very nice for a quick example, but when you hit a huge xml file with that query, particularly if it is followed by something complex, you will quickly run into performance is... | XPath query with PHP | [
"",
"php",
"xml",
"xpath",
""
] |
Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string. | Take a look at the [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) method. | Its pretty simple. Assume that your classname is `Car` and the namespace is `Vehicles`, then pass the parameter as `Vehicles.Car` which returns object of type `Car`. Like this you can create any instance of any class dynamically.
```
public object GetInstance(string strFullyQualifiedName)
{
Type t = Type... | Create an instance of a class from a string | [
"",
"c#",
".net",
"instantiation",
"system.type",
""
] |
Without routing, `HttpContext.Current.Session` is there so I know that the `StateServer` is working. When I route my requests, `HttpContext.Current.Session` is `null` in the routed page. I am using .NET 3.5 sp1 on IIS 7.0, without the MVC previews. It appears that `AcquireRequestState` is never fired when using the rou... | Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:
```
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webSer... | Just add attribute `runAllManagedModulesForAllRequests="true"` to `system.webServer\modules` in web.config.
This attribute is enabled by default in MVC and Dynamic Data projects. | HttpContext.Current.Session is null when routing requests | [
"",
"c#",
"asp.net",
"routes",
"session-variables",
""
] |
Is there a class in the standard library of .NET that gives me the functionality to create random variables that follow Gaussian distribution? | Jarrett's suggestion of using a Box-Muller transform is good for a quick-and-dirty solution. A simple implementation:
```
Random rand = new Random(); //reuse this if you are generating many
double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0-rand.NextDouble();
double randStdNormal = Math.S... | This question appears to have moved on top of Google for .NET Gaussian generation, so I figured I'd post an answer.
I've made some [extension methods for the .NET Random class](https://bitbucket.org/Superbest/superbest-random), including an implementation of the Box-Muller transform. Since they're extensions, so long ... | Random Gaussian Variables | [
"",
"c#",
".net",
""
] |
Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new application instance will not created).
In C#, I use `Mutex` class for this but I don't know how to do this in Java. | If I believe this [article](http://www.rbgrn.net/blog/2008/05/java-single-application-instance.html), by :
> having the first instance attempt to open a listening socket on the localhost interface. If it's able to open the socket, it is assumed that this is the first instance of the application to be launched. If not,... | I use the following method in the main method. This is the simplest, most robust, and least intrusive method I have seen so I thought that I'd share it.
```
private static boolean lockInstance(final String lockFile) {
try {
final File file = new File(lockFile);
final RandomAccessFile randomAccessFi... | How to implement a single instance Java application? | [
"",
"java",
"single-instance",
""
] |
I am using a List Control to display a representation of elements within a vector. When the list is clicked on another control shows information about that element. The index of the element is currently determined by its index in the control, however if I wish to sort or filter the results this will no longer work.
I ... | Frankly - tying data (the position in your data vector) to the presentation of the data in the list control (the position in the list ctrl) is something I would stay away from.
In MFC each control has a "Data" DWORD member variable - when coding in MFC I Always called "SetItemData" for each item added and passed in a ... | The purpose of virtual list controls is totally different: You should use it for performance reason when you have A LOT of items in your list (I'd say 2500+).
In your case, all you need is to store the vector index in the list item data as NotJarvis explains. | Virtual List Controls (MFC) | [
"",
"c++",
"windows",
"user-interface",
"mfc",
"controls",
""
] |
Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc. | First be sure you really need to support copy. Most of the time it is not the case, and thus disabling both is the way to go.
Sometimes, you'll still need to provide duplication on a class from a polymorphic hierarchy, in that case: disable the assignment operator, write a (protected?) copy constructor, and provide a ... | The compiler generated versions work in most situations.
You need to think a bit harder about the problem when your object contains a RAW pointer (an argument for not having RAW pointers). So you have a RAW pointer, the second question is do you own the pointer (is it being deleted by you)? If so then you will need to... | Checklist for writing copy constructor and assignment operator in C++ | [
"",
"c++",
"copy-constructor",
"assignment-operator",
""
] |
Is it possible, with Javascript or some other technology to determine which hyperlink a user has clicked on, without changing the hyperlink source code.
For example:
Can you click on a 'tag' button, then click on a hyperlink hosted in a different iframe, and be able to calculate which hyperlink the user clicked on, wi... | Using jQuery, you are able to set the context of your selection. i.e.
$('a', $('#iframe-id')).click(function() {...});
You can then implement an event handler that will handle the iFrame hyperlink clicks. The *"this"* property within the handler will allow you to interrogate the hyperlink and obtain properties such a... | you need to put an event on each a link ,
and then you will get all the information about the specific click.
this will work only in the some document,
so if you try to do a test between the link inside an iframe and a link in your page you will not get an event for the iframe link.
in order to attach the event for a... | How do you determine html clicked on with javascript? | [
"",
"javascript",
""
] |
We are monitoring the progress of a customized app (whose source is not under our control) which writes to a XML Manifest. At times , the application is stuck due to unable to write into the Manifest file. Although we are covering our traces by explicitly closing the file handle using File.Close and also creating the f... | If you are only reading from the file, then you should be able to pass a flag to specify the sharing mode. I don't know how you specify this in .NET, but in WinAPI you'd pass `FILE_SHARE_READ | FILE_SHARE_WRITE` to `CreateFile()`.
I suggest you check your file API documentation to see where it mentions sharing modes. | Two things:
1. You should do the rest of your operations outside the scopes of the `using` statements. This way, you won't risk using the closed stream and reader. Also, you needn't use the `Close` methods, because when you exit the scope of the `using` statement, `Dispose` is called, which is equivalent.
2. You shoul... | How to avoid File Blocking | [
"",
"c#",
".net",
"multithreading",
"file-io",
""
] |
I have a series of ASCII flat files coming in from a mainframe to be processed by a C# application. A new feed has been introduced with a Packed Decimal (COMP-3) field, which needs to be converted to a numerical value.
The files are being transferred via FTP, using ASCII transfer mode. I am concerned that the binary f... | First of all you must eliminate the end of line (EOL) translation problems that will be caused by ASCII transfer mode. You are absolutely right to be concerned about data corruption when the BCD values happen to correspond to EOL characters. The worst aspect of this problem is that it will occur rarely and unexpectedly... | I have been watching the posts on numerous boards concerning converting Comp-3 BCD data from "legacy" mainframe files to something useable in C#. First, I would like to say that I am less than enamoured by the responses that some of these posts have received - especially those that have said essentially "why are you bo... | C#: Convert COMP-3 Packed Decimal to Human-Readable Value | [
"",
"c#",
".net",
"ibm-midrange",
"flat-file",
"comp-3",
""
] |
One thing that always been a pain is to log SQL (JDBC) errors when you have a PreparedStatement instead of the query itself.
You always end up with messages like:
```
2008-10-20 09:19:48,114 ERROR LoggingQueueConsumer-52 [Logger.error:168] Error
executing SQL: [INSERT INTO private_rooms_bans (room_id, name, user_id,... | I tried [log4jdbc](http://code.google.com/p/log4jdbc/) and it did the job for me.
*SECURITY NOTE: As of today August 2011, the logged results of a log4jdbc prepared statement are NOT SAFE to execute. They can be used for analysis, but should NEVER be fed back into a DBMS.*
**Example** of log generated by logjdbc:
> ... | This is very database-dependent. For example, I understand that some JDBC drivers (e.g. sybase, maybe ms-sql) handle prepared statements by create a temporary stored procedure on the server, and then invoking that procedure with the supplied arguments. So the complete SQL is never actually passed from the client.
As a... | Logging PreparedStatements in Java | [
"",
"java",
"logging",
"jdbc",
"prepared-statement",
""
] |
I'm working on a configuration script for a JNI wrapper. One of the configuration parameters is the path to `jni.h`. What's a good quick-and-dirty Autoconf test for whether this parameter is set correctly for C++ compilation? You can assume you're running on Linux and `g++` is available.
Alternatively, is there a way ... | Checking for headers is easy; just use `AC_CHECK_HEADER`. If it's in a weird place (i.e., one the compiler doesn't know about), it's entirely reasonable to expect users to set `CPPFLAGS`.
The hard part is actually locating `libjvm`. You typically don't want to link with this; but you may want to default to a location ... | Then there is the easy way: <http://www.gnu.org/software/autoconf-archive/ax_jni_include_dir.html>
Sometimes it is best to just use the standard recipies. | Autoconf test for JNI include dir | [
"",
"java",
"java-native-interface",
"autoconf",
""
] |
Having recently discovered this method of development, I'm finding it a rather nice methodology. So, for my first project, I have a small DLL's worth of code (in C#.NET, for what it's worth), and I want to make a set of tests for this code, but I am a bit lost as to how and where to start.
I'm using NUnit, and VS 2008... | See the book [Working Effectively with Legacy Code](http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052) by Michael Feathers.
In summary, it's a lot of work to refactor existing code into testable and tested code; Sometimes it's too much work to be practical. It depends on how large the code... | I call it "Test Driven Reverse Engineering".
Start "at the bottom" -- each class can be separately examined and a test written for it. When in doubt, guess.
When you're doing ordinary TDD in the forward direction, you treat the test as sacred and assume that the code is probably broken. Sometimes the test is wrong, b... | Moving existing code to Test Driven Development | [
"",
"c#",
"tdd",
"nunit",
""
] |
I want to deserialize an object but don't know the class up front. So, consider the following code...
```
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);
```
What could I... | Just do:
```
object result = formatter.Deserialize(stream);
Type t = result.GetType();
``` | Mainly as leppie says...
If you want to test it for a few known types, you can use "is"/"as":
```
MyFoo foo = result As MyFoo;
if(foo != null) { // it was one of those
// special code
}
```
But in general, you would let the serializer worry about such details...
It is very different with xml-based serializers, of... | C# BinaryFormatter - How can I find out the class of the binary data? | [
"",
"c#",
"serialization",
"binary",
""
] |
It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the que... | ```
SELECT
@@servername AS 'Server Name' -- The database server's machine name
,@@servicename AS 'Instance Name' -- e.g.: MSSQLSERVER
,DB_NAME() AS 'Database Name'
,HOST_NAME() AS 'Host Name' -- The database client's machine name
``` | ```
SELECT DB_NAME()
```
Returns the database name. | How to query the name of the current SQL Server database instance? | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"ssms",
""
] |
If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own? | See [Creating and Throwing Exceptions](http://msdn.microsoft.com/en-us/library/ms173163.aspx).
On throwing built-in exceptions, it says:
> Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.
and
> Do Not Th... | On the subject of `System.Exception` and `System.ApplicationException`: The latter was meant to be used as the base class of all custom exceptions. However, this hasn't been enforced consistently from the beginning. Consequently, there's a controversy whether this class should be used at all rather than using `System.E... | Which built-in .NET exceptions can I throw from my application? | [
"",
"c#",
".net",
"exception",
""
] |
To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.
So, what's the correct way of doing such a thing? I've tried
```
panel = new CustomJPanelWithComponentsOnIt();
parentFr... | Your use case, seems perfect for [CardLayout](http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html).
In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time. | 1) Setting the first Panel:
```
JFrame frame=new JFrame();
frame.getContentPane().add(new JPanel());
```
2)Replacing the panel:
```
frame.getContentPane().removeAll();
frame.getContentPane().add(new JPanel());
```
Also notice that you must do this in the Event's Thread, to ensure this use the [SwingUtilities.invoke... | How do I change JPanel inside a JFrame on the fly? | [
"",
"java",
"swing",
"jpanel",
"layout-manager",
"cardlayout",
""
] |
I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts).
```
$array1 = array(1 => 'a', 2 => 'b');
$array2 = array(3 => 'c', 4 => 'd');
```
Essentially I want to combine the two arrays as if it were something like this
```
$array3 = array(1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd');
``... | Use
```
$array3 = $array1 + $array2;
```
See [Array Operators](http://de3.php.net/manual/en/language.operators.array.php)
By the way: [array\_merge()](http://de3.php.net/array_merge) does something different with the arrays given in the example:
```
$a1=array(1 => 'a', 2 => 'b');
$a2=array(3 => 'c', 4 => 'd');
prin... | You can check array\_combine function. | Combining php arrays | [
"",
"php",
"arrays",
""
] |
I have a hidden embedded QuickTime object on my page that I'm trying to control via JavaScript, but it's not working. The object looks like this:
```
<object id="myPlayer" data="" type="audio/mpeg" pluginspage="http://www.apple.com/quicktime/download" width="0" height="0">
<param name="autoPlay" value="false" />
... | Try giving the object element some width and height (1px by 1px) and make it visible within the viewport when you attempt to communicate with the plugin via JavaScript.
I've noticed that if the plugin area is not visible on screen it's unresponsive to JS commands.
This might explain why this isn't working for you in ... | I don't know the QuickTime API, but this might be worth a shot:
```
player.attributes.getNamedItem('data').value = 'http://yoururlhere';
``` | SetURL method of QuickTime object undefined? | [
"",
"javascript",
"quicktime",
""
] |
I have created an **application which needs 'hand-over'** to the support group in the next month.
The application is **fairly small** (2 months development), and consists of two client side applications and a database, it's written in c# for the windows platform.
**I have a broad idea** of what to include in a suppor... | Having been on both sides of this process professionally, I can say that the following should be ***mandatory***:
* the documentation of the code (javadoc, doxygen, etc)
* details on build process
+ where to get current source
+ how to file bugs (they will happen)
+ route to provide patches either to the source ... | 1. Functional Specification (If you have one)
2. User Manual. Create one if you don't have
3. Technical Manual, Containing
* Deployment Diagram
* Softwares Used
* Configuration and build details
* Deatils of Server ip and admin / oracle / websphere passwords
4. Testing Document
5. Over view document giving ... | What are the core elements to include in Support Documentation? | [
"",
"c#",
".net",
"documentation",
""
] |
On our live/production database I'm trying to add a trigger to a table, but have been unsuccessful. I have tried a few times, but it has taken more than 30 minutes for the create trigger statement to complete and I've cancelled it.
The table is one that gets read/written to often by a couple different processes. I hav... | The problem may not be in the table itself, but in the system tables that have to be updated in order to create the trigger. If you're doing any other kind of DDL as part of your normal processes they could be holding it up.
Use sp\_who to find out where the block is coming from then investigate from there. | I believe the CREATE Trigger will attempt to put a lock on the entire table.
If you have a lots of activity on that table it might have to wait a long time and you could be creating a deadlock.
For any schema changes you should really get everyone of the database.
That said it is tempting to put in "small" changes w... | CREATE TRIGGER is taking more than 30 minutes on SQL Server 2005 | [
"",
"sql",
"sql-server",
"triggers",
""
] |
## Question
I'm looking for a Java in-memory object caching API. Any recommendations? What solutions have you used in the past?
## Current
Right now, I'm just using a Map:
```
Map cache = new HashMap<String, Object>();
cache.put("key", value);
```
## Requirements
I need to extend the cache to include basic featur... | [EHCache](http://ehcache.sourceforge.net/) is very nice. You can create an in memory cache. Check out their [code samples](http://ehcache.sourceforge.net/documentation/samples.html) for an example of creating an in memory cache. You can specify a max size, and a time to live.
EHCache does offer some advanced features,... | I really like the [`MapMaker`](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/MapMaker.html) that comes with [Google Guava](https://github.com/google/guava) ([API](https://google.github.io/guava/releases/snapshot/api/docs/))
The JavaDoc has a pretty neat example that demonstrates b... | Lightweight Java Object cache API | [
"",
"java",
"caching",
""
] |
When using C++ namespaces, do you prefer to explicitly name them, like this:
```
std::cout << "Hello, world!\n";
```
Or do you prefer `using namespace`:
```
using namespace std;
cout << "Hello, world!\n";
```
And if if you prefer the latter, do you declare your usings at file or function scope?
Personally I prefer... | I always use `using namespace` for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.
In headers, I never use `using namespace` to avoid polluting the global namespace of the #including source. | I use always explicit ones. Writing std does not hurt me and I clearly see where is it from. It's useful when you have some legacy project to take care of with it's own "strings", "vectors" etc to maintain. The more information the code carries with it, the better. | Do you prefer explicit namespaces or 'using' in C++? | [
"",
"c++",
"namespaces",
"using",
""
] |
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.
Can we build similar feature for C/C++ (some kind of symbol table lookup)? | I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe).
You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously exp... | There is no direct means of doing this in the language. However, it is possible to do this sort of thing by using a map such as the following:
```
typedef std::map<std::string, int> variables_type;
variables_type variables;
variables["var"] = 1;
if(variables.find("jon") == variables.end())
std::cout << "variable, ... | Counterpart of PHP's isset() in C/C++ | [
"",
"c++",
"c",
"compiler-construction",
""
] |
I'm working on a project in C and it requires memalign(). Really, posix\_memalign() would do as well, but darwin/OSX lacks both of them.
What is a good solution to shoehorn-in memalign? I don't understand the licensing for posix-C code if I were to rip off memalign.c and put it in my project- I don't want any viral-ty... | Mac OS X appears to be [16-byte mem aligned.](http://www.taybin.com/2007/04/03/macos-x-memory-alignment/)
Quote from the website:
> I had a hard time finding a definitive
> statement on MacOS X memory alignment
> so I did my own tests. On 10.4/intel,
> both stack and heap memory is 16 byte
> aligned. So people portin... | ### update: OSX now has `posix_memalign()`
Late to the party, but newer versions of OSX *do* have `posix_memalign()`. You might want this when aligning to page boundaries. For example:
```
#include <stdlib.h>
char *buffer;
int pagesize;
pagesize = sysconf(_SC_PAGE_SIZE);
if (pagesize == -1) handle_error("sysconf");... | OSX lacks memalign | [
"",
"c++",
"c",
"macos",
"posix",
""
] |
I want to I check whether a string is in ASCII or not.
I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functi... | ```
def is_ascii(s):
return all(ord(c) < 128 for c in s)
``` | I think you are not asking the right question--
A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you nee... | How to check if a string in Python is in ASCII? | [
"",
"python",
"string",
"unicode",
"ascii",
""
] |
Would it suppose any difference regarding overhead to write an import loading all the types within one package (`import java.*`); than just a specific type (i.e. `import java.lang.ClassLoader`)? Would the second one be a more advisable way to use than the other one? | There is not a performance or overhead cost to doing import .\* vs importing specific types. However, I consider it to be a best practice to never use import .\* My primary reason for this is I just like to keep things straightward, clean and with as little ambiguity as possible, and I think with a .\* import you lose ... | Take a look at the java API, and you'll see many classes and interfaces with the same name in different packages.
For example:
```
java.lang.reflect.Array
java.sql.Array
```
So, if you import `java.lang.reflect.*` and `java.sql.*` you'll have a collision on the Array type, and have to fully qualify them in your code... | Import package.* vs import package.SpecificType | [
"",
"java",
"import",
"overhead",
""
] |
How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string. | The method len() returns the number of elements in the list.
Syntax:
```
len(myArray)
```
Eg:
```
myArray = [1, 2, 3]
len(myArray)
```
Output:
```
3
``` | `len` is a built-in function that calls the given container object's `__len__` member function to get the number of elements in the object.
Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used vi... | Counting array elements in Python | [
"",
"python",
"arrays",
""
] |
Any ideas how i can best drive a USB POS printer from c#.
POS printers are usually serial, TCP/IP or USB based.
I know how to accomplish serial and TCP/IP but have no idea about communications through USB in C#.
I know that there is a layer available from Microsoft called POS.NET, but I want to try and avoid using this... | You should really consider using POS for .NET and OPOS or .NET service objects (Epson, for example provides both). POS for .NET conforms to the UnifiedPOS industry standard for interfacing with these devices. | If the printer registers itself as a Human Interface Device, you can [P/INVOKE into the appropriate Win32 APIs](http://www.lvr.com/hidpage.htm "The HID Page"). Here are the signatures:
```
[ DllImport( "hid.dll", SetLastError=true ) ]
public static extern Boolean
HidD_FlushQueue( SafeFileHandle HidDeviceO... | Drive a POS printer via USB in c# | [
"",
"c#",
"usb",
"point-of-sale",
""
] |
I'd like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or explicitly by parameters, either way is good) and saves me looking up constructors every time I want to do this. All of the above is preferably in C, alt... | We just code utility methods for each of the types of exceptions we want to throw. Here are some examples:
```
jint throwNoClassDefError( JNIEnv *env, char *message )
{
jclass exClass;
char *className = "java/lang/NoClassDefFoundError";
exClass = (*env)->FindClass( env, className);
if (exClass == NULL... | I simply use 2 lines:
```
sprintf(exBuffer, "NE%4.4X: Caller can %s %s print", marker, "log", "or");
(*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/Exception"), exBuffer);
```
Produces:
```
Exception in thread "main" java.lang.Exception: NE0042: Caller can log or print.
``` | Best way to throw exceptions in JNI code? | [
"",
"java",
"exception",
"java-native-interface",
""
] |
I'd like to use the newer `<button>` tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button. The asp:Button control renders as `<input type="button">`, is there any way to make a preexisting control render to `<button>`?
From what I've read there is an inc... | This is an old question, but for those of us unlucky enough still having to maintain ASP.NET Web Forms applications, I went through this myself while trying to include Bootstrap glyphs inside of built-in button controls.
As per Bootstrap documentation, the desired markup is as follows:
```
<button class="btn btn-defa... | Although you say that using the [button runat="server"] is not a good enough solution it is important to mention it - a lot of .NET programmers are afraid of using the "native" HTML tags...
Use:
```
<button id="btnSubmit" runat="server" class="myButton"
onserverclick="btnSubmit_Click">Hello</button>
```
This us... | How can I use the button tag with ASP.NET? | [
"",
"asp.net",
"c#",
"html",
""
] |
I have few different applications among which I'd like to share a C# enum. I can't quite figure out how to share an enum declaration between a regular application and a WCF service.
Here's the situation. I have 2 lightweight C# destop apps and a WCF webservice that all need to share enum values.
Client 1 has
```
Me... | Using the Common library should be fine. Enumerations are serializable and the DataContract attributes are not needed.
See:
<http://msdn.microsoft.com/en-us/library/ms731923.aspx>
> Enumeration types. Enumerations, including flag enumerations, are
> serializable. Optionally, enumeration types can be marked with the
>... | I must have had some issues with an outdated service reference or something. I went back and created a common library containing the enum, and everything works fine. I simply added a using reference to the service interface's file.
```
using Common;
[ServiceContract]
[ServiceKnownType(typeof(MyEnum))]
public interf... | Sharing Enum with WCF Service | [
"",
"c#",
"wcf",
"enums",
""
] |
What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:
```
map.connect('/logs/', controller='logs', action='logs')
map.connect('/logs', controller='logs', action='logs')
```
I think that turning minimization on would do the trick, but... | There are two possible ways to solve this:
1. [Do it entirely in pylons](http://wiki.pylonshq.com/display/pylonscookbook/Adding+trailing+slash+to+pages+automatically).
2. [Add an htaccess rule to rewrite the trailing slash](http://enarion.net/web/apache/htaccess/trailing-slash/).
Personally I don't like the trailing ... | The following snippet added as the very last route worked for me:
```
map.redirect('/*(url)/', '/{url}',
_redirect_code='301 Moved Permanently')
``` | Trailing slashes in Pylons Routes | [
"",
"python",
"routes",
"pylons",
""
] |
I have a requirement of reading subject, sender address and message body of new message in my Outlook inbox from a C# program. But I am getting security alert 'A Program is trying to access e-mail addresses you have stored in Outlook. Do you want to allow this'.
By some googling I found few third party COM libraries t... | Sorry, I have had that annoying issue in both Outlook 2003 and Outlook 2007 add-ins, and the only solution that worked was to purchase a [Redemption](http://www.dimastr.com/redemption/) license. In Outlook 2007 that pesky popup should only show up if your firewall is down or your anti-virus software is outdated as far ... | I ran into same issue while accessing sender email address for outlook mail item. To avoid 'security alert' do not create new Application object, instead use **Globals.ThisAddIn.Application** to create new mailitem.
```
string GetSenderEmail(Outlook.MailItem item)
{
string emailAddress = "";
if (it... | How to avoid Outlook security alert when reading outlook message from C# program | [
"",
"c#",
"outlook",
""
] |
Recently, [I made a post about the developers I'm working with not using try catch blocks properly](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception), and unfortuantely using try... catch blocks in critical situations and ignoring the exception error all together. c... | Have you considered using an ORM like NHibernate? There's no point in re-inventing the wheel.
To me this is a code smell:
```
BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34);
```
Too many brackets!
I've found that using the active record pattern in a language like C# always ends in tears because it... | The jump from the first bit of code to the next is huge. Whether a complicated business object layer is necessary will depend on the size of the app in question. At the very least though our policy is that exceptions are logged where they are handled. How you present to the user is up to you but having logs is essentia... | General Business Object Practices (and exception errors - redux) | [
"",
"c#",
"error-handling",
"object",
""
] |
I've worked in shops where I've implemented Exception Handling into the event log, and into a table in the database.
Each have their merits, of which I can highlight a few based on my experience:
Event Log
* Industry standard location for exceptions (+)
* Ease of logging (+)
* Can log database connection problems he... | You need to differentiate between logging and tracing. While the lines are a bit fuzzy, I tend to think of logging as "non developer stuff". Things like unhandled exceptions, corrupt files, etc. These are definitely not normal, and should be a very infrequent problem.
Tracing is what a developer is interested in. The ... | I wouldn't log *straight* to the database. As you say, database issues become tricky to log :)
I would log to the filesystem, and then have a job which bulk-inserts from files to the database. Personally I like having the logs in the database in the log run primarily for the scaling situation - I pretty much assume I'... | (Windows) Exception Handling: to Event Log or to Database? | [
"",
"sql",
"exception",
"event-log",
""
] |
I know VS2008 has the remove and sort function for cleaning up using directives, as does Resharper. Apart from your code being "clean" and removing the problem of referencing namespaces which might not exist in the future, what are the benefits of maintaining a "clean" list of using directives?
Less code?
Faster compi... | For me it's basically all about less noise (plus making Resharper happy!).
I would believe any improvement in compilation time would be minimal. | If you always only have the using directives that you need, and always have them appropriately sorted, then when you come to diff two versions of the code, you'll never see irrelevant changes.
Furthermore, if you have a neat set of using directives then anyone looking at the code to start with can get a *rough* idea o... | What are the benefits of maintaining a "clean" list of using directives in C#? | [
"",
"c#",
"visual-studio",
"resharper",
"using",
""
] |
Can a `JApplet` use a `JFileChooser` so that the user can select a file on his hard-drive? Or would this violate Java applet security? (I'm assuming that the default security settings are being used. I don't want to ask my users to grant me extra permissions.) | [This thread](http://forums.sun.com/thread.jspa?threadID=5322793&tstart=91) indicates that you need to digitally sign your applet before a `JFileChooser` is permitted. | As mentioned, you need to sign your applet, which result in a "vague security warning" when the user is presented the applet. When the user accept to run this applet, the applet is given full access and functions like an ordinary application with it's obvious security implications. I'm in the same dilemma regarding a w... | JFileChooser use within JApplet | [
"",
"java",
"applet",
"jfilechooser",
""
] |
To make click-able divs, I do:
```
<div class="clickable" url="http://google.com">
blah blah
</div>
```
and then
```
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
});
```
I don't know if this is the best way, but it works perfectly with me, except for one issue:
If the div co... | If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).
```
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
return false;
});
```
See [event.preventDefault() vs. return f... | `$("div.clickable").click(
function(event)
{
window.location = $(this).attr("url");
event.preventDefault();
});` | jQuery DIV click, with anchors | [
"",
"javascript",
"jquery",
""
] |
I am using java language,I have a method that is supposed to return an object if it is found.
If it is not found, should I:
1. return null
2. throw an exception
3. other
Which is the best practise or idiom? | If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do other places in the code? Consistency is impo... | Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null.
Otherwise it is a matter of preference. | Should a retrieval method return 'null' or throw an exception when it can't produce the return value? | [
"",
"java",
"exception",
"error-handling",
"null",
""
] |
I am trying to connect to 2 databases on the same instance of MySQL from 1 PHP script.
At the moment the only way I've figured out is to connect to both databases with a different user for each.
I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one... | You'll need to pass a boolean true as the optional fourth argument to mysql\_connect(). See [PHP's mysql\_connect() documentation](http://php.net/mysql_connect) for more info. | If your database user has access to both databases and they are on the same server, you can use one connection and just specify the database you want to work with before the table name. Example:
```
SELECT column
FROM database.table
```
Depending on what you need to do, you might be able to do an [`INSERT INTO`](http... | How to connect to 2 databases at the same time in PHP | [
"",
"php",
"mysql",
"database",
""
] |
What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?
```
private static DateTime TrimDateToMinute(DateTime date)
{
return new D... | ```
static class Program
{
//using extension method:
static DateTime Trim(this DateTime date, long roundTicks)
{
return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind);
}
//sample usage:
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
... | You could use an enumeration
```
public enum DateTimePrecision
{
Hour, Minute, Second
}
public static DateTime TrimDate(DateTime date, DateTimePrecision precision)
{
switch (precision)
{
case DateTimePrecision.Hour:
return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
case DateTi... | Is there a better way to trim a DateTime to a specific precision? | [
"",
"c#",
".net",
"datetime",
""
] |
for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library? | You could make a subprocess call to [antiword](http://en.wikipedia.org/wiki/Antiword). Antiword is a linux commandline utility for dumping text out of a word doc. Works pretty well for simple documents (obviously it loses formatting). It's available through apt, and probably as RPM, or you could compile it yourself. | Use the **native Python docx module**. Here's how to extract all the text from a doc:
```
document = docx.Document(filename)
docText = '\n\n'.join(
paragraph.text for paragraph in document.paragraphs
)
print(docText)
```
See [Python DocX site](https://python-docx.readthedocs.org/en/latest/)
Also check out [Textr... | extracting text from MS word files in python | [
"",
"python",
"linux",
"ms-word",
""
] |
Is there an easy way to convert between color models in Java (RGB, HSV and Lab).
Assuming RGB color model:
* How do I calculate black body spectrum color palette? I want to use it for a heatmap chart.
* How about single-wavelength spectrum?
**Edit:** I found that the [ColorSpace](http://java.sun.com/javase/6/docs/ap... | You can build such a palette using the HSV color-model. That's easy once you have the HSV to RGB code in place and play around with the numbers for some minutes.
However, I think it's not worth it to add the code to your project just to generate a little palette.
It's much easier and less work to extract the palettes... | Java has built-in RGB to HSB conversion. Whenever I need a quick pallet of colors in Java I just do this:
```
public Color[] generateColors(int n)
{
Color[] cols = new Color[n];
for(int i = 0; i < n; i++)
{
cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f);
}
return cols;
}
``... | Generating spectrum color palettes | [
"",
"java",
"colors",
""
] |
I'm using C# & .NEt 3.5. What is the difference between the OptionA and OptionB ?
```
class MyClass
{
private object m_Locker = new object();
private Dicionary<string, object> m_Hash = new Dictionary<string, object>();
public void OptionA()
{
lock(m_Locker){
// Do something with the... | Option B uses the object to be protected to create a critical section. In some cases, this more clearly communicates the intent. If used consistently, it guarantees only one critical section for the protected object will be active at a time:
```
lock (m_Hash)
{
// Across all threads, I can be in one and only one o... | It's important to understand that lock(m\_Hash) does *NOT* prevent other code from using the hash. It only prevents other code from running that is also using m\_Hash as its locking object.
One reason to use option A is because classes are likely to have private variables that you will use inside the lock statement. I... | Difference between lock(locker) and lock(variable_which_I_am_using) | [
"",
"c#",
".net",
"multithreading",
""
] |
I have always wondered WHaT tHE *HecK?!?* is the difference between JScript and JavaScript. | Just different names for what is really ECMAScript. John Resig has a [good explanation](http://ejohn.org/blog/versions-of-javascript/).
Here's the full version breakdown:
* IE 6-7 support JScript 5 (which is equivalent to ECMAScript 3, JavaScript 1.5)
* IE 8 supports JScript 6 (which is equivalent to ECMAScript 3, Ja... | As far as I can tell, two things:
1. ActiveXObject constructor
2. The idiom f(x) = y, which is roughly equivalent to f[x] = y. | What's the difference between JavaScript and JScript? | [
"",
"javascript",
"jscript",
""
] |
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:
```
queryset = Modelclass.objects.filter(somekey=foo)
```
In my template I would like to do
```
{% for object in data.somekey_set.FILTER %}
```
but I just can't seem to find out how to ... | You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.
So you have several options. The easiest is to do the filtering, then pass the result to `render_to_response`... | I just add an extra template tag like this:
```
@register.filter
def in_category(things, category):
return things.filter(category=category)
```
Then I can do:
```
{% for category in categories %}
{% for thing in things|in_category:category %}
{{ thing }}
{% endfor %}
{% endfor %}
``` | How do I perform query filtering in django templates | [
"",
"python",
"django",
"django-templates",
""
] |
Because of several iframes, XUL browser elements, and so forth, I have a number of window objects in my XULRunner application. I'm looking for the best way to find the window object that a specified node belongs to using JavaScript.
So, to be more specific, given node x, I need to find the specific window object that ... | +1 to your question, it was exactly what I was looking for and thanks for the hint given directly by answering yourself.
I Googled a bit and according to <http://www.quirksmode.org/dom/w3c_html.html> cross-browsers tables I think the right answer is:
```
function GetOwnerWindow(html_node)
{
/*
ownerDocument is ... | You may want to use **self**. self is a reference to the current document.
**From within the iframe:**
```
<body>
<div id="example">Example!</div>
<script type="text/javascript">
window.onload = function () {
var exampleNode = document.getElementById('example');
exampleNode.bar = function () {
... | How can I get the window object that an HTML node belongs to using JavaScript? | [
"",
"javascript",
"xul",
"xulrunner",
""
] |
We are currently designing a website that will be accessed from kiosks in a museum. Users will need to be able to browse through a number of different web pages that will currently contain static HTML content as well as go through various interactive presentations that will be based on flash and run in flash player. Us... | You can have the same content, but you should have different CSS files. The touchscreen version will need to employ much larger fonts, and in some cases a touchscreen keyboard, whereas the home users won't need that.
Further, you may want to promote museum events on the sidebar of the home version to get people to com... | Designing for kiosks is 90% UI optimization. Have a read through this
<http://www.voltagecreative.com/blog/2008/05/best-practices-of-touch-screen-interface-design/> | Touchscreen-Oriented Website Development Recommendations for Non-Microsoft Platform | [
"",
"php",
"flash",
"touchscreen",
"kiosk",
""
] |
I'm using a small site to experiment with the uploading of pictures and displaying them.
When someone clicks "add a picture", they get taken to a page with a form on it. They can select a file and click the submit button.
But what I want to do now is this: put a second submit button labeled "Cancel" next to the norma... | You can't look at the button with php - the whole request will have been sent before PHP gets that information.
What you could do is put the cancel button in a different `<form>`, like this:
```
<form> <input type="file> <input type="submit" value="upload"> </form>
<form> <input type="submit" value="cancel"> </form>
... | Greg has the right idea there.
In stead of following the majority, or looking at how things are done, look at smart alternatives, like Greg's explanation above.
Any upload cannot function without a valid link between the client and the server; hence if you close your browser window, or re-direct it to some place else,... | Cancel a webform submit with PHP | [
"",
"php",
"html",
"web-services",
""
] |
I'd like to install Java on a Psion 5MX with GNU/Linux 16MB RAM machine, will it be possible?
Unfortunatly, ["KVM must be installed by the manufacturer"](http://www.java.com/en/download/faq/5000080100.xml).
What I want is to be able to is to write basic Java code, test and sketch simple algorithms.
Important notes: I... | Please give us more details about the machine, besides the OS and the memory. Also give us details on what you hope to accomplish with Java on such an underpowered machine (Java has some big overhead in embedded places as compared to writing native code).
The answer is maybe. I've seen Java running on a machine with 4... | There is a [List of Java virtual machines](http://en.wikipedia.org/wiki/List_of_Java_virtual_machines "List of Java virtual machines") on Wikipedia, with a number of them open source and targeting embed devices. Like [Mika](http://www.k-embedded-java.com/mika/trac/ "Mika") which seems quite small and portable. | What is the lightest Java Virtual Machine ever? (except KVM) | [
"",
"java",
"jvm",
""
] |
Is it possible for a generic interface's type to be based on a specific parent class?
For example:
```
public interface IGenericFace<T : BaseClass>
{
}
```
Obviously the above code doesn't work but if it did, what I'm trying to tell the compiler is that `T` must be a sub-class of `BaseClass`. Can that be done, are t... | ```
public interface IGenericFace<T> where T : SomeBaseClass
``` | What your are referring to is called "Generic Constraints". There are numerous constraints that can be put on a generic type.
Some basic examples are as follows:
* `where T: struct` - The type argument must be a value type. Any value type except `Nullable` - can be specified. See [Using Nullable Types (C# Programming... | Can C# generics have a specific base type? | [
"",
"c#",
"generics",
""
] |
I'm trying to make a simple C# web server that, at this stage, you can access via your browser and will just do a "Hello World".
The problem I'm having is that the server can receive data fine - I get the browser's header information - but the browser doesn't receive anything I send. Furthermore, I can only connect to... | You might like to know that you can use [`HttpListener`](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) to write a basic web-server very easily - this deals with most of the painful bits, letting you concentrate on writing the actual code. The MSDN page gives an example.
Note that this uses HTTP... | One thing which isn't a problem at the moment but might be later on is that your content length is based on the *Unicode* length of the message string, not the *binary* length.
There's also rather a lot going on in the Connection constructor - stuff that really doesn't belong in a constructor at all, IMO. It also does... | C# Web Server Connection Problem | [
"",
"c#",
"connection",
""
] |
I want to hold a bunch of const char pointers into an std::set container [1]. std::set template requires a comparator functor, and the standard C++ library offers std::less, but its implementation is based on comparing the two keys directly, which is not standard for pointers.
I know I can define my own functor and im... | Just go ahead and use the default ordering which is less<>. The Standard guarantees that less will work even for pointers to different objects:
"For templates greater, less, greater\_equal, and less\_equal, the specializations for any
pointer type yield a total order, even if the built-in operators <, >, <=, >= do not... | If you don't want to wrap them in `std::string`s, you can define a functor class:
```
struct ConstCharStarComparator
{
bool operator()(const char *s1, const char *s2) const
{
return strcmp(s1, s2) < 0;
}
};
typedef std::set<const char *, ConstCharStarComparator> stringset_t;
stringset_t myStringSet;
``` | Simplest, safest way of holding a bunch of const char* in a set? | [
"",
"c++",
"stl",
""
] |
How do I force Python's `print` function to flush the buffered output to the screen?
---
**See also:** [Disable output buffering](https://stackoverflow.com/questions/107705) if the goal is to change the buffering behaviour generally. This question is about explicitly flushing output after a specific `print` call, eve... | In Python 3, [`print`](https://docs.python.org/library/functions.html#print) can take an optional `flush` argument:
```
print("Hello, World!", flush=True)
```
In Python 2, after calling `print`, do:
```
import sys
sys.stdout.flush()
```
By default, [`print`](https://docs.python.org/2/reference/simple_stmts.html#the... | You can change the flushing behavior using the `-u` command line flag, e.g. `python -u script.py`.
> -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
> see man page for details on internal buffering relating to '-u'
Here is the [relevant documentation](http://docs.python.org/using/cmdline.html#cmdopt... | How can I flush the output of the print function? | [
"",
"python",
"printing",
"flush",
"output-buffering",
""
] |
I'm in the process of trying to move our company from SalesForce to SugarCRM, but I've run in to a nasty bug (the moment I add a custom field to Accounts, all accounts stop showing up). We've paid for support from the SugarCRM people, but they only have take-forever-then-get-a-worthless-response-level tech support for ... | Although it's not a perfect answer to my question, this article:
<http://developers.sugarcrm.com/wordpress/2008/09/26/where-is-the-code-for-x/>
did help a bit. Also when I looked further through the official Sugar docs I found that the Developer Guide does contain some explanation of how Sugar works (although obvious... | I worked with SugarCRM a couple years ago, and although I loved what I saw on the surface, I ended up rejecting it for our project because of what you are experiencing now. The internals of the product are woefully underdocumented. I had envisioned writing a bunch of slick modules for the product, but the resources jus... | How do you debug SugarCRM problems/learn how SugarCRM works? | [
"",
"php",
"sugarcrm",
""
] |
Today I had a discussion with a colleague about nested functions in Javascript:
```
function a() {
function b() {
alert('boo')
}
var c = 'Bound to local call object.'
d = 'Bound to global object.'
}
```
In this example, trials point out that b is not reachable outside the body of a, much like c is. ... | This is static scoping. Statements within a function are scoped within that function.
Javascript has a quirky behavior, however, which is that without the **var** keyword, you've implied a **global variable**. That's what you're seeing in your test. Your "d" variable is available because it is an implied global, despi... | As I understand it, these are equivalent as far as scoping is concerned:
```
function a() { ... }
```
and
```
var a = function() { ... }
``` | What is the scope of a function in Javascript/ECMAScript? | [
"",
"javascript",
"functional-programming",
"scope",
"ecma262",
""
] |
Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet :
```
Myobject *ob; // create an object
ob->addField("newField",44); // we add the field to the class and we assign an initial value to it
printf("%d",ob->newField); // now we can access that field
... | ## Use a map and a variant.
For example, using boost::variant. See <http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html>
(But of course, you can create your own, to suit the types of your XML attributes.)
```
#include <map>
#include <boost/variant.hpp>
typedef boost::variant< int, std::string > MyValue ;
typ... | There's no way to do it in the way you've described, since the compiler needs to resolve the reference at compile time - it will generate an error.
But see [The Universal Design Pattern](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html). | C++ dynamic class ( dynamic hack ) | [
"",
"c++",
"dynamic",
""
] |
What's the best way to use NaNs in C++?
I found `std::numeric_limits<double>::quiet_NaN()` and `std::numeric_limits<double>::signaling_NaN()`. I'd like to use `signaling_NaN` to represent an uninitialized variable as follows:
```
double diameter = std::numeric_limits<double>::signaling_NaN();
```
This, however, sign... | After looking into this some more, it looks like `signaling_NaN` is useless as provided. If floating point exceptions are enabled, then calling it counts as processing a signaling NaN, so it immediately raises an exception. If floating point exceptions are disabled, then processing a signaling NaN automatically demotes... | What signaling NAN means is that when the CPU encounters it a signal is fired, (hence the name). If you want to detect uninitialized variables then raising the warning level on your compiler usually detects all paths that use uninitalized values. Failing that you can use a wrapper class that stores a boolean saying if ... | Using NaN in C++? | [
"",
"c++",
"floating-point",
"nan",
""
] |
Is it safe to assume that two itterations over the same collection will return the objects in the same order? Obviously, it is assumed that the collection has not otherwise been changed. | Short answer - yes.
Obviously, though, the order of the items in the collection may not be exactly as they were inserted, depending on the type of collection (a dictionary, for example).
But you will get the same results each time you iterate over a single, unmodified collection using a foreach loop. | It depends on the collection type. For most collections, the answer is "Yes".
However, this is not guaranteed. The docs of a collection type should specify whether or not it does, but as most do, that detail is generally over looked. However, if it is not stable, it would be a tremendous oversight if the docs didn't m... | Is the order of objects returned by FOREACH stable? | [
"",
"c#",
".net",
"collections",
"foreach",
"ienumerable",
""
] |
If you throw an exception from inside an MFC dialog, the app hangs, even if you have a catch block in your code. It refuses to respond to the mouse or keyboard, and the only way to shut it down is to use Task Manager.
### Why I'm posting this question
To my shame, there is a popular shrink-wrapped application that ha... | The code for CDialog::DoModal makes the dialog modal by disabling the parent window. When the dialog code returns, the window is reenabled. There is an explicit catch for CException\* errors, but not for any other kind of thrown exception; thus the parent window never gets reenabled.
Change your code to throw a pointe... | If you are interested in learning about how Windows detects apphangs we have added some posts to this on the Windows Error Reporting blog:
[Let there be hangs part 1 of 4](http://blogs.msdn.com/wer/archive/2009/03/19/let-there-be-hangs-part-1-not-responding.aspx)
[Let there be hangs part 2 of 4](http://blogs.msdn.com... | Why does my MFC app hang when I throw an exception? | [
"",
"c++",
"windows",
"mfc",
""
] |
Finding out what's selected in real browsers is as simple as:
```
var range = {
start: textbox.selectionStart,
end: textbox.selectionEnd
}
```
But IE, as usual, doesn't understand. What's the best cross-browser way to do this? | I'll post this function for another time, seeing as this question got linked to from another one.
The following will do the job in all browsers and deals with all new line problems without seriously compromising performance. I've arrived at this after [some toing and froing](https://stackoverflow.com/questions/3622818... | IE's Range implementation is a slithy horror. It really wants you to use the execrable execCommand interface instead of anything involving indexing into the text.
There are two approaches I know of for getting the indices and they both have problems. The first uses range.text as in your example code. Unfortunately ran... | Is there an Internet Explorer approved substitute for selectionStart and selectionEnd? | [
"",
"javascript",
"internet-explorer",
"selection-api",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.