Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Why would someone use `WHERE 1=1 AND <conditions>` in a SQL clause (Either SQL obtained through concatenated strings, either view definition)
I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.
If there is injection `WHERE 1 = 1 AND injected OR 1=1` would have the sa... | If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:
```
and <condition>
```
and concatenate them all together. With the `1=1` at the start, the initial `and` has somethin... | Just adding a example code to Greg's answer:
```
dim sqlstmt as new StringBuilder
sqlstmt.add("SELECT * FROM Products")
sqlstmt.add(" WHERE 1=1")
''// From now on you don't have to worry if you must
''// append AND or WHERE because you know the WHERE is there
If ProductCategoryID <> 0 then
sqlstmt.AppendFormat(" ... | Why would someone use WHERE 1=1 AND <conditions> in a SQL clause? | [
"",
"sql",
"dynamic-sql",
""
] |
I have a loader.exe with Main() that loads the 'UI' in WPF, the thing is that I want only one instance of the loader.exe, how can I achieve it?
Is there a way a user clicks loader.exe it should check if an existing loader.exe is running and does nothing.
currently I have
loader.exe
with
```
main()
....
..
Load UI... | We use the following C# code to detect if an application is already running:
```
using System.Threading;
string appSpecificGuid = "{007400FE-003D-00A5-AFFE-DA62E35CC1F5}";
bool exclusive;
Mutex m = new Mutex(true, appSpecificGuid, out exclusive);
if (exclusive) {
// run
} else {
// already running
}
```
... | Have a look at:
<http://yogesh.jagotagroup.com/blog/post/2008/07/03/Ways-of-making-a-WPF-application-Single-Instance.aspx>
Also, you might find a more detailed answer in the following post here on StackOverflow:
[What is the correct way to create a single-instance application?](https://stackoverflow.com/questions/19... | c# WPF Maintain Single Instance of loader | [
"",
"c#",
"wpf",
"single-instance",
""
] |
If you read other people's source code, how do you approach the code? What patterns are you looking for (datatypes, loops, use of control flow, ...)? How long can you read other people's code without getting bored? What is the most exciting patterns that you have discovered so far? | Aside from the obvious "work from the top down" general approach, it depends on **why** I'm reading it: code review, trying to understand a bit of avaialable code to adapt for my own use, trying to learn a new technique, etc.
It also depends heavily on the language. If it is an OOPL, I'll probably do something like th... | At first, I ignore the urge to change the code. Which is sometimes hard to do. But understanding first and change later saves yourself a lot of nasty "learning experiences."
Next if the format is bad, reformat. Use a code formatter if you have one. This is because you tend to look at the indentation and if that is bad... | What should I take note of when reading others' source code? | [
"",
"java",
"design-patterns",
""
] |
I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this?
Edit: The scope of the problem is as follows: I'm trying to hack a program fo... | The built in function id() returns a unique id for any object, which just happens to be it's memory address.
<http://docs.python.org/library/functions.html#id> | For accessing and setting environment variables, read up on the os.environ dictionary. You can also use os.putenv to set an environment variable. | Python - Setting / Getting Environment Variables and Addrs | [
"",
"python",
"linux",
"environment-variables",
""
] |
After creating a instance of a class, can we invoke the constructor explicitly?
For example
```
class A{
A(int a)
{
}
}
A instance;
instance.A(2);
```
Can we do this? | You can use [placement new](http://en.wikipedia.org/wiki/Placement_new), which permits
```
new (&instance) A(2);
```
However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do
```
A instance(2);
```
Placement new is usually only used wh... | No.
Create a method for the set and call it from the constructor. This method will then also be available for later.
```
class A{
A(int a) { Set(a); }
void Set(int a) { }
}
A instance;
instance.Set(2);
```
You'll also probably want a default value or default constructor. | Can you invoke an instantiated object's class constructor explicity in C++? | [
"",
"c++",
"constructor",
""
] |
I need to get execution time in milliseconds.
**Note**: I originally asked this question back in 2008. The accepted answer then was to use [`new Date().getTime()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) However, we can all agree now that using the standard [`perf... | ## Using [**performance.now()**](https://developer.mozilla.org/en-US/docs/Web/API/Performance.now):
```
var startTime = performance.now()
doSomething() // <---- measured code goes between startTime and endTime
var endTime = performance.now()
console.log(`Call to doSomething took ${endTime - startTime} millise... | use [new Date().getTime()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime)
> The getTime() method returns the number of milliseconds since midnight of January 1, 1970.
ex.
```
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// do something
}
var end = ... | How to measure time taken by a function to execute | [
"",
"javascript",
"profiling",
""
] |
I'm experimenting with WCF Services, and have come across a problem with passing Interfaces.
This works:
```
[ServiceContract]
public interface IHomeService
{
[OperationContract]
string GetString();
}
```
but this doesn't:
```
[ServiceContract]
public interface IHomeService
{
[OperationContract]
IDe... | You need to tell the WCF serializer which class to use to serialize the interface
```
[ServiceKnownType(typeof(ConcreteDeviceType)]
``` | Thanks, it works when I changed it like this:
```
[ServiceContract]
[ServiceKnownType(typeof(PhotoCamera))]
[ServiceKnownType(typeof(TemperatureSensor))]
[ServiceKnownType(typeof(DeviceBase))]
public interface IHomeService
{
[OperationContract]
IDevice GetInterface();
}
```
I also got help from this site: <ht... | Passing Interface in a WCF Service? | [
"",
"c#",
".net",
"wcf",
""
] |
I'm trying to work my way through Ron Jeffries's Extreme Programming Adventures in C#. I am stuck, however, in Chapter 3 because the code does not, and **cannot**, do what the author says it does.
Basically, the text says that I should be able to write some text in a word-wrap enabled text box. If I then move the curs... | Try emailing Ron Jeffries directly. I have the book - somewhere, but I don't remember it not working. His email address is ronjeffries at acm dot org and put [Ron] in the subject line.
(And for those wondering - his email info was right from his website [Welcome page](http://www.xprogramming.com/welcome.htm)) | I've also just started this book and had exactly the same problem although the code you have included looks further along than where I am.
The 'subscript out of range' occurred for 2 reasons, first as Ron explains he was just testing and so returned a hard-coded value of 3 before he wrote the CursorLine() function, whi... | Errata in Extreme Programming Adventures in C#? | [
"",
"c#",
"textbox",
"extreme-programming",
""
] |
```
class Score
{
var $score;
var $name;
var $dept;
var $date;
function Score($score, $name, $dept, $date)
{
$this->scores = ($score);
$this->name = ($name);
$this->dept = ($dept);
$this->date = ($date);
}
function return_score(){
return $this->s... | You can't return more than once in a function. You *could* return a concatenated string:
```
return $this->scores.' '.this->name.' '.$this->dept.' '.$this->date;
//added spaces for readability, but this is a silly thing to do anyway...
```
I wouldn't recommend it though as you'd be mixing you presentation of the obje... | You can only return one value in each function or method.
In your situation, you should have a method for each of the class members:
```
public function getScore() {
return $this->score;
}
public function getName() {
return $this->name;
}
public function getDept() {
return $this->dept;
}
public function ... | Only getting one element returned, OO PHP | [
"",
"php",
"oop",
""
] |
At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type.
```
Queue<MyData> myDataQueue = new Queue<MyData>();
// Populate the queue here
XmlSerializer mySerializer =
new XmlSerializer(myDataQueue.G... | It would be easier (and more appropriate IMO) to serialize the *data* from the queue - perhaps in a flat array or `List<T>`. Since `Queue<T>` implements `IEnumerable<T>`, you should be able to use:
```
List<T> list = new List<T>(queue);
``` | Not all parts of the framework are designed for XML serialization. You'll find that dictionaries also are lacking in the serialization department.
A queue is pretty trivial to implement. You can easily create your own that also implements IList so that it will be serializable. | In C#, How can I serialize Queue<>? (.Net 2.0) | [
"",
"c#",
".net",
"generics",
"serialization",
".net-2.0",
""
] |
Does this pattern:
```
setTimeout(function(){
// do stuff
}, 0);
```
Actually return control to the UI from within a loop? When are you supposed to use it? Does it work equally well in all browsers? | It runs code asynchronously (not in parallel though). The delay is usually changed to a minimum of 10ms, but that doesn't matter.
The main use for this trick is to avoid limit of call stack depth. If you risk reaching limit (walk deep tree structure and plan to do a lot of work on leafs), you can use timeout to start ... | <http://blog.thinkature.com/index.php/2006/11/26/escaping-the-javascript-call-stack-with-settimeout/>
Some good info in there. Basically, you are correct and it works on pretty much all browsers. Cool trick.
You would want to use this in the example that the author of the post gave, as well as instances where you nee... | What is setTimeout(function(){//dostuff}, 0); actually supposed to do? | [
"",
"javascript",
"performance",
""
] |
I have a sql query that runs super fast, around one second, when not using variables, like:
```
WHERE id BETWEEN 5461094 and 5461097
```
But when I have:
```
declare @firstId int
declare @lastId int
set @firstId = 5461094
set @lastId = 5461097
...
WHERE id BETWEEN @firstId and @lastId
```
... the query runs r... | It's because when the values are hard coded, it can look up [the statistics](http://www.microsoft.com/technet/prodtechnol/sql/2005/qrystats.mspx) it has on the data in the table, and figure out the best query to run. Have a look at the execution plans of each of these queries. It must be scanning when your using variab... | OK,
1. You are the Optimizer and the Query Plan is a vehicle.
2. I will give you a query and you have to choose the vehicle.
3. All the books in the library have a sequential number
My query is Go to the library and get me all the books between 3 and 5
You'd pick a bike right, quick, cheap, efficient and big enough ... | Why SQL Server go slow when using variables? | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a `JProgressBar` widget, which I would like to show the current progress of the download. For that I would need t... | Any HTTP response is *supposed* to contain a Content-Length header, so you could query the URLConnection object for this value.
```
//once the connection has been opened
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {
// getHeaderFields() returns a Ma... | As mentioned, URLConnection's [`getContentLengthLong()`](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getContentLengthLong--) is your best bet, but it won't always give a definite length. That's because the HTTP protocol (and others that could be represented by a `URLConnection`) doesn't always... | Java URLConnection : how can I find out the size of a web file? | [
"",
"java",
"http",
"http-headers",
""
] |
I need to build a function which parses the domain from a URL.
So, with
```
http://google.com/dhasjkdas/sadsdds/sdda/sdads.html
```
or
```
http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html
```
it should return `google.com`
with
```
http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html
```
it should return... | Check out [`parse_url()`](http://php.net/parse_url):
```
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'
```
`parse_url` doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls. | ```
$domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));
```
**This would return the `google.com` for both <http://google.com/>... and <http://www.google.com/>...** | Parsing domain from a URL | [
"",
"php",
""
] |
I am battling regular expressions now as I type.
I would like to determine a pattern for the following example file: `b410cv11_test.ext`. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at... | Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;)
> must start with
The caret (`^`) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol.
> 'b',... | To avoid confusion, read the following, in order.
First, you have the [glob](http://www.python.org/doc/2.5.2/lib/module-glob.html) module, which handles file name regular expressions just like the Windows and unix shells.
Second, you have the [fnmatch](http://www.python.org/doc/2.5.2/lib/module-fnmatch.html) module, ... | How can I translate the following filename to a regular expression in Python? | [
"",
"python",
"regex",
""
] |
I want to convert a `std::string` to lowercase. I am aware of the function `tolower()`. However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a `std::string` would require iterating over each character.
Is there an alternative which works 100% of the time? | Adapted from [*Not So Frequently Asked Questions*](http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/):
```
#include <algorithm>
#include <cctype>
#include <string>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c... | [Boost provides a string algorithm for this](https://www.boost.org/doc/libs/1_70_0/doc/html/boost/algorithm/to_lower.html):
```
#include <boost/algorithm/string.hpp>
std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str
```
[Or, for non-in-place](https://www.boost.org/doc/libs/1_70_0/do... | How to convert an instance of std::string to lower case | [
"",
"c++",
"string",
"std",
"tolower",
""
] |
The default generated hashCode and equals implementations are ugly at best.
Is it possible to make eclipse generate ones from HashCodeBuilder and EqualsBuilder, and perhaps even a toString with ToStringBuilder? | Take a look at [Commons4E](http://marketplace.eclipse.org/content/commons4e)
It hasn't been updated in a while, but then I don't guess it needs to change much?
Update: Just checked against 3.4.1 and it works fine. | You can configure Eclipse to generate `toString()` using a custom builder. In our case `ToStringBuilder` from [Apache Commons Lang](http://commons.apache.org/lang/). You can see here <http://azagorneanu.blogspot.com/2011/08/how-to-generate-equals-hashcode.html> how to do it.
That blog post contains also Eclipse templa... | Is it possible to make eclipse generate hashCode and equals with HashCodeBuilder and EqualsBuilder | [
"",
"java",
"eclipse",
""
] |
This is a contrived example, but lets say I have declared objects:
```
CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;
```
And I have an string array:
```
string[] stringarray = new string[] {"foo","bar","baz"};
```
How can I programmatically access and instantiate those objects using the string array, iterat... | You need to be clear in your mind about the difference between an object and a variable. Objects themselves don't have names. Variable names are decided at compile-time. You can't access variables via an execution-time-determined name except via reflection.
It sounds like you *really* just want a `Dictionary<string, C... | You can't.
You can place them into a dictionary:
```
Dictionary<String, CustomObj> objs = new Dictionary<String, CustomObj>();
foreach (string i in stringarray)
{
objs[i] = new CustomObj(i);
}
```
But that's about as good as it gets.
If you store the objects in fields in your class, like this:
```
public clas... | Programmatically using a string as object name when instantiating an object | [
"",
"c#",
"oop",
""
] |
I am using CYGWIN as a platform and would like to use wxPython. Is there a way to get the source compiled and working in cygwin? | I found this link to [build wxPython under Cygwin](http://gnuradio.org/redmine/projects/gnuradio/wiki/WxPythonCygwin). To me this is a much better option than installing all the X11 stuff. I tried it out using wxPython-src-2.8.12.1, and following the instructions to a tee, it worked perfectly. | You would need a full working X environment to get it to work. It would be much easier to just use Python and wxPython under plain vanilla Windows. Do you have a special case? | How do you compile wxPython under cygwin? | [
"",
"python",
"installation",
"wxpython",
"cygwin",
"compilation",
""
] |
So I have xml that looks like this:
```
<todo-list>
<id type="integer">#{id}</id>
<name>#{name}</name>
<description>#{description}</description>
<project-id type="integer">#{project_id}</project-id>
<milestone-id type="integer">#{milestone_id}</milestone-id>
<position type="integer">#{position}</position>
... | Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments... | Boils down to using xsd.exe from tools in VS:
```
xsd.exe "%xsdFile%" /c /out:"%outDirectory%" /l:"%language%"
```
Then load it with reader and deserializer:
```
public GeneratedClassFromXSD GetObjectFromXML()
{
var settings = new XmlReaderSettings();
var obj = new GeneratedClassFromXSD();
var reader = X... | Deserializing XML to Objects in C# | [
"",
"c#",
".net",
"serialization",
""
] |
I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the `<head>`
note: I am working with a local server, so pageload in instant.
```
function changeVisibility() {
var a = do... | This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)
> note: I am working with a local server, so pageload in instant.
that's not the issue - the constituent parts of a d... | mercutio is correct. If that code is executing in the HEAD, the call to "document.getElementById('click1')" will always return null since the body hasn't been parsed yet. Perhaps you should put that logic inside of an onload event handler. | Javascript: var is null | [
"",
"javascript",
"html",
"null",
""
] |
I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong?
Function:
```
std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...
return it;
...
}
```... | Your search function is returning a const\_iterator. You should either return the same type, i.e. `std::vector< CClass >::const_iterator`, or cast it to a `std::vector< CClass >::iterator` if you intend the caller to be able to modify the found item through the iterator.
EDIT: after seeing your update, it seems the pr... | Sounds like you have your const\_iterators mixed up. Please post more code, specifically how you are declaring your iterator. | Returning an Iterator | [
"",
"c++",
"stl",
"iterator",
""
] |
What is the *best* way to print the cells of a `String[][]` array as a right-justified table? For example, the input
```
{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } }
```
should yield the output
```
x xxx
yyy y
zz zz
```
This seems like something that one *should* be able to accomplish using `java.util.F... | Indeed, if you specify a width for the fields, it should be right-justified.
If you need to have a dynamic padding, minimal for the longest string, you have to walk the array, getting the maximal width, generate the format string with the width computed from this maxima, and use it for format the output. | Here's an answer, using dynamically-generated format strings for each column:
```
public static void printTable(String[][] table) {
// Find out what the maximum number of columns is in any row
int maxColumns = 0;
for (int i = 0; i < table.length; i++) {
maxColumns = Math.max(table[i].length, maxColumns);
}... | Java: Print a 2D String array as a right-justified table | [
"",
"java",
"formatting",
"printf",
""
] |
Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?
Let's say we have an array of associative arrays:
```
var myArray = [{'key': 'value'}, {'key': 'value1'}];
```
So we can iterate:
```
for (var i = 0; i < myArray.length; i++)
```
And:
```
for (var i ... | The choice should be based on the which idiom is best understood.
An array is iterated using:
```
for (var i = 0; i < a.length; i++)
//do stuff with a[i]
```
An object being used as an associative array is iterated using:
```
for (var key in o)
//do stuff with o[key]
```
Unless you have earth shattering reaso... | Douglas Crockford recommends in [JavaScript: The Good Parts](http://oreilly.com/catalog/9780596517748/) (page 24) to avoid using the `for in` statement.
If you use `for in` to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from... | JavaScript for...in vs for | [
"",
"javascript",
""
] |
We are developing a new web service and are looking into the "best practice" for returning errors in the soap response.
We were looking into creating a error response object which every response would contain as a property. This seems a little heavy however and are wondering if it is possible to use the SOAP header to... | SOAPFault is used to hold error and status information, and server returns 500 in the HTTP header for it to state it as fault.
see the specification from W3.org
<http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383507>
You can design your own information token by either placing it into soap header or even within... | Soap already uses custom headers for error info, all you need to do is throw an exception on the server side, and exception is raised on the client side as a [SoapException](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapexception.aspx).
You can thrown SoapExceptions on the serverside if you... | Error handling using Soap Headers | [
"",
"c#",
".net",
"web-services",
"soap",
"error-handling",
""
] |
How can I return the result of a different action or move the user to a different action if there is an error in my `ModelState` without losing my `ModelState` information?
The scenario is; `Delete` action accepts a POST from a DELETE form rendered by my `Index` Action/View. If there is an error in the `Delete` I want... | Store your view data in `TempData` and retrieve it from there in your `Index` action, if it exists.
```
...
if (!ModelState.IsValid)
TempData["ViewData"] = ViewData;
RedirectToAction( "Index" );
}
public ActionResult Index()
{
if (TempData["ViewData"] != null)
{
ViewData = (ViewD... | Use Action Filters (PRG pattern) (as easy as using attributes)
Mentioned [here](https://stackoverflow.com/questions/658747/how-do-i-maintain-modelstate-errors-when-using-redirecttoaction) and [here](https://web.archive.org/web/20130702160308/http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-p... | How can I maintain ModelState with RedirectToAction? | [
"",
"c#",
"asp.net-mvc",
""
] |
How can I transform a time value into YYYY-MM-DD format in Java?
```
long lastmodified = file.lastModified();
String lasmod = /*TODO: Transform it to this format YYYY-MM-DD*/
``` | Something like:
```
Date lm = new Date(lastmodified);
String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(lm);
```
See the javadoc for [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html). | ```
final Date modDate = new Date(lastmodified);
final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
final String lasmod = f.format(modDate);
```
[SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html) | How to transform a time value into YYYY-MM-DD format in Java? | [
"",
"java",
"time",
""
] |
I'm calling a web service that returns an array of objects in JSON. I want to take those objects and populate a div with HTML. Let's say each object contains a url and a name.
If I wanted to generate the following HTML for each object:
```
<div><img src="the url" />the name</div>
```
Is there a best practice for thi... | Options #1 and #2 are going to be your most immediate straight forward options, however, for both options, you're going to feel the performance and maintenance impact by either building strings or creating DOM objects.
Templating isn't all that immature, and you're seeing it popup in most of the major Javascript frame... | If you absolutely have to concatenate strings, instead of the normal :
```
var s="";
for (var i=0; i < 200; ++i) {s += "testing"; }
```
use a temporary array:
```
var s=[];
for (var i=0; i < 200; ++i) { s.push("testing"); }
s = s.join("");
```
Using arrays is much faster, especially in IE. I did some testing with s... | Is there a best practice for generating html with javascript | [
"",
"javascript",
"html",
"ajax",
"dynamic",
"dhtml",
""
] |
I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492').
In other words, I need to add correct amount of leading zeros to the number.
```
int n = 999;
... | or using the stringstreams:
```
#include <sstream>
#include <iomanip>
std::stringstream ss;
ss << std::setw(10) << std::setfill('0') << i;
std::string s = ss.str();
```
I compiled the information I found on [arachnoid.com](http://www.arachnoid.com/cpptutor/student3.html) because I like the type-safe way of iostreams... | ```
char str[7];
snprintf (str, 7, "%06d", n);
```
See [snprintf](http://libslack.org/manpages/snprintf.3.html) | Convert a number to a string with specified length in C++ | [
"",
"c++",
"integer",
"stdstring",
""
] |
Yes, I know you could use regular objects as associative arrays in JavaScript, but I'd like to use something closer to java's Map's implementation (HashMap, LinkedHashMap etc). Something that could have any kind of data used as key. Are there any good hash(code/table) in JavaScript implementation out there? | In javascript, **objects are literally a hash implementation**. A Java HashMap will be a little bit of a fake-out, so I'd **challenge you** to re-think your needs.
The **straight answer is no**, I don't believe that there is a great implementation of Java's HashMap in javascript. If there is, it's bound to be part of ... | I have released a standalone JavaScript hash table implementation that goes further than those listed here.
<http://www.timdown.co.uk/jshashtable/> | Is there any good JavaScript hash(code/table) implementation out there? | [
"",
"javascript",
"hash",
""
] |
Is there a way to get all methods (private, privileged, or public) of a javascript object from within? Here's the sample object:
```
var Test = function() {
// private methods
function testOne() {}
function testTwo() {}
function testThree() {}
// public methods
function getMethods() {
for (i in t... | The technical reason why those methods are hidden is twofold.
First, when you execute a method on the Test object, "this" will be the untyped object returned at the end of the anonymous function that contains the public methods per the [Module Pattern](http://yuiblog.com/blog/2007/06/12/module-pattern/).
Second, the ... | From <http://netjs.codeplex.com/SourceControl/changeset/view/91169#1773642>
```
//Reflection
~function (extern) {
var Reflection = this.Reflection = (function () { return Reflection; });
Reflection.prototype = Reflection;
Reflection.constructor = Reflection;
Reflection.getArguments = function (func) {
var sym... | Javascript Reflection | [
"",
"javascript",
"reflection",
"closures",
""
] |
We are developing an application that involves a lot of different tests where each test lead the users to a number of steps. We are thinking of using a state machine framework to capture the states/transitions out of the code. We are also thinking of using rule engine to supplement on the rules. Anyone has experience w... | [jbpm](http://jboss.org/jbpm) does this and integrates well with jboss. In my experience, it's pretty easy to use and is powerful. | You might want to look at [StatefulJ](http://www.statefulj.org). It is built off of Spring Data for Persistence support and the State Model itself is defined using Annotations. This approach makes it easier to set up and maintain vs. XML. Regarding rules - I've used Drools in the past and seems very well supported.
Di... | State Machine Framework for JBoss/Java? | [
"",
"java",
"frameworks",
"fsm",
""
] |
Is there any difference between a `volatile` Object reference and `AtomicReference` in case I would just use `get()` and `set()`-methods from `AtomicReference`? | Short answer is: No.
From the [`java.util.concurrent.atomic`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/atomic/package-summary.html) package documentation. To quote:
> The memory effects for accesses and updates of atomics generally follow the rules for volatiles:
>
> * `get` h... | No, there is not.
The additional power provided by AtomicReference is the compareAndSet() method and friends. If you do not need those methods, a volatile reference provides the same semantics as AtomicReference.set() and .get(). | Java volatile reference vs. AtomicReference | [
"",
"java",
"concurrency",
""
] |
What would be the easiest way to move the mouse around (and possibly click) using Python on OS X?
This is just for rapid prototyping, it doesn't have to be elegant. | I dug through the source code of Synergy to find the call that generates mouse events:
```
#include <ApplicationServices/ApplicationServices.h>
int to(int x, int y)
{
CGPoint newloc;
CGEventRef eventRef;
newloc.x = x;
newloc.y = y;
eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newl... | Try the code at [this page](http://web.archive.org/web/20111229234504/http://www.geekorgy.com:80/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/). It defines a couple of functions, `mousemove` and `mouseclick`, which hook into Apple's integration between Python and the platform... | How to control the mouse in Mac using Python? | [
"",
"python",
"macos",
"mouse",
""
] |
Is it possible to share a single 'god' instance among everyone that links to this code, to be placed in a shared object?
```
god* _god = NULL;
extern "C"
{
int set_log_level(int level)
{
if(_god == NULL) return -1;
_stb->log_level(level);
return 0;
}
int god_init(){
if(_god == NULL){
_god = ... | [Boost Interprocess](http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html) library has high(er) level, portable shared memory objects. | This isn't the correct approach at all. By doing what you suggest, the variable, yes, is global to the library, and thus the program, but the data is private to the actual running process. You won't be able to share the values across running programs. @grieve is referring to a global accessed by multiple threads, but t... | Creating an object in shared memory inside a Shared Lib (so) in C++ | [
"",
"c++",
"memory",
"shared-libraries",
""
] |
How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?
```
$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);
$C = array_intersect($A,$B); //equals (1,2,3,4)
$A = array_diff($A,$B); //equals (5,6,7,8)
```
Is this the simplest... | You've got it. Just use `array_diff` or `array_intersect`. Doesn't get much easier than that.
**Edit:**
For example:
```
$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);
```
[Source](https://stackoverflow.com/a/8691348/2210140) | Dear easy and clean way
```
$clean1 = array_diff($array1, $array2);
$clean2 = array_diff($array2, $array1);
$final_output = array_merge($clean1, $clean2);
``` | How to compare two arrays and remove matching elements from one for the next loop? | [
"",
"php",
"arrays",
""
] |
I'm developing a Java application using Eclipse. My project has two source directories that are both built and then some files are copied into the output folder. From the output directory I then run my application and all works well.
However, I keep having these warnings:
[Snapshot from Problems tab in Eclipse http:/... | Have you tried to add
`**/.svn/`
to the *Exclusion patterns* at the *Source* preferences of the project's build path settings? | You could also try installing the Subversion plugin ([Subclipse](http://subclipse.tigris.org/)) for Eclipse. | In Eclipse, how can I exclude some files (maybe based on the .svn extension or filename) from being copied to the output folder? | [
"",
"java",
"eclipse",
"svn",
"build-process",
""
] |
I'm working with LINQ to objects and have a function where in some cases I need to modify the underlying collection before calling `Aggregate(...)` and then return it to its original state before the funciton returns the results of `Aggregate(...)`. My current code looks something like this:
```
bool collectionModifie... | Just to check I understand you - you basically want to iterate through all of the results, just to force any side effects to take place?
Side effects are generally a bad idea precisely because things are harder to understand with this kind of logic. Having said that, the easiest way to do it and force full evaluation ... | (Note: typing without a compiler at hand, so the code is untested)
If you have Reactive Extensions for .NET as a dependency already you can use Run():
```
aggregationResult.Run();
```
But it might not be worth adding a dependency for this.
You can also implement the Run method yourself as an extension method:
```
... | Something better than .ToArray() to force enumeration of LINQ output | [
"",
"c#",
"linq",
".net-3.5",
""
] |
How can I make this java generic cast ?
```
public interface IField {
}
class Field implements IField { // package private class
}
public class Form {
private List<Field> fields;
public List<IField> getFields() {
return this.fields;
}
}
```
The return statement throws a compiler error (I know the r... | A better solution, IMO, is to change the signature of your method to use a bounded wildcard:
```
public List<? extends IField> getFields()
```
This will let the caller treat anything coming "out" of the list as an IField, but it won't let the caller add anything into the list (without casting or warnings), as they do... | As it happens, you can, because Java generics are just grafted on, not part of the type system.
You can do
```
return (List<IField>)(Object)this.fields;
```
because all `List<T>` objects are the same underlying type.
Bear in mind that this allows anyone to put any type implementing `IField` in your list, so if your... | How can I make this java generic cast? | [
"",
"java",
""
] |
[Javascript Developer Tools](http://wiki.eclipse.org/index.php/ATF/JSDT) (JSDT) for Eclipse provides a nice outline view of Javascript classes, with a little symbol next to them to indicate visibility.
Looking at *Preferences->Javascript->Appearance->Members Sort Order*, it seems able to indicate whether a method is p... | Seems that it is just a standard Java-based settings tree (used in many plugins) but without real implementation of JS [private members](http://javascript.crockford.com/private.html) stuff. Oh, we can hope that it is reserved for future use :) | There's no syntactical way of making a method *private, public* or *protected* in JavaScript, it strictly relies on where the method is defined (scope).
*Marking* a methods privacy is something else, there really isn't a standard for that. All I've ever heard of is the "underscore" for private members. So maybe JSDT d... | How to indicate public/protected/private members in JSDT outline view? | [
"",
"javascript",
"eclipse",
"ide",
"jsdt",
""
] |
I am using Infragistics UltraGrid in a Windows Forms application.
I need an event which is raised on cell value change.
I've tried many events like `AfterCellActivate`, `AfterCellUpdate` but was unable to find the right one. | AfterCellUpdate is what you want, but you may need to call:
* YourGridControl.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.EnterEditMode)
* YourGridControl.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode)
to actually trigger the update, depending on when you want it triggered.
... | There is a CellChange event which fires when the user begins to type a value in the cell. This event is useful if you need to know exactly when a cell is modified as the AfterCellUpdate event only fires when the user exits from the cell s/he is changing. | Which event raise on cell value change in Infragistics UltraGrid? | [
"",
"c#",
"vb.net",
"winforms",
"infragistics",
"ultrawingrid",
""
] |
I'm an end-user of one of my company's products. It is not very suitable for integration into Spring, however I am able to get a handle on the context and retrieve the required bean by name. However, I would still like to know if it was possible to inject a bean into this class, even though the class is not managed by ... | You can do this:
```
ApplicationContext ctx = ...
YourClass someBeanNotCreatedBySpring = ...
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
someBeanNotCreatedBySpring,
AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
```
You can use `@Autowired` and so on within `YourClass` to specify field... | suppose that u have the following dependency chain:
A --> B --> C --> x --> y -- > Z
A, B, C are spring managed beans (constructed and manged by spring framework)
x, y are really simple POJOs that constructed by your application, without spring assistance
now if you want that y will get a reference to Z using spring... | Injecting beans into a class outside the Spring managed context | [
"",
"java",
"spring",
""
] |
Consider the following use of template template parameters...
```
#include <iostream>
template <typename X>
class A
{
X _t;
public:
A(X t)
:_t(t)
{
}
X GetValue()
{
return _t;
}
};
template <typename T, template <typename T> class C >
class B
{
C<T> _c;
public:
B(T... | I assume you're after X, as well as A, in your code.
The usual pattern is to have
```
template<typename C>
struct B
{
C c;
};
```
and then, inside classes eligible for substitution:
```
template<typename X>
class A
{
typedef X type_name;
X t;
};
```
Then you can access the template parameter using `C::typ... | This is not possible. Note that this is a common misunderstanding: `A<int>` is not a class template anymore! So it would not fit to a template-template parameter, but would have to be accepted using a type-parameter:
```
template<typename C>
struct B {
C c;
};
B< A<int> > b;
```
Your way of using a separate para... | How to declare/define a class with template template parameters without using an extra template parameter | [
"",
"c++",
"templates",
"metaprogramming",
""
] |
What's wrong with the following snippet ?
```
#include <tr1/functional>
#include <functional>
#include <iostream>
using namespace std::tr1::placeholders;
struct abc
{
typedef void result_type;
void hello(int)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void hello(int) const
{ std::cout <... | The lookup is done at a time when the constness of `this` is not known. You just have to give it a hint via casting. Try this:
```
typedef void (abc::*fptr)(int) const; // or remove const
std::tr1::bind((fptr)&abc::hello, x , _1)(a);
```
You may also notice here that removing the `const` still works. This is because ... | As John suggested, the problems arisen in those snippets are the following:
1. When passing a *member-function-pointer* it's necessary to specify its signature (if overloaded)
2. `bind()` are passed arguments by value.
The first problem is solved by casting the member function pointer provided to bind:
```
std::... | tr1::mem_fn and tr1::bind: on const-correctness and overloading | [
"",
"c++",
"c++11",
"functional-programming",
"tr1",
""
] |
Does anybody have experience using the open source offering from Terracotta as opposed to their enterprise offering? Specifically, I'm interested if it is worth the effort to use terracotta without the enterprise tools to manage your cluster?
Over-simplified usage summary: we're a small startup with limited budget tha... | At the moment, the Terracotta enterprise tools provide only a few features beyond the open source version around things like visualization and management (like the ability to kick a client out of the cluster). That will continue to diverge and the enterprise tools are likely to boast more operator-level functionality a... | I am in a process of integrating Terracotta with my project (a sensor node network simulator). About three weeks ago I found out about Terracotta from one of my colleagues. And now my application takes advantage of grid computing using Terracotta. Below I summarized some essential points of my experience with Terracott... | Any experience using Terracotta open source? | [
"",
"java",
"load-balancing",
"terracotta",
""
] |
I have a set of core, complicated JavaScript data structures/classes that I'd like to be able to use both in the browser as JavaScript and run on the desktop with .NET 3.5. Is it possible to compile web-friendly JavaScript into assemblies that my C# code can access?
* Managed JScript - Is there a compiler for this ava... | JScript.Net is actually mostly EMCAScript3 compliant. As long as you treat your code as a processing library (only have it do crunching, etc - use callbacks to interact with the program), you should be fine.
I'm doing something similar, using javascript as my core parsing library, and then using it within python, dotne... | Managed JavaScript (IronJScript) appears to have been killed. See [this answer](https://stackoverflow.com/questions/775339/where-can-you-download-managed-jscript-for-the-dlr/886173#886173): | Sharing JavaScript code between .NET desktop and browser | [
"",
".net",
"javascript",
"script#",
"jscript.net",
"managed-jscript",
""
] |
Is there an easy way within C# to check to see if a DateTime instance has been assigned a value or not? | The only way of having a variable which hasn't been assigned a value in C# is for it to be a local variable - in which case at compile-time you can tell that it isn't definitely assigned by trying to read from it :)
I suspect you really want `Nullable<DateTime>` (or `DateTime?` with the C# syntactic sugar) - make it `... | do you mean like so:
```
DateTime datetime = new DateTime();
if (datetime == DateTime.MinValue)
{
//unassigned
}
```
or you could use Nullable
```
DateTime? datetime = null;
if (!datetime.HasValue)
{
//unassigned
}
``` | Checking to see if a DateTime variable has had a value assigned | [
"",
"c#",
"datetime",
""
] |
Is there any way to access the Windows Event Log from a java class. Has anyone written any APIs for this, and would there be any way to access the data from a remote machine?
The scenario is:
I run a process on a remote machine, from a controlling Java process.
This remote process logs stuff to the Event Log, which I... | On the Java side, you'll need a library that allows you to make native calls. Sun offers [JNI](http://java.sun.com/javase/6/docs/technotes/guides/jni/index.html), but it sounds like sort of a pain. Also consider:
* <https://github.com/twall/jna/>
* <http://johannburkard.de/software/nativecall/>
On the Windows side, t... | [http://www.j-interop.org/](http://www.j-interop.org/ "J-Interop") is an open-source Java library that implements the DCOM protocol specification ***without using any native code***. (i.e. you can use it to access DCOM objects on a remote Windows host from Java code running on a non-Windows client).
Microsoft exposes ... | How do I access Windows Event Viewer log data from Java | [
"",
"java",
"windows",
"logging",
""
] |
I have a directory with 500,000 files in it. I would like to access them as quickly as possible. The algorithm requires me to repeatedly open and close them (can't have 500,000 file open simultaneously).
How can I do that efficiently? I had originally thought that I could cache the inodes and open the files that way, ... | Assuming your file system is [ext3](http://en.wikipedia.org/wiki/Ext3), your directory is indexed with a hashed B-Tree if dir\_index is enabled. That's going to give you as much a boost as anything you could code into your app.
If the directory is indexed, your file naming scheme shouldn't matter.
<http://lonesysadmi... | A couple of ideas:
a) If you can control the directory layout then put the files into subdirectories.
b) If you can't move the files around, then you might try different filesystems, I think xfs might be good for directories with lots of entries? | Quick file access in a directory with 500,000 files | [
"",
"c++",
"linux",
"file-io",
"filesystems",
"inode",
""
] |
I have a time represented as the number of seconds elapsed since midnight, January 1, 1970, UTC (the results of an earlier call to time()). How do I add one day to this time?
Adding 24 \* 60 \* 60 works in most cases, but fails if the daylight saving time comes on or off in between. In other words, I mostly want to ad... | use *gmtime()* to convert the *time\_t* to a *struct tm*
add one to the day (*tm\_mday*)
use *mktime()* to convert the *struct tm* back to a *time\_t*
see [time.h](http://www.cplusplus.com/reference/clibrary/ctime/) for more info
Edit:
I just tried it, this works:
```
int main()
{
time_t base = 1142085600;
fo... | FigBug's solution will work **almost** every time, but it needs DST fix: **tm->tm\_isdst = -1**
> A positive or 0 value for tm\_isdst
> causes mktime() to presume initially
> that Daylight Savings Time,
> respectively, is or is not in effect
> for the specified time. A negative
> value for tm\_isdst causes mktime() to... | How to add one day to a time obtained from time() | [
"",
"c++",
"c",
"date",
"dst",
""
] |
How do I check that I have an open network connection and can contact a specific ip address in c#? I have seen example in VB.Net but they all use the 'My' structure.
Thank you. | If you just want to check if the network is up then use:
```
bool networkUp
= System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
```
To check a specific interface's status (or other info) use:
```
NetworkInterface[] networkCards
= System.Net.NetworkInformation.NetworkInterface.GetAllNetw... | If you want to monitor for changes in the status, use the [`System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged`](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkavailabilitychanged.aspx) event:
```
NetworkChange.NetworkAvailabilityChanged
+= new Netwo... | Checking network status in C# | [
"",
"c#",
".net",
"network-programming",
""
] |
**The background**
I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.
The only decision I'm having trouble with, is whether w... | Django does [work on Jython](http://wiki.python.org/jython/DjangoOnJython), although you'll need to use the development release of Jython, since technically Jython 2.5 is still in beta. However, Django 1.0 and up should work unmodified.
So as to whether you should use the regular Python implementation or Jython, I'd s... | I'd say that if you like Django, you'll also like Python. Don't make the (far too common) mistake of mixing past language's experience while you learn a new one. Only after mastering Python, you'll have the experience to judge if a hybrid language is better than either one.
It's true that very few cheap hostings offer... | Are there problems developing Django on Jython? | [
"",
"python",
"django",
"jvm",
"jython",
""
] |
I have a List object being accessed by multiple threads. There is mostly one thread, and in some conditions two threads, that updates the list. There are one to five threads that can read from this list, depending on the number of user requests being processed.
The list is not a queue of tasks to perform, it is a list ... | Do you have to use a sequential list? If a map-type structure is more appropriate, you can use a `ConcurrentHashMap`. With a list, a `ReadWriteLock` is probably the most effective way.
Edit to reflect OP's edit: Binary search on insertion order? Do you store a timestamp and use that for comparison, in your binary sear... | I don't know if this is a posible solution for the problem but... it makes sense to me to use a Database manager to hold that huge amount of data and let it manage the transactions | Best approach to use in Java 6 for a List being accessed concurrently | [
"",
"java",
"collections",
"concurrency",
""
] |
I have used getopt in Python and was hoping there would be something similar in Java.
Please give a reason why your answer is better than the others. | [Commons CLI](http://commons.apache.org/cli/) | I use [Jewelcli](http://jewelcli.sourceforge.net/index.html) and it's quite good.
You can also find a discussion of different available libraries [here](http://furiouspurpose.blogspot.com/2008/07/command-line-parsing-libraries-for-java.html). | What is the best way of parsing many complex command-line arguments in Java? | [
"",
"java",
"command-line",
""
] |
Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:
```
assertEquals(expectedValue, actualValue);
```
hit `Ctrl` + `Shift` + `O` and have Eclipse add:
```
import static org.junit.Assert.assertEquals;
```
Maybe... | I'm using Eclipse Europa, which also has the Favorite preference section:
> Window > Preferences > Java > Editor > Content Assist > Favorites
In mine, I have the following entries (when adding, use "New Type" and omit the `.*`):
```
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
o... | If you highlight the method `Assert.assertEquals(val1, val2)` and hit `Ctrl` + `Shift` + `M` (Add Import), it will add it as a static import, at least in Eclipse 3.4. | Eclipse Optimize Imports to Include Static Imports | [
"",
"java",
"eclipse",
"keyboard-shortcuts",
""
] |
Let's say we have a concrete `class Apple`. (Apple objects can be instantiated.)
Now, someone comes and derives an abstract `class Peach` from Apple. It's abstract because it introduces a new pure virtual function. The user of Peach is now forced to derive from it and define this new function. Is this a common pattern?... | Re Peach from Apple:
* Don't do it if Apple is a value class
(i.e. has copy ctor, non-identical
instances can be equal, etc). See Meyers
More Effective C++ Item 33 for why.
* Don't do it if Apple has a public
nonvirtual destructor, otherwise you
invite undefined behaviour when your
users delete an Apple th... | It would seem to me like an indication of a bad design. Could be forced if you wanted to take a concrete definition from a closed library and extend it and branch a bunch of stuff off it, but at that point I'd be seriously considering the guideline regarding Encapsulation over Inheritance.. If you possibly can encapsul... | Deriving an abstract class from concrete class | [
"",
"c++",
"inheritance",
"abstract-class",
"pure-virtual",
""
] |
I am using this HTML
```
<html>
<head>
<Title>EBAY Search</title>
</head>
<script language="JavaScript" src="ajaxlib.js"></script>
<body>
Click here <a href="#" OnClick="GetEmployee()">link</a> to show content
<div id="Result"><The result will be fetched here></div>
</body>
... | use a javascript debugging tool like firebug, this will make your life simpler.
you had a syntax error in your code that made the error "GetEmployee is not defined"
it was a missing "catch" after the last try in "GetXmlHttpObject()". this is the same function after adding the missing "catch".
```
function GetXmlHttp... | ```
var url="get_employee.php?"
```
Needs the "?".
It's better to use this markup to include your scripts:
```
<script type="text/javascript" src="ajaxlib.js"></script>
``` | javascript not being called | [
"",
"javascript",
"html",
"ajax",
""
] |
> **Possible Duplicate:**
> [PDO Prepared Statements](https://stackoverflow.com/questions/210564/pdo-prepared-statements)
I'm using the mysqli extension in PHP and I'm wondering, is there possibly any way to see a prepared query as it will be executed on the server, e.g. The query is something like this
```
select ... | **Duplicate of [PDO Prepared Statements](https://stackoverflow.com/questions/210564/pdo-prepared-statements)**
Short answer: no. A prepared query will never be converted to the query you expect. It's executed directly by the database server. You can use mysql's query log or PDO's undocumented function `debugDumpParams... | Turn on [mysql query logging](http://dev.mysql.com/doc/refman/5.0/en/query-log.html) and it will log all queries to a text file for you to review. | Is there a way to see a prepared query as it will be executed on the database? | [
"",
"php",
"mysql",
"mysqli",
""
] |
EDIT: For the inner queries, there could be more than one match per inner query. It grabs a bunch of tags with the same game\_ID. Thats why .First or .Max won't work.
Need some help, I have a query in LINQ that looks like this:
```
from yy in Tags_Lookups
where yy.Tag_ID == (from xx in Tags_Lookups
where xx.Game_ID =... | Since your inner query can return multiple matches, you just need to convert the inner query to a list and reverse the sense of the contains clause, I think.
```
from yy in Tags_Lookups
where (from xx in Tags_Lookups
where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c")
select xx.Tag_ID).T... | Just saw the edit - I think this is what you want (check my syntax, though):
```
from yy in Tags_Lookups
join xx in Tags_Lookups on yy.Tag_ID Equals xx.Tag_ID
where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c")
select yy
```
That will get you a Tags\_Lookups value for every matching Game\_ID. You may... | Linq Help. int.Contains and int == iqueryable doesn't work | [
"",
"c#",
"asp.net",
"linq",
""
] |
another request sorry..
Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line..
if my file contains
```
Hey Bob
Now
```
should give me
```
Hey
Bob
[NEW LINE]
NOW
```
Is there a way to do this without using getline? | Yes the operator>> when used with string read 'white space' separated words. A 'White space' includes space tab and new line characters.
If you want to read a line at a time use std::getline()
The line can then be tokenized separately with a string stream.
```
std::string line;
while(std::getline(std::cin,line))
... | I don't know why you think `std::getline` is bad. You can still recognize newlines.
```
std::string token;
std::ifstream file("file.txt");
while(std::getline(file, token)) {
std::istringstream line(token);
while(line >> token) {
std::cout << "Token :" << token << std::endl;
}
if(file.unget().ge... | C++ Reading file Tokens | [
"",
"c++",
"file",
"token",
""
] |
I'm creating some big files (DB exports) with Java and I need to put them somewhere on our SharePoint server. Right now, I'm doing this with IE but I'd like to automate this step, too.
I searched the web and I found some hints to use SOAP but I don't really see to the ground of all this, yet. Can someone provide me wi... | Okay ... after several hours of work and biting myself through the "documentation" MicroSoft provides and all the hints randomly spread over the 'net, I've managed to write some sample code to browse the content of a SharePoint server: [Navigating SharePoint Folders With Axis2](http://blog.pdark.de/2008/11/navigating-s... | In addition to [Sacha's suggestions](https://stackoverflow.com/questions/314258/how-do-i-upload-a-document-to-sharepoint-with-java/314283#314283), you can use the SharePoint SOAP web services. Each SharePoint site exposes a bunch of web services via the path `http://<Site>/_vti_bin/`.
In your case, you probably want t... | How do I upload a document to SharePoint with Java? | [
"",
"java",
"sharepoint",
"soap",
"upload",
""
] |
Say I have a stored procedure that returns data from a SELECT query. I would like to get a slightly different cut on those results depending on what parameters I pass through. I'm wondering whether it is better design to have multiple stored procedures that take one or no parameters to do this (for example, GetXByDate ... | The more complex stored procedures are more complex for the SQL server to compile
correctly and execute quickly and efficiently.
Even in the big stored procedure you have to either have to have several copies of the query or add lots of CASEs and IFs in it which reduce performance. So you don't really gain much from l... | I would treat stored procedures much in the same way as I would a method on a class. It ought to do one thing and do it simply. Consider applying the same sorts of refactoring/code smell rules to your stored procedures that you would to your application code. | Is it better to write a more targeted stored procedure with fewer parameters? | [
"",
"sql",
"stored-procedures",
""
] |
I need to replace our [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) Modal Popup controls with a JavaScript equivalent. We use this as a simple context sensitive help type popup. I did a quick browse but didn't see quite what I was looking for. I just need some text and a simple Close button/link, but I wo... | I can provide you the code. Do your modifications as necessary, OK?
Page JavaScript:
```
function myPop() {
this.square = null;
this.overdiv = null;
this.popOut = function(msgtxt) {
//filter:alpha(opacity=25);-moz-opacity:.25;opacity:.25;
this.overdiv = document.createElement("div");
... | I've used the simplemodal jQuery plugin and I've been quite happy with it. You can check it out [here](http://www.ericmmartin.com/projects/simplemodal/). | How to code a JavaScript modal popup (to replace Ajax)? | [
"",
"javascript",
"modalpopups",
""
] |
I have an application that needs to send a moderately high volume of messages between a number of AppDomains. I know that I could implement this using remoting, but I have also noticed that there are cross-domain delegates. Has anyone looked at this kind of problem? | I have had good success using WCF with a named pipes binding. Using named pipes creates no network traffic and uses binary encoding, so it should be pretty fast without sacrificing the ability to distribute in future scaling scenarios.
EDIT:
Refer [here](https://stackoverflow.com/questions/50153/interprocess-communica... | A cross-domain delegate only allows a void method with zero parameters, and it's probably not what you think it is. It's only barely useful as a simple callback for notification purposes from one appdomain to another, e.g. a method like InitComplete() or something.
Remoting is the ONLY choice, whether you call it WCF ... | How best to communicate between AppDomains? | [
"",
"c#",
".net",
"remoting",
"appdomain",
""
] |
I am running a java program that sets up a database connection to an SQL database. It works fine on Mac OS X, but when I try to run the same code on Linux, I get a Exception in thread "main" java.lang.NoClassDefFoundError: java/sql/SQLClientInfoException.
I am using jdk-1.6.0\_02 - if I unzip src.zip, it turns out tha... | SQLClientInfoException is new in Java 1.6 and should be present in the src.zip. I have a `jdk1.6.0_03` in Windows and a `jdk1.6.0_06` in Linux and the class is included in both. Try to upgrade to the latest version. | Make sure you're actually running the sun JDK and not the GCJ version that ships as standard on many linux distributions. That version is a bit outdated and prone to weird bugs like this. | SQLClientInfoException / Linux | [
"",
"java",
"linux",
""
] |
Is there a way I can set up callbacks on (or automataically log) method parameters, entries, and exits without making explicit calls within each method? I basically want to log this information to my logger class (which is static) without having to do it manually for each method.
Right now I have to call Logger::logEn... | use a wrapper class. this method has the following benefits:
* no need to change your underlying class structure / method signatures
* change logging? just update this class
* update object calls vs inserting code into every class you want to log
.
```
class LogWatch {
function __construct($class) {
$... | If you want to do function logging for the sake of debugging you may want to look into the Xdebug extension. There's no good way to intercept function calls at at runtime, and any automated interception will add great runtime overhead.
Using XDebug you could instead turn it on as-needed, as well as get lots of other s... | PHP: Callback on Entry/Exit of Class Methods? | [
"",
"php",
"logging",
"methods",
"callback",
"stack-trace",
""
] |
I am creating a large table dynamically using Javascript.
I have realised the time taken to add a new row grows exponentially as the number of rows increase.
I suspect the Page is getting refreshed in each loop per row (I am also adding input elements of type text on each cell)
Is there a way to stop the page "refres... | Use the table DOM to loop trough the rows and cells to populate them, instead of using document.getElementByID() to get each individual cell.
```
E.g.
thisTable = document.getElementByID('mytable');//get the table
oneRow = thisTable.rows[0].cells; //for instance the first row
for (var colCount = 0; colCount <totalCols... | You can create the table object without adding it to the document tree, add all the rows and then append the table object to the document tree.
```
var theTable = document.createElement("table");
// ...
// add all the rows to theTable
// ...
document.body.appendChild(theTable);
``` | How to "pause" refresh of page when drawing HTML table dynamically | [
"",
"javascript",
"html",
""
] |
I have two tables: a source table and a target table. The target table will have a subset of the columns of the source table. I need to update a single column in the target table by joining with the source table based on another column. The update statement is as follows:
```
UPDATE target_table tt
SET special_id = ( ... | Your initial query executes the inner subquery once for every row in the outer table. See if Oracle likes this better:
```
UPDATE target_table
SET special_id = st.source_special_id
FROM
target_table tt
INNER JOIN
source_table st
WHERE tt.another_id = st.another_id
```
(edited after posted query ... | Is there an index on source\_table(another\_id)? If not source\_table will be fully scanned once for each row in target\_table. This will take some time if target\_table is big.
Is it possible for there to be no match in source\_table for some target\_table rows? If so, your update will set special\_id to null for tho... | How can I speed up a joined update in SQL? My statement seems to run indefinitely | [
"",
"sql",
"oracle",
"performance",
""
] |
I'm trying to get a handle on if there's a good time to use standard linq keywords or linq extension methods with lambda expressions. They seems to do the same thing, just are written differently. Is it purely a matter of style?
```
var query = from p in Products
where p.Name.Contains("foo")
orderby c.Name
... | Honestly, sometimes it can be situational once you start using Funcs and Actions. Say you are using these three funcs:
```
Func<DataClasses.User, String> userName = user => user.UserName;
Func<DataClasses.User, Boolean> userIDOverTen = user => user.UserID < 10;
Func<DataClasses.User, Boolean> userIDUnderTen = us... | One advantage to using LINQ extension methods (*method-based queries*) is that you can define custom extension methods and it will still read fine.
On the other hand, when using a LINQ *query expression*, the custom extension method is not in the keywords list. It will look a bit strange mixed with the other keywords.... | Extension methods syntax vs query syntax | [
"",
"c#",
".net",
"linq",
"extension-methods",
"linq-query-syntax",
""
] |
I haven't used regular expressions at all, so I'm having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this beha... | Use the beginning and end anchors.
```
Regex regex = new Regex(@"^\d$");
```
Use `"^\d+$"` if you need to match more than one digit.
---
Note that `"\d"` will match `[0-9]` and other digit characters like the Eastern Arabic numerals `٠١٢٣٤٥٦٧٨٩`. Use `"^[0-9]+$"` to restrict matches to just the Arabic numerals 0 - ... | Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:
```
regex = new Regex("^[0-9]+$");
```
The `^` will anchor the beginning of the string, the `$` will anchor the end of the string, and the `+` will match one or more of what pre... | Regex for numbers only | [
"",
"c#",
"regex",
""
] |
I am using Eclipse 3.3 ("Europa"). Periodically, Eclipse takes an inordinately long time (perhaps forever) to start up. The only thing I can see in the Eclipse log is:
```
!ENTRY org.eclipse.core.resources 2 10035 2008-10-16 09:47:34.801
!MESSAGE The workspace exited with unsaved changes in the previous sessio... | This may not be an exact solution for your issue, but in my case, I tracked the files that Eclipse was polling against with [SysInternals Procmon](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx), and found that Eclipse was constantly polling a fairly large snapshot file for one of my projects. Removed th... | try:
1. cd to **<workspace>\.metadata\.plugins\org.eclipse.core.resources**
2. remove the file **\*.snap** (or **.markers** in Indigo) | How do I prevent Eclipse from hanging on startup? | [
"",
"java",
"eclipse",
"eclipse-3.3",
""
] |
[C++11](http://en.wikipedia.org/wiki/C%2B%2B11) introduces [user-defined literals](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2378.pdf) which will allow the introduction of new literal syntax based on existing literals (`int`, `hex`, `string`, `float`) so that any type will be able to have a literal prese... | Here's a case where there is an advantage to using user-defined literals instead of a constructor call:
```
#include <bitset>
#include <iostream>
template<char... Bits>
struct checkbits
{
static const bool valid = false;
};
template<char High, char... Bits>
struct checkbits<High, Bits...>
{
static ... | At first sight, it seems to be simple syntactic sugar.
But when looking deeper, we see it's more than syntactic sugar, as **it extends the C++ user's options to create user-defined types that behave exactly like distinct built-in types.** In this, this little "bonus" is a very interesting C++11 addition to C++.
## Do... | What new capabilities do user-defined literals add to C++? | [
"",
"c++",
"c++11",
"user-defined-literals",
""
] |
I've got a console application that compiles and executes fine with Visual C++ 6.0, except that it will then only get as far as telling me about missing command line parameters. There doesn't seem to be anywhere obvious to enter these. How do I run or debug it with command line parameters? | I assume you're talking about setting the command line parameters for running in the IDE.
Open the Project/Settings property page and go to the Debug tab.
There's a "Program arguments" field you can put them into. | If I remember correctly, under Project/Settings/Debug tab there is a place to enter the command line parameters. It's the "Program arguments" field. | How to run a console application with command line parameters in Visual C++ 6.0? | [
"",
"c++",
"command-line",
"parameters",
"visual-c++-6",
""
] |
Let's say you have a text file like this one:
<http://www.gutenberg.org/files/17921/17921-8.txt>
Does anyone has a good algorithm, or open-source code, to extract words from a text file?
How to get all the words, while avoiding special characters, and keeping things like "it's", etc...
I'm working in Java.
Thanks | This sounds like the right job for regular expressions. Here is some Java code to give you an idea, in case you don't know how to start:
```
String input = "Input text, with words, punctuation, etc. Well, it's rather short.";
Pattern p = Pattern.compile("[\\w']+");
Matcher m = p.matcher(input);
while ( m.find() ) {
... | Here's a good approach to your problem:
This function receives your text as an input and returns an array of all the words inside the given text
```
private ArrayList<String> get_Words(String SInput){
StringBuilder stringBuffer = new StringBuilder(SInput);
ArrayList<String> all_Words_List = new ArrayList<Stri... | Extract words out of a text file | [
"",
"java",
"text",
""
] |
I've noticed, using visual studio 2003, that I can "comment out" my comments to make them no longer be comments. This one needs an example:
If I have:
```
/*
int commented_out = 0;
*/
```
I can comment out the /\* and \*/ with // and code within the /\* and \*/ is no longer "commented out" (the text changes to non-c... | Yep, this is perfectly normal behavior. The C++ standard says that a `/*` is the start of a comment block only if it itself is not commented out. I often use what you've written above to comment or uncomment a block of code by adding/deleting one character. A nice little trick for switching between two blocks of code, ... | It should work in any compiler as the `//` is encountered first in the input stream.
I tend to use `#if 0` for this sort of stuff and change it to `#if 1` to uncomment, shown here:
```
#if 0
int commented_out = 0;
#endif
```
Then I don't have to worry about comment markers at all. | Commenting out comments | [
"",
"c++",
"comments",
""
] |
I'm looking for a .NET library that will allow creation of a Word document. I need to export HTML based content to a Word doc (97-2003 format, not docx).
I know that there are the Microsoft Office Automation libraries and Office interop, but as far as I can tell, they require that you have office actually installed an... | *Would it work if I somehow converted the CSS to be embedded in the HTML??*
Yes. I use an internal style sheet, as I mentioned.
Document Example:
```
<html>
<head>
<STYLE type="text/css">
h1 {text-align:center; font-size:12.0pt; font-family:Arial; font-weight:bold;}
p {margin:0in; margin-bottom:0pt; font-si... | I use Aspose for working with Word, makes everything a breeze: <http://www.aspose.com/> | Export to Word Document in C# | [
"",
"c#",
"ms-word",
"export",
""
] |
I am binding the dropdown with db entity.
```
ddlCustomer.DataSource = Customer.GetAll();
ddlCustomer.DataTextField = "CustomerName";
ddlCustomer.DataBind();
```
I want to add "SELECT" as the first itemlist in dropdown and bind then entity to the dropdown. How can i do this? | Add:
```
ddlCustomer.Items.Insert(0, "SELECT");
```
After ddlCustomer.DataBind();
The item must be inserted after the data bind because the data bind clears the items. | I know there is an answer already, but you can also do this:
```
<asp:DropDownList AppendDataBoundItems="true" ID="ddlCustomer" runat="server">
<asp:ListItem Value="0" Text="Select"/>
</asp:DropDownList>
```
That way, you won't have to worry about when you call Databind and when you add the select-item. | Databinding DropDown Control in .Net | [
"",
"c#",
".net",
"winforms",
"data-binding",
".net-2.0",
""
] |
Imagine I have a property defined in global.asax.
```
public List<string> Roles
{
get
{
...
}
set
{
...
}
}
```
I want to use the value in another page. how to I refer to it? | You can access the class like this:
```
((Global)this.Context.ApplicationInstance).Roles
``` | It looks to me like that only depends on the session - so why not make it a pair of static methods which take the session as a parameter? Then you can pass in the value of the "Session" property from the page. (Anything which *does* have access to the HttpApplication can just reference its Session property, of course.) | How do I access properties from global.asax in some other page's code behind | [
"",
"c#",
"asp.net",
"global-asax",
""
] |
I am using Borland Turbo C++ with some inlined assembler code, so presumably Turbo Assembler (TASM) style assembly code. I wish to do the following:
```
void foo::bar( void )
{
__asm
{
mov eax, SomeLabel
// ...
}
// ...
SomeLabel:
// ...
}
```
So the address of SomeLabel is placed into... | Last time I tried to make some assembly code Borland-compatible I came across the limitation that you can't forward-reference labels. Not sure if that's what you're running into here. | Everything I can find about Borland suggests this ought to work. Similar questions on other sites ([here](http://www.experts-exchange.com/Programming/Languages/Assembly/Q_21731289.html) and [here](http://www.tek-tips.com/viewthread.cfm?qid=972872&page=10)) suggest that Borland can handle forward-references for labels, ... | Borland x86 inlined assembler; get a label's address? | [
"",
"c++",
"assembly",
"x86",
"turbo-c++",
""
] |
The [var](http://msdn.microsoft.com/en-us/library/bb384061.aspx) keyword does away with the need for an explicit type declaration and I have read with interest the [SO discussion](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c) of when it might be appropriate.
I have also read about (but not used) [... | **Update:** There are two related questions here, actually:
1. Why do I have to declare variables at all?
2. What use is "var" in a language that makes you declare variables?
The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:
As other commenters have said, LINQ u... | Without the var keyword it becomes possible to accidentally create a new variable when you had actually intended to use an already existing variable. e.g.
```
name = "fred";
...
Name = "barney"; // whoops! we meant to reuse name
``` | What's the point of the var keyword? | [
"",
"c#",
"variables",
"boo",
""
] |
I am working on implementing Zend Framework within an existing project that has a public marketing area, a private members area, an administration site, and a marketing campaign management site. Currently these are poorly organized with the controller scripts for the marketing area and the members area all being under ... | What I do is keep common classes in a "library" directory outside of the modules hierarchy. Then set my `INCLUDE_PATH` to use the "models" directory of the respective module, plus the common "library" directory.
```
docroot/
index.php
application/
library/ <-- common classes go here
default/
con... | This can also be accomplished through a naming convention to follow `Zend_Loader`. Keep your model files in the models folder under their module folder. Name them as `Module_Models_ModelName` and save them in a file name ModelName.php in the models folder for that module. Make sure the application folder is in your inc... | How to Use Same Models in Different Modules in Zend Framework? | [
"",
"php",
"model-view-controller",
"zend-framework",
"module",
""
] |
If I've got an array of values that are basically zero-padded string representations of various numbers and another array of integers, will `array_intersect()` still match elements of different types?
For example, would this work:
```
$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);
$intersect ... | $ cat > test.php
```
<?php
$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);
$intersect = array_intersect($arrayOne, $arrayTwo);
print_r($intersect );
?>
```
$ php test.php
Array
(
)
$
So no, it will not. But if you add
```
foreach($arrayOne as $key => $value)
{
$arrayOne[$key] = intval... | From <https://www.php.net/manual/en/function.array-intersect.php>:
> ```
> Note: Two elements are considered equal if and only if
> (string) $elem1 === (string) $elem2.
> In words: when the string representation is the same.
> ```
In your example, $intersect will be an empty array because 5 !== "005" and 4 !== "004" | Filtering array with array_intersect() - values are equal as integers, but not as strings | [
"",
"php",
"arrays",
"casting",
"types",
"array-intersect",
""
] |
I'm trying to find a way to get the open tasks in C#. I've been searching on google and can only find how to get a list of the **processes**. I want the only the tasks that would show up on the taskbar.
Also, along with that, it would be cool if I could get the process the task is associated with. And if possible get ... | This article should pretty much tell you exactly what to do, it shows how to build your own task switch and includes the code needed to enumerate all windows and determine if they are "tasks" and it shows you how to use PrintWindow api to get the previews on XP.
<http://msdn.microsoft.com/en-us/library/ms997649.aspx>
... | From an API (Win32) perspective there is no such thing as Tasks (at least not the one that Windows Task Manager/Alt-Tab shows).
Those "Tasks" are actually top level windows.
So in order to get a list of those, you need to [enumerate the windows](http://msdn.microsoft.com/en-us/library/ms682615(VS.85).aspx) (here is t... | C# - Get list of open tasks | [
"",
"c#",
".net",
"taskbar",
"task",
""
] |
I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:
```
>>> my_ar = numpy.array((0,5,10))
[0, 5, 10]
>>> transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful
array([
[ 0, 0, 0],
[ ... | Use map to apply your transformation function to each element in my\_ar:
```
import numpy
my_ar = numpy.array((0,5,10))
print my_ar
transformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar))
print transformed
print transformed.shape
``` | Does numpy.dstack do what you want? The first two indexes are the same as the original array, and the new third index is "depth".
```
>>> import numpy as N
>>> a = N.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> b = N.dstack((a,a,a))
>>> b
array([[[1, 1, 1],
... | Adding a dimension to every element of a numpy.array | [
"",
"python",
"arrays",
"numpy",
""
] |
Is it necessary for setter methods to have one argument? Usually setter methods accept one argument as the value of a certain property of an Object. What if I want to test first the validity which depends on another argument which is a boolean, if true, validate first, else just set the value.
I am getting the values ... | It is necessary specifically in the java bean framework model, but it s not mandatory in general.
You can have setter with no argument when they are meant to "swith" a value.
```
void setCheck()
```
could for instance be meant to set the "check" boolean attribute to true.
So even if it is not a "setter" in the java... | By Java Bean specification setter have one argument. If you add another one, for whatever reason, it is not considered setter anymore.
Setter is perfectly valid to "clean up" its argument, or throw exception if is invalid. | Is it necessary for setter methods to have one argument? | [
"",
"java",
"setter",
""
] |
When reading a stack trace like:
```
[FormatException: Input string was not in a correct format.]
System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +2755599
System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info... | It means:
> it’s an offset into the native instructions for the method.
Read [this](http://odetocode.com/blogs/scott/archive/2005/01/24/funny-numbers-in-my-stack-trace.aspx) for more details. | I believe they're offsets into the code of the method - whether IL or JIT-compiled-assembly bytes, I'm not sure...
(Basically they're taking the place of line numbers, which of course aren't available without the pdbs.) | What do the "+n" values mean at the end of a method name in a stack trace? | [
"",
"c#",
".net",
""
] |
I am trying to write a decorator to do logging:
```
def logger(myFunc):
def new(*args, **keyargs):
print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
return myFunc(*args, **keyargs)
return new
class C(object):
@logger
def f():
pass
C().f()
```
I would like ... | Claudiu's answer is correct, but you can also cheat by getting the class name off of the `self` argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example:
```
from functools import wraps # use this to preserve functi... | Functions only become methods at runtime. That is, when you get `C.f` you get a bound function (and `C.f.im_class is C`). At the time your function is defined it is just a plain function, it is not bound to any class. This unbound and disassociated function is what is decorated by logger.
`self.__class__.__name__` wil... | Python decorator makes function forget that it belongs to a class | [
"",
"python",
"reflection",
"metaprogramming",
""
] |
I have a site made with php which uses server side sessions throughout the site.
In fact, it's a site with a user login which depends on session variables and if there were a problem with *all* session variables, no pages would load at all.
On the site, there's an iframe that holds a feed of little messages from oth... | I thought some people might find the solution to this problem interesting. Fiddler certainly helped here. Thanks to Fiddler, I could see that I was, in fact, hitting the page main.php (thus setting the session variable moments after setting it on the target page), but the server was defaulting there after getting a 302... | Check the name of the server machine. IE has problems with machine names that contain '-' or '\_' - they cannot maintain a session! I've had this problem twice in the past, and it always takes me weeks to figure out, and I'm shocked IE hasn't fixed it.
Just rename the machine to have no strange characters! You can get... | PHP session doesn't work with IE | [
"",
"php",
"internet-explorer",
"session",
""
] |
There is two available Eclipse plugins for Maven :
* [Eclipse IAM](http://www.eclipse.org/proposals/iam/) (old name is Q4E)
* [m2eclipse](http://m2eclipse.codehaus.org/)
m2eclipse seems to be the oldest but the more robust. Is there any key differences between the two ?
Which one should be chosen for a project start... | I choose **m2eclipse** since it is stable and have all that I need. Especially ability to resolve dependencies inside workspace.
I tried the other one some time ago and didn't like it. It was to buggy so I gave up quickly. | The side by side comparison is moved to <http://web.archive.org/web/20150526230611/http://docs.codehaus.org/display/MAVENUSER/Eclipse+Integration> | Which is the best Maven Eclipse plugin? | [
"",
"java",
"eclipse",
"maven-2",
"eclipse-plugin",
""
] |
How do I write the getDB() function and use it properly?
Here is a code snippet of my App Object:
```
public class MyApp extends UiApplication {
private static PersistentObject m_oStore;
private static MyBigObjectOfStorage m_oDB;
static {
store = PersistentStore.getPersistentObject(0xa1a56927823... | ```
public MyBigObjectOfStorage getDB() {
return m_oDB;
}
```
As you put it is correct. It will return a *copy of the reference*, which is kind of in between a copy and a reference.
The actual object instance returned by getDB() is the same object referenced by m\_oDB. However, you can't change the reference return... | I am one of those folks that are very much against using singletons and/or statics as it tends to make unit testing impossible. As this is posted under best practices, I suggest that you take a look at using a dependency injection framework. Personally I am using and prefer [Google Guice](http://code.google.com/p/googl... | Java Application/Class Design - How do accessors in Java work? | [
"",
"java",
""
] |
I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using `#!/usr/bin/env groovy` at the top of my script. | If you really have to you can also load a JAR at runtime with:
```
this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())
``` | Starting a groovy script with `#!/usr/bin/env groovy` has a very important limitation - **No additional arguments can be added.** No classpath can be configured, no running groovy with defines or in debug. This is not a [groovy](http://jira.codehaus.org/browse/GMOD-226 "groovy issue") issue, but a limitation in how the... | How do I include jars in a groovy script? | [
"",
"java",
"groovy",
"jar",
"classpath",
""
] |
I am having trouble deleting orphan nodes using JPA with the following mapping
```
@OneToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner")
private List<Bikes> bikes;
```
I am having the issue of the orphaned roles hanging around the database.
I can use the annotation `org.hibernate.annota... | If you are using it with Hibernate, you'll have to explicitly define the annotation `CascadeType.DELETE_ORPHAN`, which can be used in conjunction with JPA `CascadeType.ALL`.
If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan... | If you are using JPA 2.0, you can now use the `orphanRemoval=true` attribute of the `@xxxToMany` annotation to remove orphans.
Actually, `CascadeType.DELETE_ORPHAN` has been deprecated in 3.5.2-Final. | JPA CascadeType.ALL does not delete orphans | [
"",
"java",
"hibernate",
"orm",
"jpa",
"jpa-2.0",
""
] |
More detail to my question:
HTML and JavaScript are called "client-side code".
C# and VB in the code behind files are termed "server-side code".
So what is inline-asp, and 'runat=server' code blocks called?
```
<!-- This is called "client-side" -->
<p>Hello World</p>
<script>alert("Hello World");</script>
```
...
... | To be explicit, Microsoft calls them Embedded Code Blocks.
<http://msdn.microsoft.com/en-us/library/ms178135.aspx>
They are code blocks embeded into the page lifecycle by being called during the Render phase. | The sections of an ASP page that start with *`<%`* and end with *`%>`* are [**code render blocks**](https://msdn.microsoft.com/en-us/library/k6xeyd4z(v=vs.90).aspx "MSDN: Code Render Blocks") and `<script>` elements with `runat=server` are called [**code declaration blocks**](http://msdn.microsoft.com/en-us/library/2cy... | In ASP.NET, What is the 'ASP' code called? | [
"",
"c#",
"asp.net",
"terminology",
""
] |
From googling around it looks like Xcode (3.1 in my case) should be at least trying to give me a sane debug view of STL containers - or at least vectors.
However, whenever I go to look at a vector in the debugger I just see M\_impl, with M\_start and M\_finish members (and a couple of others) - but nothing in-between!... | The ability to view the container's items may rely on the complexity of the templated type. For trivial objects like int, bool, etc., and even simple class templates like
```
template <class T> struct S { T m_t; }
```
I *normally* have no problem viewing vector items in the debugger variable view. I say normally beca... | You can create [Data formatters](https://web.archive.org/web/20090812202145/http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeDebugging/600-Viewing_Variables_and_Memory/variables_and_memory.html) for different variable types so they show up nicer :-). | Inspecting STL containers in Xcode | [
"",
"c++",
"xcode",
"debugging",
"macos",
"stl",
""
] |
I'm looking for a good Java obfuscator.
I've done initial research into the following Java obfuscators: proguard, yguard, retroguard, dasho, allatori, jshrink, smokescreen, jobfuscate, marvin, jbco, jode, javaguard, jarg, joga, cafebabe, donquixote, mwobfu, bbmug, zelix klassmaster, sandmark, jcloak, thicket, blufusca... | I use [ProGuard](http://proguard.sourceforge.net) heavily for all my release builds and I have found it is excellent. I can't recommend it enough!
I *have* encountered obscure bugs caused by it's optimizations on several occasions and I now disable optimizations across the board - haven't had a problem caused by ProGu... | A good collection of links to free and commercial tools is given in this arcticle
["Protect Your Java Code - Through Obfuscators And Beyond"](http://www.excelsior-usa.com/articles/java-obfuscators.html)
The author also discusses the strong and weak points of bytecode obfuscation | Java obfuscators | [
"",
"java",
"obfuscation",
""
] |
I am using Delphi 7 and ICS components to communicate with php script and insert some data in mysql database...
How to post unicode data using http post ?
After using utf8encode from tnt controls I am doing it to post to PHP script
```
<?php
echo "Note = ". $_POST['note'];
if($_POST['action'] == 'i')
{
/*
... | Your example code shows your data coming from a TNT Unicode control. That value will have type `WideString`, so to get UTF-8 data, you should call `Utf8Encode`, which will return an `AnsiString` value. Then call `UrlEncode` on that value. Make sure `UrlEncode`'s input type is `AnsiString`. So, something like this:
```... | Encode the UTF-8 data in application/x-www-form-urlencoded. This will ensure that the server can read the data over the http connection | How to do HTTP POST in Utf-8 -> php script -> mysql | [
"",
"php",
"delphi",
"unicode",
""
] |
I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in t... | Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.
Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will i... | At first, try compacting and repairing the .mdb file.
Then, simplify your WHERE clause:
```
WHERE
[drawername] Like Nz(Forms!FrmSearchCompany!SearchName, "") & "*"
And
[Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, "") & "*"
And
[drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortco... | Slow SQL Code on local server in MS Access | [
"",
"sql",
"ms-access",
""
] |
I have an Informix SQL query which returns a set of rows. It was slightly modified for the new version of the site we've been working on and our QA noticed that the new version returns different results. After investigation we've found that the only difference between two queries were in the number of fields returned.
... | The Informix SQL engine uses the indices on the tables based on the columns we want to retrieve. When retrieving different columns we were using different indices and therefore getting the results in different order. | Adding `--+ ORDERED` join-order directive fixes the problem by allowing you to get your results in predictable order each time.
The links goes to the description of how the directive works
<http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls1144.htm>
> Use the ORDERED join-orde... | Informix SQL query: Two similar queries returning different results | [
"",
"sql",
"database",
"informix",
""
] |
We would need to embed mathematical formulas through [AsciiMathML](http://www1.chapman.edu/~jipsen/asciimath.html) into [Google Sites](http://sites.google.com) pages (internal wiki for a research team). I am stuck with the limitation of Google Sites.
Any idea how to do that?
(ps: I have finally found a [poorly practi... | I used to use [texify.com](http://www.texify.com/), but they're no longer available. Now I use [Google Infographics Mathematical Formulas](http://code.google.com/apis/chart/infographics/docs/formulas.html), which has more features *and* (IMO) is more likely to continue being available in the future. | I had the same problem, but found texify: <http://www.texify.com/> as a complete solution. Texify is an online tex editor rendering gifs, and not AsciiMathML, but I found it quick to get the hang of. Just add the html code generated into your source in Google Sites, or insert picture from the GUI. | How to embed AsciiMathML in Google Sites? | [
"",
"javascript",
"math",
"mathml",
"google-sites",
""
] |
I am trying to declare and use a class B inside of a class A
and define B outside A.
I know for a fact that this is possible because Bjarne Stroustrup
uses this in his book "The C++ programming language"
(page 293,for example the String and Srep classes).
So this is my minimal piece of code that causes problems
... | Define the constructor for A AFTER the definition of struct B. | The expression `c->i` dereferences the pointer to `struct A::B` so a full definition must be visible at this point in the program.
The simplest fix is to make the constructor of `A` non-inline and provide a body for it after the defintion of `struct A::B`. | C++ Nested classes forward declaration error | [
"",
"c++",
"class",
"nested",
"declaration",
"forward",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.