Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to install an application meant to be run by an end user? | Once you get to the point where your application is ready for distribution, package it up for your favorite distributions/OSes in a way that puts your library code in site-packages and executable scripts on the system path.
Until then (i.e. for all development work), don't do any of the above: save yourself major headaches and use [zc.buildout](http://pypi.python.org/pypi/zc.buildout) or [virtualenv](http://pypi.python.org/pypi/virtualenv) to keep your development code (and, if you like, its dependencies as well) isolated from the rest of the system. | We do it like this.
Most stuff we download is in site-packages. They come from `pypi` or Source Forge or some other external source; they are easy to rebuild; they're highly reused; they don't change much.
Must stuff we write is in other locations (usually under `/opt`, or `c:\opt`) AND is included in the `PYTHONPATH`.
There's no *great* reason for keeping our stuff out of `site-packages`. However, our feeble excuse is that our stuff changes a lot. Pretty much constantly. To reinstall in site-packages every time we think we have something better is a bit of a pain.
Since we're testing out of our working directories or SVN checkout directories, our test environments make heavy use of `PYTHONPATH`.
The development use of `PYTHONPATH` bled over into production. We use a `setup.py` for production installs, but install to an alternate home under `/opt` and set the `PYTHONPATH` to include `/opt/ourapp-1.1`. | Is site-packages appropriate for applications or just libraries? | [
"",
"python",
""
] |
I would like to be able to print object properties, and I've hit a snag when I hit nested collections of the iLists.
```
foreach (PropertyInformation p in properties)
{
//Ensure IList type, then perform recursive call
if (p.PropertyType.IsGenericType)
{
// recursive call to PrintListProperties<p.type?>((IList)p," ");
}
```
Can anyone please offer some help?
Cheers
KA | I'm just thinking aloud here. Maybe you can have a non generic PrintListProperties method that looks something like this:
```
private void PrintListProperties(IList list, Type type)
{
//reflect over type and use that when enumerating the list
}
```
Then, when you come across a nested list, do something like this:
```
if (p.PropertyType.IsGenericType)
{
PringListProperties((Ilist)p,p.PropertyType.GetGenericArguments()[0]);
}
```
Again, haven't tested this, but give it a whirl... | ```
foreach (PropertyInfo p in props)
{
// We need to distinguish between indexed properties and parameterless properties
if (p.GetIndexParameters().Length == 0)
{
// This is the value of the property
Object v = p.GetValue(t, null);
// If it implements IList<> ...
if (v != null && v.GetType().GetInterface("IList`1") != null)
{
// ... then make the recursive call:
typeof(YourDeclaringClassHere).GetMethod("PrintListProperties").MakeGenericMethod(v.GetType().GetInterface("IList`1").GetGenericArguments()).Invoke(null, new object[] { v, indent + " " });
}
Console.WriteLine(indent + " {0} = {1}", p.Name, v);
}
else
{
Console.WriteLine(indent + " {0} = <indexed property>", p.Name);
}
}
``` | C# - Reflection using Generics: Problem with Nested collections of ILists | [
"",
"c#",
"generics",
"reflection",
"nested",
"ilist",
""
] |
Is there a way to have mod\_wsgi reload all modules (maybe in a particular directory) on each load?
While working on the code, it's very annoying to restart apache every time something is changed. The only option I've found so far is to put `modname = reload(modname)` below every import.. but that's also really annoying since it means I'm going to have to go through and remove them all at a later date.. | The mod\_wsgi [documentation on code reloading](http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode) is your best bet for an answer. | The link:
<http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode>
should be emphasised. It also should be emphaised that on UNIX systems daemon mode of mod\_wsgi must be used and you must implement the code monitor described in the documentation. The whole process reloading option will not work for embedded mode of mod\_wsgi on UNIX systems. Even though on Windows systems the only option is embedded mode, it is possible through a bit of trickery to do the same thing by triggering an internal restart of Apache from the code monitoring script. This is also described in the documentation. | mod_wsgi force reload modules | [
"",
"python",
"module",
"mod-wsgi",
"reload",
""
] |
what is context object design pattern ? | A Context is a collection of data, often stored in a `Map` or in a custom class which acts as a struct with accessors and modifiers. It is used for maintaining state and for sharing information within a system. [See this PDF for an indepth description](https://www.dre.vanderbilt.edu/~schmidt/PDF/Context-Object-Pattern.pdf). Though it can be used for efficient and effective data sharing, you should note that many are wary of the `Context` pattern as [an anti-pattern](https://stackoverflow.com/questions/986865/can-you-explain-the-context-design-pattern-a-bit/986947#986947). | An example for it might be the HttpSession object: you have attributes which is basically a map with String keys and Object elements. This provides state information between http requests. Another example is the ServletRequest which provides state information between Servlets. | what is context object design pattern? | [
"",
"java",
"design-patterns",
""
] |
I catch the windows mouse movement events and calculate an relative mouse movement to send it to another pc. So far so good, works well.
But if I block the mouse movement on the screen that is sending the mouse coordinates (the client) or reach one side of the screen, there is a second mouse event fired by the windows api, that snaps the mouse back.
My first thought is to record the relative movements and ignore every "inverted" movement. But I'm looking for a better method.
First I call:
```
Cursor.Position = new Point(0, 0);
void HookManager_MouseMoveExt(object sender, MouseEventExtArgs e)
{
Logger.Log(String.Format("Pos: {0} {1} Delta: {2} {3}", e.X, e.Y, e.DeltaX, e.DeltaY), LogLevel.Info);
if (hasControl)
server.MouseMove(e.DeltaX, e.DeltaY, true); // send the coordinates to the client
e.Handled = true; // Don't move the mouse
}
```
Now I start the app and move the mouse to the upper left direction. I only want to receive only negative deltas, but this happens:
```
09.04.2009 00:29:31 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:31 <10> Pos: -1 0 Delta: -1 0
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 0 -1
09.04.2009 00:29:31 <10> Pos: 0 0 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 0 Delta: -1 0
09.04.2009 00:29:31 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:31 <10> Pos: -1 0 Delta: -1 0
09.04.2009 00:29:31 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: -1 0
09.04.2009 00:29:31 <10> Pos: -1 0 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: 0 0 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: -1 -1
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 0 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 0 -1
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -2 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 1 0 // Here it starts to snap back first time
09.04.2009 00:29:31 <10> Pos: -1 0 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 0 -1
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -2 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -2 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -2 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 -2 Delta: 1 0
09.04.2009 00:29:31 <10> Pos: -3 -1 Delta: 0 1
09.04.2009 00:29:31 <10> Pos: -2 -2 Delta: 1 0
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: 1 1
09.04.2009 00:29:31 <10> Pos: -3 -1 Delta: 0 0
09.04.2009 00:29:31 <10> Pos: -1 0 Delta: 2 0
09.04.2009 00:29:31 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:31 <10> Pos: -1 -1 Delta: -1 0
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: 0 0
09.04.2009 00:29:32 <10> Pos: 0 0 Delta: 0 0
09.04.2009 00:29:32 <10> Pos: -1 -1 Delta: -1 -1
09.04.2009 00:29:32 <10> Pos: -1 -1 Delta: 0 0
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: 0 0
09.04.2009 00:29:32 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: -1 0
09.04.2009 00:29:32 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: -1 0
09.04.2009 00:29:32 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:32 <10> Pos: -1 -1 Delta: -1 0
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: 0 0
09.04.2009 00:29:32 <10> Pos: -1 -1 Delta: 0 -1
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: 0 0
09.04.2009 00:29:32 <10> Pos: -2 -2 Delta: 0 -2
09.04.2009 00:29:32 <10> Pos: 0 0 Delta: 2 2
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: -1 0
09.04.2009 00:29:32 <10> Pos: 0 -1 Delta: 0 -1
09.04.2009 00:29:32 <10> Pos: -1 0 Delta: -1 0
09.04.2009 00:29:32 <10> Pos: -1 -1 Delta: 0 -1
09.04.2009 00:29:33 <10> Pos: -1 -1 Delta: 0 0
09.04.2009 00:29:36 <10> Pos: -1 -1 Delta: 0 0
09.04.2009 00:29:36 <10> Pos: -2 -2 Delta: 0 0
09.04.2009 00:29:36 <10> Pos: -5 -5 Delta: -3 -3
09.04.2009 00:29:36 <10> Pos: -5 -4 Delta: 0 1
09.04.2009 00:29:36 <10> Pos: -6 -6 Delta: -1 -2
09.04.2009 00:29:36 <10> Pos: -8 -7 Delta: -2 -1
09.04.2009 00:29:36 <10> Pos: -8 -7 Delta: 0 0
09.04.2009 00:29:36 <10> Pos: -14 -11 Delta: -6 -4
09.04.2009 00:29:36 <10> Pos: -20 -17 Delta: -6 -6
09.04.2009 00:29:36 <10> Pos: -26 -25 Delta: -6 -8
09.04.2009 00:29:36 <10> Pos: -33 -25 Delta: -7 0
09.04.2009 00:29:36 <10> Pos: -36 -31 Delta: -3 -6
09.04.2009 00:29:36 <10> Pos: -39 -31 Delta: -3 0
09.04.2009 00:29:36 <10> Pos: -38 -29 Delta: 1 2
09.04.2009 00:29:36 <10> Pos: -38 -24 Delta: 0 5
09.04.2009 00:29:36 <10> Pos: -33 -24 Delta: 5 0
09.04.2009 00:29:36 <10> Pos: -28 -21 Delta: 5 3
09.04.2009 00:29:36 <10> Pos: -27 -18 Delta: 1 3
09.04.2009 00:29:36 <10> Pos: -22 -16 Delta: 5 2
09.04.2009 00:29:36 <10> Pos: -19 -12 Delta: 3 4
09.04.2009 00:29:36 <10> Pos: -16 -11 Delta: 3 1
09.04.2009 00:29:36 <10> Pos: -14 -8 Delta: 2 3
09.04.2009 00:29:36 <10> Pos: -11 -8 Delta: 3 0
09.04.2009 00:29:36 <10> Pos: -8 -5 Delta: 3 3
09.04.2009 00:29:36 <10> Pos: -8 -5 Delta: 0 0
09.04.2009 00:29:36 <10> Pos: -4 -2 Delta: 4 3
09.04.2009 00:29:36 <10> Pos: -3 -3 Delta: 1 -1
09.04.2009 00:29:36 <10> Pos: -1 0 Delta: 2 3
``` | Got my solution, based on the box method.
MouseSimulator.Position just do:
```
Cursor.Position = new Point(value, Y);
```
HookManager\_MouseMoveExt is my callback. MouseEventExtArgs are just extended MouseEventArgs, added features like the deltas.
```
private bool ignoreNext = false;
void HookManager_MouseMoveExt(object sender, MouseEventExtArgs e)
{
// Should we block all mouse interactions?
if (Block) {
e.Handled = true;
return;
}
// Return if we should ignore the nex, because we made a big jump
if (ignoreNext) {
ignoreNext = false;
return;
}
if (hasControl)
{
// Lock the mouse to 100,100 : 200,200 and flip back to 150,150 if out of bounds
if (e.X < 100 || e.X > 200 || e.Y < 100 || e.Y > 200) // Box leaved
{
// If we leave the box, we set the position to the center
// and set the event to handled otherwise the mouse is free
MouseSimulator.Position = new System.Drawing.Point(150, 150);
e.Handled = true;
ignoreNext = true;
}
// We moved fine, send the delta to the server
// The MouseSimulator.Position change will not be visible yet.
server.MouseMove(e.DeltaX, e.DeltaY, true);
}
Logger.Log(String.Format("Pos: {0} {1} Delta: {2} {3}", e.X, e.Y, e.DeltaX, e.DeltaY), LogLevel.Info);
}
``` | I can't actually answer your question, but are you aware of the open-source program [Synergy](http://synergy2.sourceforge.net/)?
It does what you're trying to do - perhaps you could take a peek at the source for hints. | How to send relative mouse movement to another pc | [
"",
"c#",
"controls",
"mouse",
"hook",
""
] |
I am working on a merge sort function. I got the sort down - I am trying to get my merge part finished. Assume that I am learning C++, have cursory knowledge of pointers, and don't understand all the rules of std::vector::iterator's (or std::vector's, for that matter).
Assume that num is the size of the original std::vector that have copied (std::copy) values from an array of size "int ar[num]." Assume that farray has the values of (0 to (num / 2)) and sarray has the values of ((num / 2) to num).
```
int num = original.size();
std::vector<int> final(num);
for (std::vector<int>::iterator it = farray.begin(); it != farray.end(); ++it) {
for (std::vector<int>::iterator iter = sarray.begin(); iter != sarray.end(); ++iter) {
if (*it > *iter) final.push_back(*it);
else
final.push_back(*iter);
}
}
```
This code compiles and my latest stable build of Bloodshed Dev-C++ does not throw any warnings or errors. I don't know if this is valid, I still need to try and cout all the values of final. I just want to know if this is common, prone to errors, or just bad style. And, if so, how you would | It's valid... but a for loop probably isn't what you want. When you use two for loops, your inner loop keeps going back to the start every time the outer loop loops. So if your vectors contain:
```
farray: 10 9 8 4 3
sarray: 7 6 4 3 1
```
Then your final array will contain something like:
```
10 10 10 10 10 9 9 9 9 9 8 8 8 8 8 7 6 4 4 4 7 6 4 3 3
```
because you are testing every single combination, and adding the larger one to the final list. A better solution might be to remember an iterator for each list, and just use one loop. Rather than looping over a list, just go through both of them together - if sarray has the larger number, then increment your sarray iterator, and compare that with the old farray iterator. Stop your loop when both sarray and farray are empty.
```
vector<int> fiter = farray.begin();
vector<int> siter = sarray.begin();
vector<int> final;
// Let's traverse both farray and sarray.
// We'll want to stop this loop once we've traversed both lists.
while (fiter != farray.end() && siter != sarray.end())
{
if (fiter == farray.end())
{
// we must have gone right through farray -
// so use the value from sarray, and go to the next one
final.push_back(*siter);
siter++;
}
else if (siter == sarray.end())
{
// we must have gone right through sarray -
// so use the value from farray, and go to the next one
final.push_back(*fiter);
fiter++;
}
else if (*siter > *fiter)
{
// siter is the bigger of the two - add it to the final list, and
// go to the next sarray entry
final.push_back(*siter);
siter++;
}
else // *fiter >= *siter
{
// fiter is the bigger of the two - add it to the final list, and
// go to the next farray entry
final.push_back(*fiter);
fiter++;
}
}
```
I haven't tested it - and if this is for homework, then *please* try to understand what I've done, go away and write it yourself, rather than copy+paste. | Merge sort algorithm aside, nested for loop with iterator's is just as valid as nested for loops with two variables *i* and *j*. | Can you embed for loops (in each other) in C++ | [
"",
"c++",
"pointers",
"vector",
"loops",
"iterator",
""
] |
I have a variable `$params` which gets data from the database:
```
$params = mssql_fetch_array($result)
```
As far as I know, it is associative array. I want another array `$tempParams` to hold the value of this array. Can I assign it by using the following statement:
```
$tempParams = $params
```
In addition, do I need one single statement to declare and assign a value to $tempParams, or can these be separated?
One more question I would like to ask is that following statement is correct;
While $tempParams contains values;
```
$params['column1'] = $tempParams['newColumns']
``` | Yes,
```
$tempParams = $params;
```
Will copy all values from $params to $tempParams.
```
$params['foo'] = 'bar';
echo $tempParams['foo']; //nothing
$tempParams = $params;
echo $tempParams['foo']; //'bar'
$params['foo'] = 'hai';
echo $tempParams['foo']; //still: 'bar'
``` | As far as whether or not your array is associative, read the documentation on [mysql\_fetch\_array()](http://us.php.net/mysql_fetch_array)
As far as assignment goes, you actually can put it in one statement
```
$tempParams = $params = mysql_fetch_array( $result, MYSQL_ASSOC );
```
This simple test shows that when you do an assignment like this, both variables are separate copies and not references.
```
$a = $b = array( 1, 2, 3 );
$b[1] = 'x';
echo '<pre>';
print_r( $a );
print_r( $b );
echo '</pre>';
``` | Assign value from one associative array of php into another array | [
"",
"php",
"declaration",
"variable-assignment",
"associative-array",
""
] |
If you were to define some extension methods, properties in an assembly written in F#, and then use that assembly in C#, would you see the defined extensions in C#?
If so, that would be so cool. | ```
[<System.Runtime.CompilerServices.Extension>]
module Methods =
[<System.Runtime.CompilerServices.Extension>]
let Exists(opt : string option) =
match opt with
| Some _ -> true
| None -> false
```
This method could be used in C# only by adding the namespace (using using) to the file where it will be used.
```
if (p2.Description.Exists()) { ...}
```
[Here is a link to the original blogpost.](http://langexplr.blogspot.com/2008/06/using-f-option-types-in-c.html)
Answering question in comments "Extension Static Methods":
```
namespace ExtensionFSharp
module CollectionExtensions =
type System.Linq.Enumerable with
static member RangeChar(first:char, last:char) =
{first .. last}
```
In F# you call it like so:
```
open System.Linq
open ExtensionFSharp.CollectionExtensions
let rangeChar = Enumerable.RangeChar('a', 'z')
printfn "Contains %i items" rangeChar.CountItems
```
In C# you call it like so:
```
using System;
using System.Collections.Generic;
using ExtensionFSharp;
class Program
{
static void Main(string[] args)
{
var method = typeof (CollectionExtensions).GetMethod("Enumerable.RangeChar.2.static");
var rangeChar = (IEnumerable<char>) method.Invoke(null, new object[] {'a', 'z'});
foreach (var c in rangeChar)
{
Console.WriteLine(c);
}
}
}
```
Now, give me my freaking medal! | Despite my other answer, I did just try this with the F# CTP (on VS shell) and C# Express from my box at home (all free dev tools!), and this works:
F#
```
#light
namespace MyFSharp
// C# way
[<System.Runtime.CompilerServices.Extension>]
module ExtensionMethods =
[<System.Runtime.CompilerServices.Extension>]
let Great(s : System.String) = "Great"
// F# way
type System.String with
member this.Awesome() = "Awesome"
let example = "foo".Awesome()
```
C#
```
using System;
using MyFSharp; // reference the F# dll
class Program
{
static void Main(string[] args)
{
var s = "foo";
//s.Awesome(); // no
Console.WriteLine(s.Great()); // yes
}
}
```
I was not aware you could do this; nifty. Credit to @alex. | F# extension methods in C# | [
"",
"c#",
"f#",
"extension-methods",
""
] |
How to convert an equation into formulas for individual variables? I am thinking about a math equations like:
```
c^2 = a^2 + b^2
```
I would like to have a function that could process any formula, and give me the individual variable formulas. The above equation would produce the following:
```
a = (c^2 - b^2)^0.5
b = (c^2 - a^2)^0.5
c = (a^2 + b^2)^0.5
```
I would also like to start with:
```
a = (c^2 - b^2)^0.5
```
and output:
```
b = (c^2 - a^2)^0.5
c = (a^2 + b^2)^0.5
```
I have looked at expression trees, but I am having trouble visualizing how this will work. I would like a .NET (C#, VB.NET, or F#) solution. Any ideas?
Something like:
```
public string[] GetFormulas(string equation)
{
...
}
```
Thanks. | Symbolic equation solving is a complex problem and there is no closed solution for many equations. Writing your own [Computer Algebra System](http://en.wikipedia.org/wiki/Computer_algebra_system) is none trivial, but you may be able to write a program for simple equation.
You will have to build a expression tree of the input string and define transformation rules for manipulating the expression tree. To solve for a variable you might then perform a search (guided by good heuristics to keep the runtime acceptable) on the space of expression tree that can be derived from the orginal tree by multiple aplications of
transformation rules. | This is a non-trivial problem you're trying to solve... I don't think you'll have much luck trying to solve it on your own. Better to find some kind of third-party app or library that does it. There are a number of programs that can do the operation you're talking about, such as Matlab and Maple. Also, a TI-89 graphing calculator can do it. You may be able to get the algorithms you need from [Octave](http://www.gnu.org/software/octave/), which is essentially an open-source implementation of Matlab. | How to convert an equation into formulas for individual variables? | [
"",
"c#",
".net",
"math",
"logic",
"expression-trees",
""
] |
I am using LINQ to XML. I want to use an equivalent of sql's `<>` operator in the `where` clause below....
```
var myBooks = from book in xDoc.Descendants("BOOKOB")
where book.Element("AUTHOR").Value
```
Please help! | Isn't != working? | As others have said, you can use != perfectly easily - don't forget that even when you're using LINQ, you're writing C#, *not* SQL.
You need to provide a value for it not to be equal to, of course, along with a `select` clause:
```
var myBooks = from book in xDoc.Descendants("BOOKOB")
where book.Element("AUTHOR").Value != "Jeff Atwood"
select book;
```
For simple queries like this, I usually find "dot notation" simpler to read:
```
var myBooks = xDoc.Descendants("BOOKOB")
.Where(b => b.Element("AUTHOR").Value != "Jeff Atwood");
``` | LINQ to Xml not equal to operator | [
"",
"c#",
"xml",
"linq",
""
] |
In my windows application i have a usercontrol, which in turn host few other usercontrols.
Just before the end of the main user control's constructor, i try to create a thread... but it does not appear to be created:
```
mainUserControl()
{
var t=new Thread(ThreadJob);
t.IsBackground=true;
t.Start();
}
private void ThreadJob()
{
//Thread.Sleep(120000);
//if(txtStatus.InvokeRequired) {
// txtStatus.Invoke(new MethodInvoker(delegate { txtStatus.Text="Thread started"; }));
//}
txtStatus.Text="sample";
}
```
This code does not work: i take this as evidence that the thread is not spawned, as if it were then `txtStatus.Text="sample";` would have thrown an exception.... right?
So what's happening here? Why isn't my thread being created? | My guess is, since you took out your delay, the thread is spawning, setting the value, and shutting down.
Accessing `txtStatus.Text` from the wrong thread is not guaranteed to throw, though. There are situations where you can access a property on a control from a background thread and it will not throw. (You still shouldn't do it, though!)
If you still believe the thread is not starting, you could try setting a breakpoint there - I'm fairly certain you'll see that it's hitting that point. | It would not necessarily have thrown an exception. It might have, but then again it might have just failed to work. There's a reason why cross-thread UI access is discouraged: it's flaky and dangerous. Overall, not a good way to verify your program is set up the way you think it should be.
Use a breakpoint and a debugger... | My thread does not appear to have been created... any idea why? | [
"",
"c#",
"multithreading",
""
] |
I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files. | Is the function defined in the header file? So that the actual code is given directly in the function, like this:
```
static int addTwo(int x)
{
return x + 2;
}
```
Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.
Remember that `#include`:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.
**UPDATE**: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) [intrinsic functions](http://en.wikipedia.org/wiki/Intrinsic_function) can be expressed like the above, and with an explicit `inline` keyword even:
```
static inline int addTwo(int *x)
{
__add_two_superquickly(x);
}
```
Here, the `__add_two_superquickly()` function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.
The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used. | It will effectively create a separate static function with the same name inside every cpp file it is included into. The same applies to global variables. | C/C++: Static function in header file, what does it mean? | [
"",
"c++",
"c",
"function",
"static",
""
] |
So, in PHPDoc one can specify `@var` above the member variable declaration to hint at its type. Then an IDE, for ex. PHPEd, will know what type of object it's working with and will be able to provide a code insight for that variable.
```
<?php
class Test
{
/** @var SomeObj */
private $someObjInstance;
}
?>
```
This works great until I need to do the same to an array of objects to be able to get a proper hint when I iterate through those objects later on.
So, is there a way to declare a PHPDoc tag to specify that the member variable is an array of `SomeObj`s? `@var` array is not enough, and `@var array(SomeObj)` doesn't seem to be valid, for example. | **Use:**
```
/* @var $objs Test[] */
foreach ($objs as $obj) {
// Typehinting will occur after typing $obj->
}
```
when typehinting inline variables, and
```
class A {
/** @var Test[] */
private $items;
}
```
for class properties.
**Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:**
The best you can do is say,
```
foreach ($Objs as $Obj)
{
/* @var $Obj Test */
// You should be able to get hinting after the preceding line if you type $Obj->
}
```
I do that a lot in Zend Studio. Don't know about other editors, but it ought to work. | In the PhpStorm IDE from JetBrains, you can use `/** @var SomeObj[] */`, e.g.:
```
/**
* @return SomeObj[]
*/
function getSomeObjects() {...}
```
The [phpdoc documentation](https://docs.phpdoc.org/3.0/guide/references/phpdoc/types.html) recommends this method:
> specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.
>
> Example: `@return int[]` | PHPDoc type hinting for array of objects? | [
"",
"php",
"ide",
"phpdoc",
"var",
"hint",
""
] |
I need a java data structure/solution that meets these requirements. What best fits these?
1) Object's insertion order must be kept
2) Object's must be unique (These are database objects that are uniquely identified by a UUID).
3) If a newer object with the same ID is added, the older version of the object should be over-written/removed
4) The Solution should be accessible by many threads.
5) When the first object added to the Structure is read/used, it should be removed from the data structure | There are a couple of possibilities here. The simplest might be to start with a [LinkedHashSet](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashSet.html). That will provide you with the uniqueness and predictable ordering that you require. Then, you could wrap the resulting set to make it thread-safe:
```
Set<T> s = Collections.synchronizedSet(new LinkedHashSet<T>(...));
```
Note: Since a Set doesn't really define a method for retrieving items from it, your code would have to manually invoke Set.remove(Object).
Alternatively, you could wrap a [LinkedHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html), which does provide a hook for the delete-on-read semantics you require:
```
class DeleteOnReadMap<K, V> implements Map<K, V> {
private Map<K, V> m = new LinkedHashMap<K, V>();
// implement Map "read" methods Map with delete-on-read semantics
public V get(K key) {
// ...
}
// (other read methods here)
// implement remaining Map methods by forwarding to inner Map
public V put(K key, V value) {
return m.put(key, value);
}
// (remaining Map methods here)
}
```
Finally, wrap an instance of your custom Map to make it thread-safe:
```
Map<K, V> m = Collections.synchronizedMap(new DeleteOnReadMap<K, V>(...));
``` | My thought is something like the following:
```
Collections.synchronizedMap(new LinkedHashMap<K, V>());
```
I think that takes care of everything except requirement 5, but you can do that by using the `remove()` method instead of `get()`.
This won't be quite as efficient as a `ConcurrentMap` would be - synchronization locks the entire map on every access, but I think `ConncurrentMap` implementations can use read-write locks and selective locking on only part of the map to allow multiple non-conflicting accesses to go on simultaneously. If you wanted, you could probably get better performance by writing your own subclass of some existing `Map` implementation. | What Java Data Structure/Solution would best fit these requirements? | [
"",
"java",
"data-structures",
"collections",
"concurrency",
""
] |
I've spent hours searching for examples of how to use the bsddb module and the only ones that I've found are these ([from here](http://pybsddb.sourceforge.net/bsddb3.html)):
```
data = mydb.get(key)
if data:
doSomething(data)
#####################
rec = cursor.first()
while rec:
print rec
rec = cursor.next()
#####################
rec = mydb.set()
while rec:
key, val = rec
doSomething(key, val)
rec = mydb.next()
```
Does anyone know where I could find more (practical) examples of how to use this package?
Or would anyone mind sharing code that they've written themselves that used it?
**Edit:**
The reason I chose the Berkeley DB was because of its scalability. I'm working on a latent semantic analysis of about 2.2 Million web pages. My simple testing of 14 web pages generates around 500,000 records. So doing the math out... there will be about 78.6 Billion records in my table.
If anyone knows of another efficient, scalable database model that I can use python to access, please let me know about it! (*lt\_kije* has brought it to my attention that `bsddb` is deprecated in Python 2.6 and will be gone in 3.\*) | These days, most folks use the [anydbm](http://docs.python.org/library/anydbm.html) meta-module to interface with db-like databases. But the [API](http://docs.python.org/library/bsddb.html) is essentially dict-like; see [PyMOTW](http://www.doughellmann.com/PyMOTW/anydbm/) for some examples. Note that bsddb is deprecated in 2.6.1 and will be gone in 3.x. Switching to anydbm will make the upgrade easier; switching to sqlite (which is now in stdlib) will give you a much more flexible store. | Look at: Lib3/bsddb/test after downloading the source from <http://pypi.python.org/pypi/bsddb3/>
The current distribution contains the following tests that are very helpful to start working with bsddb3:
```
test_all.py
test_associate.py
test_basics.py
test_compare.py
test_compat.py
test_cursor_pget_bug.py
test_dbenv.py
test_dbobj.py
test_db.py
test_dbshelve.py
test_dbtables.py
test_distributed_transactions.py
test_early_close.py
test_fileid.py
test_get_none.py
test_join.py
test_lock.py
test_misc.py
test_pickle.py
test_queue.py
test_recno.py
test_replication.py
test_sequence.py
test_thread.py
``` | Where can I find examples of bsddb in use? | [
"",
"python",
"berkeley-db",
"bsddb",
""
] |
In WPF, **where can I put styles that should be applied throughout the application?**
This is because currently, whenever I use a style, I put it in the `<Window.Resources>` section of every window, which ofcourse is wrong in so many ways.
So where can I put these styles to apply throughout? | `<Application.Resources>` in your App.xaml | If you have many styles it could become bloated with Xaml if you put them all in application.resources. Another possibilty is to use resource dictionaries. [Here](http://blogs.msdn.com/wpfsdk/archive/2007/06/08/defining-and-using-shared-resources-in-a-custom-control-library.aspx) is more info about resource dictionaries and sharing multiple resource dictionaries. | WPF: Applying styles throught the application | [
"",
"c#",
"wpf",
"styles",
""
] |
I have a Parent Form that holds a "HUD" with First Name, Last Name, etc. One of the child forms is a Search Form. When the user selects a member from the results that are displayed in a DataGrid I want the pertinent information to fill in the HUD. I created a HUD class with variables for each value and a method called UpdateHUD(). I am unsure how to get this working. I have a reference to the Search Form of the Parent form containing the HUD, like so:
```
public frmWWCModuleHost _frmWWCModuleHost;
```
This is the code I use to embed forms. I am not using MDI.
```
public static void ShowFormInContainerControl(Control ctl, Form frm)
{
frm.TopLevel = false;
frm.FormBorderStyle = FormBorderStyle.None;
frm.Dock = DockStyle.Fill;
frm.Visible = true;
ctl.Controls.Add(frm);
}
```
Here is the code I am running on Cell Click on the Search Form. This is from before I tried implementing the HUD class.
```
private void dgvSearchResults_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
_frmWWCModuleHost = new frmWWCModuleHost();
_frmWWCModuleHost.tbxHUD_LastName.Text = dgvSearchResults.CurrentRow.Cells[1].FormattedValue.ToString();
_frmWWCModuleHost.tbxHUD_LastName.Invalidate();
_frmWWCModuleHost.FormPaint();
}
```
Thanks in advance!
~ Patrick
---
## EDIT
---
dgvSearchResults\_CellContentClick is now current. When I step through this code it is getting the correct Value here but it is never updating the actual HUD.
---
## EDIT 2
---
Is my problem that I am declaring a NEW frmWWCModuleHost instead of passing a ref to the existing? I am still pretty weak in my understanding of this.
---
## EDIT 3
---
I have "solved" this by doing the following: On the Parent Form where I declare the Child Form I pass *this* as a param. Then in the constructor of the child form I added \_frmWWCModuleHost = m\_parent; I have a UpdateHUD() method on my Parent form and I call it from the \_CellClick event on the child.
Now to rephrase my question; Is there anything glaringly wrong with doing it this way? | When the child form search completes, raise a "SearchCompleted" event. Then anything (including the parent form) can subscribe to that event and retrieve the details.
See the following NotepadCode for an example:
```
class ParentForm
{
private readonly ChildForm childForm;
public ParentForm()
{
InitializeComponent();
childForm = new ChildForm();
childForm.SearchCompleted += childForm_SearchCompleted;
}
private void childForm_SearchCompleted(object sender, SearchCompletedEventArgs e)
{
// Update the display
lblName.Text = e.DataToDisplay;
}
}
class ChildForm
{
public event EventHandler<SearchCompletedEventArgs> SearchCompleted;
private void Search(string query)
{
// Do the searching
OnSearchCompleted(new SearchCompletedEventArgs([arg values]));
}
public void OnSearchCompleted(SearchCompletedEventArgs args)
{
if (SearchCompleted != null)
{
SearchCompleted(this, args);
}
}
}
``` | Sometimes in situations like this I'll create a delegate that matches the signature of the method I want to call in the parent class (I think that would be UpdateHUD in your case), and then pass an instance of that delegate (i.e. a reference to UpdateHUD) to the child form (the search form in this case). When the child form is finished accepting input, it invokes the delegate using the data collected on the form.
So, say UpdateHUD is a method in the parent form that looks something like this.
```
private void UpdateHUD(string firstName, string lastName) {
//...
}
```
You would create a delegate with the same signature, like this.
```
public delegate void HUDUpdateHandler(string firstName, string lastName);
```
Then you would add a HUDUpdateHandler parameter to the constructor of the child form and store it in a private field (for example, `this.handler = handler`). When your child form is ready to send its data back, you would invoke the child form's private field (`this.handler.Invoke(firstNameTextBox.Text, lastNameTextBox.Text)`, for example). That will invoke UpdateHUD in your parent class using the values from the child class, and you won't have to expose anything.
I find this approach simpler to implement than raising and catching events, and it allows you to keep the internals of your parent class internal. | Sending Data from child form to Parent Form TextBox | [
"",
"c#",
"winforms",
".net-3.5",
""
] |
OK firstly, I added this line to my .htaccess file so the php engine parses php code in .xml file:
```
AddType application/x-httpd-php .php .php3 .phtml .html .xml
```
After that when I view an .xml file I get this PHP error:
**Parse error: parse error, unexpected T\_STRING in /var/www/vhosts/mydomain.com/httpdocs/test.xml on line 1**
But line 1 is not even php infact this is line 1:
```
<?xml version="1.0" encoding="utf-8"?>
```
Can anyone tell me what the problem is?
Thanks. | That's because `<?` is the short opening tag for php.
Try `<?php echo '<?xml version="1.0" encoding="utf-8"?>'; ?>` | Yeah, sad but true, it's the doctype being seen as the PHP opening short tag. You have a few options:
1. Take XML out of the list of files for PHP to parse in the .htaccess file
2. Wrap all of your xml declarations in PHP:
`<?php print('<?xml version="1.0" encoding="utf-8"?>'); ?>`
3. Turn off `short_open_tag` in .htaccess or the php.ini. This means that PHP will only accept **`<?php`** as an opening tag and will ignore **`<?`**. | PHP error in .xml file? | [
"",
"php",
"xml",
".htaccess",
""
] |
Below are two queries that return the same data. Other then style I am not sure which is better.
What factors influence these queries?
What are the benefits of using one style over the other?
Sample 1
```
var x = from s in db.Surveys
join sq in db.Survey_Questions on s.ID equals sq.Survey_ID
join q in db.Questions on sq.Question_ID equals q.ID
join qg in db.Question_Groups on q.ID equals qg.Question_ID
where s.Type_ID.Equals(typeID) & s.Type.Equals(type)
select new { question = sq.Question, status = sq.Status, grp = qg };
```
Sample 2
```
var x = db.Surveys.Where(s => s.Type_ID.Equals(typeID) & s.Type.Equals(type))
.Join(db.Survey_Questions,
s => s.ID,
sq => sq.Survey_ID,
(s, sq) => new
{
question = sq.Question,
status = sq.Status
})
.Join(db.Question_Groups,
q => q.question.ID,
qg => qg.Question_ID,
(q, qg) => new
{
question = q.question,
status = q.status,
group = qg
}).ToList();
``` | Update: You have fixed your title, so ignore the rant.
The title of your question has nothing to do with your code samples. Your question implies that one syntax is IEnumerable and the other is IQueryable, but this is incorrect. In your samples, if `db.Surveys` is an IQueryable, then *both* your samples are using IQueryable. I will try to answer *both* questions.
Your two code samples are just different ways of writing the same LINQ queries (assuming they are well-written). The code in sample 1 is just shorthand for the code in sample 2. The compiler treats the code in both samples the same way. Think of the way the C# compiler will treat `int?` the same as `Nullable<System.Int32>`. Both the C# and VB.Net languages provide this shorthand query syntax. Other languages might not have this syntax and you would have to use the sample 2 syntax. In fact, other languages might not even support extension methods or lambda expressions, and you would have to use an uglier syntax yet.
---
Update:
To take Sander's example further, when you write this (query comprehension syntax):
```
var surveyNames = from s in db.Surveys select s.Name
```
You *think* the compiler turns that shorthand into this (extension methods and lambda expression):
```
IQueryable<string> surveryNames = db.Surveys.Select(s => s.Name);
```
But actually extension methods and lambda expressions are shorthand themselves. The compilers emits something like this (not exactly, but just to give an idea):
```
Expression<Func<Survey, string>> selector = delegate(Survey s) { return s.Name; };
IQueryable<string> surveryNames = Queryable.Select(db.Surveys, selector);
```
Note that `Select()` is just a static method in the `Queryable` class. If your .NET language did not support query syntax, lambdas, or extension methods, that is kinda how you would have to write the code yourself.
---
> What are the benefits of using one style over the other?
For small queries, extension methods can be more compact:
```
var items = source.Where(s => s > 5);
```
Also, the extension method syntax can be more flexible, such as conditional where clauses:
```
var items = source.Where(s => s > 5);
if(smallerThanThen)
items = items.Where(s => s < 10);
if(even)
items = items.Where(s => (s % 2) == 0);
return items.OrderBy(s => s);
```
In addition, several methods are only available through extension method syntax (Count(), Aggregate(), Take(), Skip(), ToList(), ToArray(), etc), so if I'll use one of these, I'll usually write the whole query in this syntax to avoid mixing both syntaxes.
```
var floridaCount = source.Count(s => s.State == "FL");
var items = source
.Where(s => s > 5)
.Skip(5)
.Take(3)
.ToList();
```
On the other hand, when a query gets bigger and more complex, query comprehension syntax can be clearer, especially once you start complicating with a few `let`, `group`, `join`, etc.
In the end I will usually use whichever works better for each specific query.
---
Update: you fixed your title, so ignore the rest...
Now, about your title: With respect to LINQ, IEnumerable and IQueryable are very similar. They both have pretty much the same extension methods (Select, Where, Count, etc), with the main (only?) difference being that IEnumerable takes `Func<TIn,TOut>` as paremeters and IQueryable takes `Expression<Func<TIn,TOut>>` as parameters. You express both the same way (usually lamba expressions), but internally they are completely different.
IEnumerable is the doorway to LINQ to Objects. The LINQ to Objects extension methods can be called on any IEnumerable (arrays, lists, anything you can iterate with `foreach`) and the `Func<TIn,TOut>` is converted to IL at compile time and runs like a normal method code at run time. Note that some other LINQ providers use IEnumerable and so are actually using LINQ to Objects behind the scenes (LINQ to XML, LINQ to DataSet).
IQueryable is used by LINQ to SQL, LINQ to Entities, and other LINQ providers which need to examine your query and translate it instead of executing your code directly. IQueryable queries and their `Expression<Func<TIn,TOut>>`s are not compiled into IL at compile time. Instead an *expression tree* is created and can be examined at run time. This allows the statements to be translated into other query languages (for example T-SQL). An expression tree can be compiled into a Func<TIn,TOut> at run time and executed if desired.
An example that illustrates the difference can be found in [this question](https://stackoverflow.com/questions/695678/performing-part-of-a-iqueryable-query-and-deferring-the-rest-to-linq-for-objects/696014#696014) where the OP wants to do part of a LINQ to SQL query in SQL Server, bring the objects into managed code, and do the rest of the query in LINQ to Objects. To achieve this all he has to do is cast the IQueryable into an IEnumerable where he wants the switch to happen. | LINQ is buzz word for a technology.
IQueryable is a .NET Interface which is used by LINQ.
Other than the style, there is no difference between the two. Use whichever style you prefer.
I prefer the first style for long statement (like that one shown here) and the second for very short statements. | What is the difference between LINQ query expressions and extension methods | [
"",
"c#",
"linq",
"query-expressions",
""
] |
I'm trying to find an elegant OOP solution for the following problem.
Assume we have a collection of POJOS, events in this case, where each POJO is possibly different class. We need to process this collection, using different rules for each POJO class (or type).
A basic assumption is that we can't decorate the POJOs with appropriate handlers, since we don't control their generation, and receive the collection as is. Thus, any mechanism for this falls into the same trap. However, item 3 stil deals with this possibility.
There are some possible solutions, some very ugly, some more elegant but complicated:
1. The obvious solution, and the ugliest, is using instanceOf operators to pass POJO to handler.
2. A slightly better modification of 1, is to use a chain of responsibility for this, with chained dispatcher, so that new types just need a new dispatcher. However, each dispatcher stills needs instanceOf.
3. Create enhanced objects, not POJOS, where each object holds a reference to its handler. This creates a coupling between POJO and our processor.
4. Create (I know how to do this correctly in Java) a dispatcher service which registers handlers to the specific event class, and use generics (Typesafe container, as in effective java) to dispatch event to handler.
4 is the most elegant, but I was wondering if there are any better ideas. | Simplification of #4:
Use a Map to store the handler for each event class.
```
Map<Class, Handler> classHandlers = new HashMap<Class, Handler>();
classHandlers.put(EventA.class, new EventAHandler());
classHandlers.put(EventB.class, new EventBHandler());
```
Now use the class of the event to get the handler for the event.
```
Handler handler = classHandlers.get(event.getClass());
handler.handle(event);
```
Of course this requires knowledge of all possible event classes at coding time and is thus less flexible than an external event dispatcher. | > Assume we have a collection of POJOS, events in this case, where each POJO is possibly different class. We need to process this collection, using different rules for each POJO class (or type).
Congratulations If the classes of POJOs are stable (new *class types* aren't often added) you've just described the motivation for using the Visitor Pattern!
Even better, because you *probably* want to do different things to your collection of POJOs, you can create an AbstractBaseVisitor and extend it to handle the different things you need to do!
This will require putting a tiny wrapper around each POJO, with one wrapper class per POJO class, to add a `visit()` function that calls back to the Visitor. | Handling collections with mixed POJOS, with different handler for each POJO | [
"",
"java",
"language-agnostic",
"design-patterns",
""
] |
I have a table (readings) already connected by ODBC in Access that opens very quickly when I click on it.
However, when I try to run this in VBA I it locks up and never displays anything:
```
Dim strSql As String
strSql = "SELECT readings.ids " & _
"INTO ids_temp " & _
"FROM readings " & _
"WHERE readings.ids > 1234;" //This is id in middle of list
DoCmd.SetWarnings False
DoCmd.RunSQL strSql
DoCmd.SetWarnings True
```
For some reason this crashes the whole system. Any ideas? | So the error was actually my fault the id I was using was causing the Query to return about 6 million results. But, this method actually works great, I just create the table and link a list box on a different form to the table, then I just show the form. I do some closes and updates in between but overall it seems to work well. Thanks for the help | Does you Database have ids\_temp table locally? If ids\_temp table is Linked table it will delete the table, because select into CREATES NEW TABLE. If you want to add to table try INSERT INTO command. You can clean table before inserting the data. | Run Query Against ODBC Connected Table VBA | [
"",
"sql",
"ms-access",
"vba",
"odbc",
""
] |
I'm getting this error when dealing with a number of classes including each other:
```
error: expected class-name before '{' token
```
I see what is going on, but I do not know how to properly correct it. Here is an abstracted version of the code:
*A.h*
```
#ifndef A_H_
#define A_H_
#include "K.h"
class A
{
public:
A();
};
#endif /*A_H_*/
```
*A.cpp*
```
#include "A.h"
A::A() {}
```
*B.h*
```
#ifndef B_H_
#define B_H_
#include "A.h"
class B : public A
{ // error: expected class-name before '{' token
public:
B();
};
#endif /*B_H_*/
```
*B.cpp*
```
#include "B.h"
B::B() : A() {}
```
*J.h*
```
#ifndef J_H_
#define J_H_
#include "B.h"
class J
{
public:
J();
};
#endif /*J_H_*/
```
*J.cpp*
```
#include "J.h"
J::J() {}
```
*K.h*
```
#ifndef K_H_
#define K_H_
#include "J.h"
class K : public J
{ // error: expected class-name before '{' token
public:
K();
};
#endif /*K_H_*/
```
*K.cpp*
```
#include "K.h"
K::K() : J() {}
```
*main.cpp*
```
#include "A.h"
int main()
{
return 0;
}
```
---
Starting in *main.cpp*, I can determine that this is what the compiler sees:
```
#include "A.h"
#ifndef A_H_
#define A_H_
#include "K.h"
#ifndef K_H_
#define K_H_
#include "J.h"
#ifndef J_H_
#define J_H_
#include "B.h"
#ifndef B_H_
#define B_H_
#include "A.h"
class B : public A
{ // error: expected class-name before '{' token
```
So, *A*'s definition is not complete when we get to *B*. I've been told that sometimes you need to use a forward declaration and then move the *#include* statement into the *.cpp* file, but I'm not having any luck with that. If I try anything like that, I simply get the additional error:
```
error: forward declaration of 'struct ClassName'
```
I think maybe I'm just not doing things in the right places. Can someone please show me how to get this code to compile? Thank you very much!
---
Edit: I want to point out that this is just abstracted version of the real code. I realize that there are no references to *K* in *A* or *B* in *J*, but there are in the real code and I feel that they're completely necessary. Perhaps if I give a brief description of the real classes, someone can help me restructure or fix my code.
Class *A* is an abstract node class that acts as an interface for nodes in a graph. Class *B* is one of what will be a number of different implementations of *A*. In the same manner, class *J* is an abstract Visitor class and *K* is the corresponding implementation. Here is the code with a little more context:
*A.h* (Abstract Node)
```
#ifndef A_H_
#define A_H_
#include "K.h"
class K;
class A
{
public:
A();
virtual void accept(const K&) const = 0;
};
#endif /*A_H_*/
```
*A.cpp*
```
#include "A.h"
A::A() {}
```
*B.h* (Concrete Node)
```
#ifndef B_H_
#define B_H_
#include "A.h"
class K;
class B : public A
{ // error: expected class-name before '{' token
public:
B();
virtual void accept(const K&) const;
};
#endif /*B_H_*/
```
*B.cpp*
```
#include "B.h"
B::B() : A() {}
void B::accept(const K& k) const { k.visit(this); }
```
*J.h* (Abstract Visitor)
```
#ifndef J_H_
#define J_H_
#include "B.h"
class B;
class J
{
public:
J();
virtual void visit(const B*) const = 0;
};
#endif /*J_H_*/
```
*J.cpp*
```
#include "J.h"
J::J() {}
```
*K.h* (Concrete Visitor)
```
#ifndef K_H_
#define K_H_
#include "J.h"
class B;
class K : public J
{ // error: expected class-name before '{' token
public:
K();
virtual void visit(const B*) const;
};
#endif /*K_H_*/
```
*K.cpp*
```
#include "K.h"
K::K() : J() {}
void K::visit(const B*) const {};
```
*main.cpp*
```
#include "A.h"
int main()
{
return 0;
}
```
I had to add some forward declarations to make some additional errors that appeared (when I added detail) go away. Some of them may not be necessary or correct. | Circular inclusions do not work.
Try to keep inclusions to a strict minimum. If you do that, you'll either be fine altogether, or you'll discover problems in your design. In your case, i don't see anything wrong with your design.
When defining class K, you're only using a pointer to an object of type B. That does not require B to be defined (as in "include the header file"), only to be declared (forward declaration is fine). So, in your case, removing inclusion to header "B.h" replaced by "class B;" is sufficient. (the same goes for class J) | Your header inclusions are circular. A -> K -> J -> B -> A. Using forward declarations is the simplest way to avoid such complexity, but it is only possible when the class being declared only uses references or pointers to the class being included. You can't use forward declaration in K.h or B.h, for example, because they inherit from J and A respectively. However, you may be able to replace the `#include "K.h"` in A.h with `class K;` depending on how you are actually using `K` in `A`.
Talk about confusing. | C++ Tricky Inheritance Class Definition Problem | [
"",
"c++",
"inheritance",
"forward-declaration",
""
] |
In C++, in which way can the stack get corrupted? One way I guess is to overwrite the stack variables by accessing an array beyond its boundaries. Is there any other way that it can get corrupted? | 1. You could have a random/undefined pointer that ends up pointing to the stack, and write though that.
2. An assembly function could incorrectly setup/modify/restore the stack
3. Cosmic waves could flips bits in the stack.
4. Radioactive elements in the chip's casing could flip bits.
5. Anything in the kernel could go wrong and accidentally change your stack memory.
But those are not particular to C++, which doesn't have any idea of the stack. | Violations of the One Definition Rule can lead to stack corruption. The following example looks stupid, but I've seen it a couple of times with different libraries compiled in different configurations.
## header.h
```
struct MyStruct
{
int val;
#ifdef LARGEMYSTRUCT
char padding[16];
#endif
}
```
## file1.cpp
```
#define LARGEMYSTRUCT
#include "header.h"
//Here it looks like MyStruct is 20 bytes in size
void func(MyStruct s)
{
memset(s.padding, 0, 16); //corrupts the stack as below file2.cpp does not have LARGEMYSTRUCT declared and declares Mystruct with 4 bytes
return; //Will probably crash here as the return pointer has been overwritten
}
```
## file2.cpp
```
#include "header.h"
//Here it looks like MyStruct is only 4 bytes in size.
extern void func(MyStruct s);
void caller()
{
MyStruct s;
func(s); //push four bytes on to the stack
}
``` | Stack corruption in C++ | [
"",
"c++",
"stack",
"corruption",
""
] |
How to get all element parents using jquery? i want to save these parents in a variable so i can use later as a selector.
such as `<div><a><img id="myImg"/></a></div>`
GetParents('myImg'); will return "div a" something like that | /// Get an array of all the elements parents:
```
allParents = $("#myElement").parents("*")
```
/// Get the nested selector through an element's parents:
```
function GetParents(id) {
var parents = $("#" + id).parents("*");
var selector = "";
for (var i = parents.length-1; i >= 0; i--) {
selector += parents[i].tagName + " ";
}
selector += "#" + id;
return selector;
}
```
GetParents('myImage') will return your nested selector: HTML BODY DIV A #myImage
## Note sure why you'd want this but its reuseable as a selector. | You don't need to grab their selectors, as you can use them directly with jQuery afterwards.
If you want to use all parents later, you can do something like:
```
var parents = $("#element").parents();
for(var i = 0; i < parents.length; i++){
$(parents[i]).dosomething();
}
``` | How to get all element parents using jquery? | [
"",
"javascript",
"jquery",
"html",
"dom",
""
] |
```
some_view?param1=10¶m2=20
def some_view(request, param1, param2):
```
Is such possible in Django? | You could always write a decorator. Eg. something like (untested):
```
def map_params(func):
def decorated(request):
return func(request, **request.GET)
return decorated
@map_params
def some_view(request, param1, param2):
...
``` | I'm not sure it's possible to get it to pass them as *arguments* to the view function, but why can't you access the `GET` variables from `request.GET`? Given that URL, Django would have `request.GET['param1']` be 10 and `request.GET['param2']` be 20. Otherwise, you'd have to come up with some kind of weird regular expression to try and do what you want. | Auto GET to argument of view | [
"",
"python",
"django",
"django-urls",
"django-views",
""
] |
What is functional testing? How is this different from unit testing and integration testing? | Another way of thinking is this:
Unit Test:
Test your code as units, calling methods and verifying return values and object property states/values
Functional Testing:
Testing your code paths while preforming a task. This ensures your application does what your code says it does.
Integral Testing? Do you mean Integration Testing?
Integration Testing:
Testing your code by plugging it into a larger mass to ensure you haven't broken existing logic and you are able to integrate back into the main branch. | Functional testing is making sure that customer requirements are implemented in the final product as specified in the spec.
Unit testing is to check that small portions of code behave as intended.
Integration testing is making sure that the system is stable when you combine all the different parts/modules together.
For example, BigBank Corporation wants a software that generates customer bank statements and inserts 3 random fees each month for each customer.
The Program Manager writes the software functional specification after several discussions with BigBank's representatives.
A developer writes a module that fills up a template statement from a database. He performs unit testing to check that most cases are covered (typical customer, no data for the month, etc.)
Another developer creates a random number generator module. He performs unit testing on that.
The integrator takes the two modules, compiles them and performs integration testing to ensure that they work well together.
Finally, in order to deliver a beta version for BigBank to try, the Test team performs functional testing to validate that the software complies with the functional specs. | What is functional testing? | [
"",
"c#",
"unit-testing",
"testing",
"terminology",
""
] |
Over the past year, I've heard an increasing amount of hype regarding the Scala language. I know that there are several existing projects that have plans to integrate Scala support with IDEs; however, it isn't always clear how good the integration really is.
Do they currently support Intellisense as well as Eclipse and Netbeans do for the Java language? Do they support instant verification as well? | I can't personally speak to the stability of the IntelliJ or NetBeans plugins (though I have heard good things), but the Scala IDE for Eclipse just recently made a new release with Scala 2.7.4. Architecturally, this release is quite different from the previous ones in that it uses Equinox Aspects, the officially supported mechanism for extending JDT (and other cross-plugin extensions). Whereas before the Scala plugin had to literally hack into the JDT internals using private APIs and reflection to trick the system into behaving properly, now it is able to simply declare its extension points and let the system do the rest. It's hard to even describe how much more stable this makes things. I'm not saying that it's all sunshine and roses yet, but if you've tried and rejected the plugin in the past (as I had), it's time to give it another look.
As for how it stacks up feature-wise, SDT doesn't have any refactoring support (IntelliJ has some basic stuff like "Rename"), nor does the editor do some things like "Mark Occurrences". However, it has a significantly better Outline than NetBeans, better compiler support than IDEA, and very good semantic highlighting. All three plugins support content assist (or "intellisense", as Microsoft calls it), but none of them are particularly reliable in this area just yet. The Scala IDE for Eclipse is the only one to support incremental compilation (alla Eclipse's Java tooling).
My advice: shop around. Try all three and see which one works the best for you. From what I've been hearing, the Scala IDE for Eclipse has leap-frogged the competition with its latest release, but the others have shown such consistent stability and steady advancement that you can't count them out just yet. | Here's a similar question:
[Which is the best IDE for Scala development?](https://stackoverflow.com/questions/419207/which-is-the-best-ide-for-scala-development)
In my very short experience with the [Scala IDE for Eclipse](http://www.scala-lang.org/node/94) and the [Scala Plugin for Netbeans](http://wiki.netbeans.org/Scala), it seemed like the Netbeans plug-in was a little more solid than the Eclipse one.
With the Scala IDE for Eclipse I was having problems with running a Hello World-type Scala object, and sometimes the syntax highlighting would start acting up. Then, I tried out the Netbeans plug-in, and it seemed to be more functional than the Eclipse one.
I haven't used either Scala IDE plug-in much in-depth, so I can't speak out of a lot of experience, but just from my initial impression, the Netbeans plug-in seemed a little bit more stable than the Eclipse one. | What is the current state of tooling for Scala? | [
"",
"java",
"ide",
"scala",
"intellisense",
""
] |
I need to be able to invoke arbitrary C# functions from C++. *[In-process Interoperability](http://www.infoq.com/articles/in-process-java-net-integration)* suggests using ICLRRuntimeHost::ExecuteInDefaultAppDomain(), but this only allows me to invoke methods having this format: `int method(string arg)`
What is the best way to invoke arbitrary C# functions? | Compile your C++ code with the **/clr** flag. With that, you can call into any .NET code with relative ease.
For example:
```
#include <tchar.h>
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
System::DateTime now = System::DateTime::Now;
printf("%d:%d:%d\n", now.Hour, now.Minute, now.Second);
return 0;
}
```
Does this count as "C++"? Well, it's obviously not *Standard C++* ... | There are several ways for a C++ application to invoke functions in a C# DLL.
1. Using C++/CLI as an intermediate DLL
* <http://blogs.microsoft.co.il/sasha/2008/02/16/net-to-c-bridge/>
2. Reverse P/Invoke
* <http://tigerang.blogspot.ca/2008/09/reverse-pinvoke.html>
* <http://blogs.msdn.com/b/junfeng/archive/2008/01/28/reverse-p-invoke-and-exception.aspx>
3. Using COM
* <http://msdn.microsoft.com/en-us/library/zsfww439.aspx>
4. Using CLR Hosting (`ICLRRuntimeHost::ExecuteInDefaultAppDomain()`)
* <http://msdn.microsoft.com/en-us/library/dd380850%28v=vs.110%29.aspx>
* <http://msdn.microsoft.com/en-us/library/ms164411%28v=vs.110%29.aspx>
* <https://stackoverflow.com/a/4283104/184528>
5. Interprocess communication (IPC)
* [How to remote invoke another process method from C# application](https://stackoverflow.com/q/19999049/184528)
* <http://www.codeproject.com/Tips/420582/Inter-Process-Communication-between-Csharp-and-Cpl>
6. Edit: Host a HTTP server and invoke via HTTP verbs (e.g. a REST style API) | Calling C# code from C++, but ExecuteInDefaultAppDomain() is too limited | [
"",
"c#",
"c++-cli",
"interop",
""
] |
If I have a credit number that is an int and I just want to display the last 4 numbers with a \* on the left, how would I do this in C#?
For example, 4838382023831234 would shown as \*1234 | ```
// assumes that ccNumber is actually a string
string hidden = "*" + ccNumber.Substring(ccNumber.Length - 4);
``` | If it's an integer type?
Where i is the int
```
string maskedNumber = string.Format("*{0}", i % 10000)
```
This will get the modulus of 10,000 which will return the last four digits of the int | How to show only part of an int in c# (like cutting off a part of a credit card number) | [
"",
"c#",
""
] |
Ok,
I have a string in a sql table like this
```
hello /r/n this is a test /r/n new line.
```
When i retrieve this string using c# for a textbox using multiline i expect the escape chars to be newlines.
But they are not and what happens is i get the line exactly as it is above.
It seems that the string returned from the table is taken as literal but i want the newlines!
How do i get this to work?
Thanks in advance.. | Things like "\n" (not "/n" by the way) are escape characters in *programming languages*, not inherently in text. (In particular, they're programming-language dependent.)
If you want to make
```
hello\r\nthis is a test\r\nnew line
```
format as
```
hello
this is a test
new line
```
you'll need to do the parsing yourself, replacing "\r" with carriage return, "\n" with newline etc, handling "\" as a literal backslash etc. I've typically found that a simple parser which just remembers whether or not the previous character was a backslash is good enough for most purposes. Something like this:
```
static string Unescape(string text)
{
StringBuilder builder = new StringBuilder(text.Length);
bool escaping = false;
foreach (char c in text)
{
if (escaping)
{
// We're not handling \uxxxx etc
escaping = false;
switch(c)
{
case 'r': builder.Append('\r'); break;
case 'n': builder.Append('\n'); break;
case 't': builder.Append('\t'); break;
case '\\': builder.Append('\\'); break;
default:
throw new ArgumentException("Unhandled escape: " + c);
}
}
else
{
if (c == '\\')
{
escaping = true;
}
else
{
builder.Append(c);
}
}
}
if (escaping)
{
throw new ArgumentException("Unterminated escape sequence");
}
return builder.ToString();
}
```
There are more efficient ways of doing it (skipping from backslash to backslash and appending whole substrings of non-escaped text, basically) but this is simple. | / is not the escape character, \ is. What you need is:
hello \r\n this is a test \r\n new line. | c# returning a string from sql 2005 | [
"",
"c#",
"string",
""
] |
Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off? | You could use Python 3.0.. The default string type is unicode, so the `u''` prefix is no longer required..
In short, no. You cannot turn this off.
The `u` comes from the `unicode.__repr__` method, which is used to display stuff in REPL:
```
>>> print repr(unicode('a'))
u'a'
>>> unicode('a')
u'a'
```
If I'm not mistaken, you cannot override this without recompiling Python.
The simplest way around this is to simply print the string..
```
>>> print unicode('a')
a
```
If you use the `unicode()` builtin to construct all your strings, you could do something like..
```
>>> class unicode(unicode):
... def __repr__(self):
... return __builtins__.unicode.__repr__(self).lstrip("u")
...
>>> unicode('a')
a
```
..but don't do that, it's horrible | I had a case where I needed drop the u prefix because I was setting up some javascript with python as part of an html template. A simple output left the u prefix in for the dict keys e.g.
```
var turns = [{u'armies':2...];
```
which breaks javascript.
In order to get the output javascript needed, I used the json python module to encode the string for me:
```
turns = json.dumps(turns)
```
This does the trick in my particular case and as the keys are all ascii there is no worry about the encoding. You could probably use this trick for your debug output. | Suppress the u'prefix indicating unicode' in python strings | [
"",
"python",
"string",
"unicode",
"printing",
""
] |
I need a structure to hold a value based on a key that has a range.
My implementation is C++, so any STL or Boost would be excellent.
I have as range-key, which are doubles, and value
* [0,2) -> value1
* [2,5) -> value2
* [5,10) -> value3
* etc
Such that a search of 1.23 should return value1, and so on.
Right now I am using a vector containing all three parts, key1/key2/value, with custom searching, but it feels like there should be a cleaner structure.
Edit: Thanks all. Given the ranges in this case are supposed to be contiguous and non-overlapping, the use of upper\_bound will work just fine. Thanks for the class Range solutions as well, they are filed away for future reference. | If your ranges are contiguous and non-overlapping, you should use std::map and the upper\_bound member function. Or, you could use a sorted vector with the upper\_bound algorithm. Either way, you only need to record the lowest value of the range, with the upper part of the range being defined by the next higher value.
Edit: I phrased that confusingly, so I decided to provide an example. In coding the example, I realized you need upper\_bound instead of lower\_bound. I always get those two confused.
```
typedef std::map<double, double> MyMap;
MyMap lookup;
lookup.insert(std::make_pair(0.0, dummy_value));
lookup.insert(std::make_pair(2.0, value1));
lookup.insert(std::make_pair(5.0, value2));
lookup.insert(std::make_pair(10.0, value3));
MyMap::iterator p = lookup.upper_bound(1.23);
if (p == lookup.begin() || p == lookup.end())
...; // out of bounds
assert(p->second == value1);
``` | ```
class Range
{
public:
Range( double a, double b ):
a_(a), b_(b){}
bool operator < ( const Range& rhs ) const
{
return a_ < rhs.a_ && b_ < rhs.b_;
}
private:
double a_;
double b_;
};
int main()
{
typedef std::map<Range, double> Ranges;
Ranges r;
r[ Range(0, 2) ] = 1;
r[ Range(2, 5) ] = 2;
r[ Range(5, 10) ] = 3;
Ranges::const_iterator it1 = r.find( Range( 2, 2 ) );
std::cout << it1->second;
Ranges::const_iterator it2 = r.find( Range( 2, 3 ) );
std::cout << it2->second;
Ranges::const_iterator it3 = r.find( Range( 6, 6 ) );
std::cout << it3->second;
return 0;
}
``` | Structure to hold value by ranged key | [
"",
"c++",
"stl",
""
] |
I wonder how weak references work internally, for example in .NET or in Java. My two general ideas are:
1. "Intrusive" - to add list of weak references to the most top class (object class). Then, when an object is destroyed, all the weak references can be iterated and set to null.
2. "Non-intrusive" - to maintain a hashtable of objects' pointers to lists of weak references. When a weak reference A is created to an object B, there would be an entry in the hashtable modified or created, whose key would be the pointer to B.
3. "Dirty" - to store a special hash-value with each object, which would be zeroed when the object is destroyed. Weak references would copy that hash-value and would compare it with the object's value to check if the object is alive. This would however cause access violation errors, when used directly, so there would need to be an additional object with that hash-value, I think.
Either of these solutions seems clean nor efficient. Does anyone know how it is actually done? | Not sure I understood your question, but you can have a look at the implementation for the class WeakReference and its superclass Reference in Java. It is well commented and you can see it has a field treated specially by the GC and another one used directly by the VM. | In .NET, when a `WeakReference` is created, the GC is asked for a handle/opaque token representing the reference. Then, when needed, `WeakReference` uses this handle to ask the GC if that handle is still valid (i.e. the original object still exists) - and if so, it can get the actual object reference.
So this is building a list of tokens/handles against object addresses (and presumably maintaining that list during defragmentation etc)
I'm not sure I 100% understand the three bullets, so I hesitate to guess which (if any) that is closest to. | How are weak references implemented? | [
"",
"java",
".net",
"weak-references",
"internals",
""
] |
as you all know update panel send the same response to server as a full post back ( or maybe i am understanding wrong), it is true that it is much better than a full post back.
so is there an alternative to send only response data ? like you have a method that ill return date, i think this is the only thing that should be sent and not the whole control view state that is going to show it ( again maybe i understood it wrong).
i am using Telerik AJAX controls, and they are built upon Microsoft AJAX so there is not much of improvement there.
one approach i like is <http://www.coolite.com/> they have AJAX Methods and events, which i think is what i am looking for, but the project is moving slowly and does not have flexibilities for my requirements.
so any input is highly appreciated. | This is why I encourage programmers new to AJAX to [learn the basics before adopting a library](https://stackoverflow.com/questions/215589/should-i-avoid-using-a-javascript-library-while-learning-how-to-write-ajax-client) - when you understand what's actually happening, this sort of optimization becomes obvious.
> so is there an alternative to send only response data? Like, you have a method that will return only a date?
Yes. The most basic way is to just write the date string to the response stream and end the response before anything else is sent - HTTP Handlers (ashx) work great for this. For a more ASP.NET AJAX-friendly technique, check out Web Methods. | If you want more control, one technique is to use JQuery and AJAX Client Library for ADO.NET Data Services to bind JSON data on the client side.
Check this sample [here](http://www.hanselman.com/blog/jQuerytoshipwithASPNETMVCandVisualStudio.aspx). This is a good example of JQuery complementing ASP.Net AJAX.
*First, I'm retrieving data from SQL Server and I need it in JSON format. I'm using the AJAX Client Library for ADO.NET Data Services to make a REST (GET) query to the back-end. To start with I'll just get the data...I include "datatable.js" as a client-side script and use Sys.Data.DataService() to make an async query. In JavaScript you can tell it's a Microsoft type if it's got "Sys." front of it. All the client support for ADO.NET Data Services is in datatable.js.* | A pro alternative to microsoft AJAX Update panel? | [
"",
"c#",
"asp.net",
"ajax",
""
] |
How can I format a number to a fixed number of decimal places (keep trailing zeroes) where the number of places is specified by a variable?
e.g.
```
int x = 3;
Console.WriteLine(Math.Round(1.2345M, x)); // 1.234 (good)
Console.WriteLine(Math.Round(1M, x)); // 1 (would like 1.000)
Console.WriteLine(Math.Round(1.2M, x)); // 1.2 (would like 1.200)
```
Note that since I want to control the number of places programatically, this string.Format won't work (surely I ought not generate the format string):
```
Console.WriteLine(
string.Format("{0:0.000}", 1.2M)); // 1.200 (good)
```
Should I just include Microsoft.VisualBasic and use [FormatNumber](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber(VS.80).aspx)?
I'm hopefully missing something obvious here. | Try
```
decimal x = 32.0040M;
string value = x.ToString("N" + 3 /* decimal places */); // 32.004
string value = x.ToString("N" + 2 /* decimal places */); // 32.00
// etc.
```
Hope this works for you. See
<http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx>
for more information. If you find the appending a little hacky try:
```
public static string ToRoundedString(this decimal d, int decimalPlaces) {
return d.ToString("N" + decimalPlaces);
}
```
Then you can just call
```
decimal x = 32.0123M;
string value = x.ToRoundedString(3); // 32.012;
``` | Try this to dynamically create your own format string without having to use multiple steps.
```
Console.WriteLine(string.Format(string.Format("{{0:0.{0}}}", new string('0', iPlaces)), dValue))
```
In steps
```
//Set the value to be shown
decimal dValue = 1.7733222345678M;
//Create number of decimal places
int iPlaces = 6;
//Create a custom format using the correct number of decimal places
string sFormat = string.Format("{{0:0.{0}}}", new string('0', iPlaces));
//Set the resultant string
string sResult = string.Format(sFormat, dValue);
``` | How do I format a Decimal to a programatically controlled number of decimals in c#? | [
"",
"c#",
"string",
"formatting",
""
] |
I need to replace a button on my web page with a hyperlink.
I am calling a PHP script using the button.
I extract the id using the following statement:
```
$id = $_POST['id'];
```
HTML code:
```
<form id="test1" method="post" action="my.php?action=show">
<input type="hidden" name="id" id="id" value="1" />
<input type="submit" name="submit" value="Click" onclick="return display(1);" />
</form>
```
Here is what I came up with:
```
<a href="my.php?action=show&id='1'" onclick="return display(1);"> Click</a>
```
Does my code have a flaw? Is there a better approach? | Looks good, except for three things:
1. Use `&` instead of `&`.
2. Use `id=1` instead of `id='1'`.
3. Use `$_GET` instead of `$_POST`. If you want backwards compatibility, you can opt for `$_REQUEST`. | You can make the link post the form:
```
<a href="#" onclick="if(display(1))document.getElementById('test1').submit();return false;"> Click</a>
```
That way it works without changing the PHP code. | How can I convert my button into a hyperlink in PHP? | [
"",
"php",
"html",
"button",
"hyperlink",
""
] |
I am just learning about computer vision and C#. It seems like two prominent image processing libraries are [OpenCV](http://opencv.willowgarage.com/wiki/) and [AForge](http://code.google.com/p/aforge/). What are some of the differences of the two?
I am making a basic image editor in C# and while researching I have come across articles on both. But I don't really know why I would choose one over the other. I would like to eventually improve the app to include more advanced functions.
Thanks. | I am using OpenCV for a project in school right now, and I browsed the documentation for AForge and their feature seem to differ.
AForge has lots of filters and is probably excellent for different transforms and image manipulation. But it seems to lack quite a bit in other areas. I could not find any matrix operations which was a disappointment as it is so useful in computer vision. Our current project (3D point cloud reconstruction from an image sequence) would, as far as I could see from the docs, be impossible to do with AForge alone.
Combine AForge with a good linear algebra library and you might have something really useful though.
As for OpenCV it has a rich feature set but is a bit tricky to program with. | Well, why not using both ;) ??
I am using (literally in C# ... lol) EMGUCV.NET (which is an OpenCV C# wrapper) and AFORGE.NET at the same time:
AFORGE.NET plus its "Image Processing Lab" makes much sense for filtering options (edge detection, thresholds, and so forth) and easing viewing functionalities.
OpenCV provides all the rest like SIFT/SURF and other more sophisticated image processing routines.
That's why you use .NET: simply bring all the components you need together in one application :) | Differences between AForge and OpenCV | [
"",
"c#",
"image-processing",
"opencv",
"aforge",
""
] |
In the app I am writing, I am trying to find a way to store hierarchies effectively. Here is an [example](http://www.battlestarvfx.com/images/bsg_breakouttutorial/BSG_TUT_CompTest_Fusion_GUI.jpg).
At the bottom, you can see the nodes to be stored. Should I use multi dimensional lists? That doesn't seem very optimal, right? I was thinking holding references like so:
```
node.Parent
node.Children { collection }
```
Anyone has experience with this kind of stuff? | This is a fairly basic implementation of a tree, yes. If choose to make your collection for the children an IList or IEnumable or ArrayList, etc is up to you.
I would strongly suggest you build a generic implementation instead of one typed to your domain model, however that is up to you. | Yeah. You have the right idea. If you need a two-directional hierarchy, I wouldn't use a multi-dimensional list... I would add a node to the tree and each node contains a parent and a collection of children.
You are on the right track. | Collections for hierarchies | [
"",
"c#",
".net",
"collections",
""
] |
We currently have a website that has user account functionality, but we are looking to provide an API to allow users to manage their accounts/perform actions via other devices/websites, by providing an API for common tasks.
Currently the website login is done via HTTPS for security, and then managed using PHP sessions with suitable security measures to guard against session hijacking etc.
How would we provide this functionality in an API?
How is it possible to submit a login without doing a POST? (As presumably GET is the only way to do this via an API call). Is isuing a URL like: <https://www.example.com/login/user-foo@password=bar> secure? Does the https setup happen before the URL is sent over the wire?
If I can sort that out then I would have the login return an access token. The first request should include this token, and the response should return a *new* token, for use on the second request and so on....
Would this work? | You can use [basic www-authentication](http://www.php.net/features.http-auth). It's basically a header, which contains username+password. The good thing about this, is that it's stateless (you don't need a separate login process), and it's very well supported. It's also quite simple to implement. As long as you serve it over https, the security is fine.
> Is isuing a URL like: <https://www.example.com/login/user-foo@password=bar> secure?
It's not good to put the credentials in the URL, since it might end up in a log.
> Does the https setup happen before the URL is sent over the wire?
Yes, https is established before the http protocol. The only thing a malicious person would be able to see, is the IP addresses of the endpoints. | Use a standard, such as [OAuth](http://oauth.net/)? If you allow for that, then your user can keep the authenticated token as long as they wish.
Alternatively, you may not need any authentication at all, if you could redirect to a login when some GET request comes in. For example: any site can link to an URL to [add a tweet](http://twitter.com/home?status=Browsing%20Stack%20Overflow) to Twitter. When not signed in, Twitter will first redirect to the login page. The referring site does not even need to know the Twitter username.
(And yes: HTTPS is established, based on the IP address of the server, before the URL is sent.) | How to do authentication within a HTTP service? | [
"",
"php",
"http",
"api",
"https",
""
] |
We're exporting some data from a website app into an Excel spreadsheet, however, when a GBP symbol is used, instead of outputting "£9.99" it produces "£9.99".
Here's the code a colleague has written to produce the spreadsheet [tableOut is a StringBuilder that contains an HTML table]:
```
string filename = "EngageReplies.xls";
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader( "content-disposition", "attachment;filename=" + filename );
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
this.EnableViewState = false;
Response.Write( tableOut );
Response.End();
```
Any ideas how we can get the desired output?
p.s. Not sure if I should separate this into a separate question, but when the spreadsheet is generated, a warning message is triggered:
> The file you are trying to open,
> 'EngageReplies.xls', is in a different
> format than specified by the file
> extension. Verify that the file is not
> corrupted and is from a trusted source
> before opening the file. Do you want
> to open the file now?
I've used Firefox and IE to Open the file with Office 2007. Clicking Yes opens the file okay, but I would prefer it if my users weren't subjected to it. | Aha!
First I tried removing the Charset and CharacterEncoding, but still got the wrong output, so then I set them to the following and it has worked correctly:
```
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
```
Thanks for the inspiration Rowland! | I wouldn't expect to see a Charset/ContentEncoding header when transferring a binary file, such as an XLS file. I'd also test the output be saving it to the lcoal disk somewhere and verifying that the file creation is doing "the right thing". | How to export pound symbol from a C# Web App to Excel correctly? (£ is produced instead of £) | [
"",
"c#",
".net",
"excel",
"character",
""
] |
I have a number of CSV files that I want to download from Yahoo finance each day. I want my application to read the file's creation date (on my computer, not the server). If the creation date is prior to today then the new file should be downloaded (as it will have new data). If not then the new file should not be downloaded, and the correlation calculator (which is essentially what my application is), should use the last downloaded file for the particular stock code.
I have done some googling and have found the Apache POI project.
Is this the best way to go, is there a better way, what would you recommend. Is JNI at all relevant here? | Did you consider creating an FTP account for access to that particular folder and then using an FTP client like SmartFTP or FileZilla to synchronize your local folder with the remote one? Should be well easy to set up and also convenient to use... Also, you could simply create an FTP command script and execute that from your Java code, if absolutely necessary...
Or I'll try to point you into another direction: md5() or other message-digest algorithms could help you. you wouldn't have to rely on timestamps. Try to calculate md5() hash of the file you have and the file you are about to download. Then you know whether to download or not. | I might be missing something but I can't see why you would need JNI or POI to download a file.
If you are downloading the file with HTTP, you can use an HttpURLConnection with the "If-Modified-Since" request header. | How do I only download new files from a server? | [
"",
"java",
"filesystems",
""
] |
My GUI locks up because I need to update it through the EDT, however, I need to also pass a variable that is being updates with the GUI:
```
while ((message = this.in.readLine()).startsWith("NUMPLAYERS"))
{
numOfPlayers = Integer.parseInt(message.split(":")[1]);
numPlayers.setText("There are currently " + numOfPlayers + " players in this game");
}
```
This does not work. I need to set the text in the EDT but I cannot pass numOfPlayers to it without declaring it as final (which I don't want to do, because it changed as new players join the server) | The easiest solution would be to use a `final` temporary variable:
```
final int currentNumOfPlayers = numOfPlayers;
EventQueue.invokeLater(new Runnable() {
public void run() {
numPlayers.setText("There are currently " +
currentNumOfPlayers + " players in this game");
}
});
``` | You have to make it final or have the `Runnable` reference a field (class varable). If referencing a field make sure that it's thread safe (via synchronized or volatile). | Passing variables to the Event Dispatch Thread | [
"",
"java",
"multithreading",
"event-dispatch-thread",
""
] |
I am looking for a one liner that transforms `List<T>` into `object[]`. It's one liner, so I am not interested in solutions such as `foreach`, or `for`...
Any takers?
Hint: No, both `List<T>.ToArray()` and `List<T>.ToArray<object>()` don't work.
Edit: Why `List<T>.ToArray<object>()` doesn't work? Because it can't compile. | ```
mylist.Cast<object>().ToArray()
```
That will only iterate once, by the way, in case you were wondering about the performance. O(n). :)
Why? Well, because [`Cast<object>`](http://msdn.microsoft.com/en-us/library/bb341406.aspx) will use deferred execution and won't actually do anything until the list is iterated by `ToArray()`. | ```
List<T>.Select(x => x as object).ToArray();
```
Should return an `object[]`. | Convert List<T> to object[] | [
"",
"c#",
"arrays",
"generics",
""
] |
I am trying include c++ library (DLL) in my c# project but every time I do that I get following error message in VS2008, any suggestions?
**EDIT:** It's a C++ MFC DLL
> ```
> ---------------------------
> Microsoft Visual Studio
> ---------------------------
> A reference to 'C:\Users\cholachaguddapv\Desktop\imaging.dll' could not be added. Please make sure that the file is accessible, and
> that it is a valid assembly or COM component.
> ``` | If it is a "normal" DLL (not COM, not managed C++), you cannot add a reference like this. You have to add p/invoke signatures (external static method definitions) for the exports you want to call in your DLL.
```
[DllImport("yourdll.dll")]
public static extern int ExportToCall(int argument);
```
Have a look at the [DllImport](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx) attribute in the online help. | If it's a straight C++ library then it's not possible to reference it in this way.
You have two options, you can compile the C++ library as an assembly an expose the unmanaged code with a C++/CLI wrapper.
-or-
You can use some p/invoke calls if the library exposes it's functionality via a C API.
Could you expand the question a bit to include some details about how you normally call imaging.dll from c++? | Using c++ library in c# | [
"",
"c#",
"visual-studio",
"visual-c++",
""
] |
I have looked at a good deal of other peoples source code and other open source PHP software, but it seems to me that almost nobody actually uses PEAR.
How common is PEAR usage out in real world usage?
I was thinking that maybe the current feeling on frameworks may be affecting its popularity. | PHP programmer culture seems to have a rampant infestation of "Not Invented Here" syndrome, where everyone appears to want to reinvent the wheel themselves.
Not to say this applies to *all* PHP Programmers, but them doing this apparently far too normal.
Much of the time I believe its due to lack of education, and that combined with difficulty of hosting providers providing decent PHP services.
This makes getting a workable PEAR installation so much more difficult, and its worsened by PHP's design structure not being favorable to a modular design.
( This may improve with the addition of namespaces, but have yet to see ).
The vast majority of PHP code I see in the wild is still classic amateur code interpolated with HTML, and the majority of cheap hosting that PHP users inevitably sign up for doesn't give you shell access. | In my (limited) experience, every PEAR project that was potentially interesting had major points against it:
* Code is targetted at the widest audience possible. There are hacks in place all over the place to deal with old/unsupported PHP versions. New useful features are ignored if they can't be emulated on older versions, meaning you end up lagging behind the core language development.
* Any given project tends to grow until it solves everyone's problem with a single simple `include`. When your PHP interpreter has to process all of that source code on every page hit (because the authors may not have designed it to be opcode-cache-friendly), there is a measurable overhead for processing thousands of unused lines of code.
* Style was always inconsistent. It never felt like I was learning generalizable APIs like in other languages.
I used to use `PEAR::DB` at work. We discovered that most of our scripts spent their time inside PEAR code instead of our own code. Replacing that with a very simple wrapper around `pgsql_*` functions significantly reduced execution time and increased runtime safety, due to the use of *real* prepared statements. `PEAR::DB` used its own (incorrect at the time) prepared-statement logic for Postgres because the native `pgsql_` functions were too new to be used everywhere.
Overall, I feel like PEAR is good as a "starter library" in many cases. It is likely to be higher quality code than any individual will produce in a short amount of time. But I would certainly not use it in a popular public-facing website (at least, not without a lot of tweaking by hand... maintaining my own fork). | How common is PEAR in the real world? | [
"",
"php",
"frameworks",
"pear",
""
] |
Date.getTime() returns milliseconds since Jan 1, 1970. Unixtime is seconds since Jan 1, 1970. I don't usually code in java, but I'm working on some bug fixes. I have:
```
Date now = new Date();
Long longTime = new Long(now.getTime()/1000);
return longTime.intValue();
```
Is there a better way to get unixtime in java? | Avoid the Date object creation w/ [System.currentTimeMillis()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/System.html#currentTimeMillis()). A divide by 1000 gets you to Unix epoch.
As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.
```
long unixTime = System.currentTimeMillis() / 1000L;
``` | Java 8 added a new API for working with dates and times.
With Java 8 you can use
```
import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();
```
`Instant.now()` returns an [Instant](http://docs.oracle.com/javase/8/docs/api/java/time/Instant.html) that represents the current system time. With `getEpochSecond()` you get the epoch seconds (unix time) from the `Instant`. | Getting "unixtime" in Java | [
"",
"java",
"unix-timestamp",
""
] |
I have a managed code Windows Service application that is crashing occasionally in production due to a managed StackOverFlowException. I know this because I've run adplus in crash mode and analyzed the crash dump post mortem using SoS. I have even attached the windbg debugger and set it to "go unhandled exception".
My problem is, I can't see any of the managed stacks or switch to any of the threads. They're all being torn down by the time the debugger breaks.
I'm not a Windbg expert, and, short of installing Visual Studio on the live system or using remote debugging and debugging using that tool, does anyone have any suggestions as to how I can get a stack trace out of the offending thread?
Here's what I'm doing.
> !threads
>
> ...
>
> XXXX 11 27c 000000001b2175f0 b220 Disabled 00000000072c9058:00000000072cad80 0000000019bdd3f0 0 Ukn System.StackOverflowException (0000000000c010d0)
>
> ...
And at this point you see the XXXX ID indicating the thread is quite dead. | Once you've hit a stack overflow, you're pretty much out of luck for debugging the problem - blowing your stack space leaves your program in a non-deterministic state, so you can't rely on *any* of the information in it at that point - any stack trace you try to get may be corrupted and can easily point you in the wrong direction. Ie, once the StackOverflowException occurs, it's too late.
Also, according to [the documentation](http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx) you can't catch a StackOverflowException from .Net 2.0 onwards, so the other suggestions to surround your code with a try/catch for that probably won't work. This makes perfect sense, given the side effects of a stack overflow (I'm surprised .Net ever allowed you to catch it).
Your only real option is to engage in the tedium of analyzing the code, looking for anything that could potentially cause a stack overflow, and putting in some sort of markers so you can get an idea where they occur *before* they occur. Eg, obviously any recursive methods are the first place to start, so give them a depth counter and **throw your own exception** if they get to some "unreasonable" value that you define, that way you can actually get a valid stack trace. | Is it an option to wrap your code with a `try-catch` that writes to the `EventLog` (or file, or whatever) and run this debug one-off?
```
try { ... } catch(SOE) { EventLog.Write(...); throw; }
```
You won't be able to debug, but you would get the stack trace. | live debugging a stack overflow | [
"",
"c#",
"crash",
"windbg",
"stack-overflow",
"sos",
""
] |
Is it possible to define a function that takes in a parameter that must implement two interfaces?
(The two interfaces are ones I just remembered off the top of my head; not the ones I want to use)
```
private void DoSomthing(IComparable, ICollection input)
{
}
``` | You can:
1) Define an interface that inherits both required interfaces:
```
public interface ICombinedInterface : IComparable, ICollection {... }
private void DoSomething(ICombinedInterface input) {... }
```
2) Use generics:
```
private void DoSomething<T>(T input)
where T : IComparable, ICollection
{...}
``` | You can inherit another interface from those two interfaces and make your parameter implement that interface. | Is it possible to make a parameter implement two interfaces? | [
"",
"c#",
".net",
"interface",
"parameters",
""
] |
I am using an infragistics webgrid and need to format a currency string. For this I need a string containing a pattern such as "$ ### ###,00" and I would like this to come out of my current CultureInfo. How can I do this?
Do I need to compose it manually from the info in:
```
CultureInfo.CreateSpecificCulture(myLanguageId).NumberFormat.CurrencyGroupSeparator
CultureInfo.CreateSpecificCulture(myLanguageId).NumberFormat.CurrencyGroupSizes
CultureInfo.CreateSpecificCulture(myLanguageId).NumberFormat.CurrencyDecimalDigits
CultureInfo.CreateSpecificCulture(myLanguageId).NumberFormat.CurrencyDecimalSeparator
```
etc
etc
etc
Is the a one-line solution? | thanks for all your answers.
It turns out that my requirements were wrong. The infragistics grid does not want a pattern string to know which separators use, it uses the pattern string for decimals and such and then queries the current culture about the rest.
So it is a non-issue.
thanks anyway! | ```
decimal moneyvalue = 1921.39m;
string s = String.Format("{0:C}", moneyvalue);
```
The current culture will be used.
Make sure you have the following in your web.config:
```
<system.web>
<globalization culture="auto" uiCulture="auto"/>
</system.web>
```
or as ck suggests, declare the equivalent, in your page | Currency format string in asp.net | [
"",
"c#",
"asp.net",
"currency",
"cultureinfo",
""
] |
I have a class that gets used in a client application and in a server application.
In the server application, I add some functionality to the class trough extension methods. Works great. Now I want a bit more:
My class (B) inherits from another class (A).
I'd like to attach a virtual function to A (let's say Execute() ), and then implement that function in B. But only in the server. The Execute() method would need to do stuff that is only possible to do on the server, using types that only the server knows about.
There are many types that inherit from A just like B does, and I'd like to implement Execute() for each of them.
I was hoping I could add a virtual extension method to A, but that idea doesn't seem to fly. I'm looking for the most elegant way to solve this problem, with or without extension methods. | No, there aren't such things as virtual extension methods. You could use overloading, but that doesn't support polymorphism. It sounds like you might want to look at something like dependency injection (etc) to have different code (dependencies) added in different environments - and use it in regular virtual methods:
```
class B {
public B(ISomeUtility util) {
// store util
}
public override void Execute() {
if(util != null) util.Foo();
}
}
```
Then use a DI framework to provide a server-specific `ISomeUtility` implementation to `B` at runtime. You can do the same thing with a central `static` registry (IOC, but no DI):
```
override void Execute() {
ISomeUtility util = Registry.Get<ISomeUtility>();
if(util != null) util.Foo();
}
```
(where you'd need to write `Registry` etc; plus on the server, register the `ISomeUtility` implementation) | You can use the new dynamic type functionality to avoid having to build a registry of types to methods:
```
using System;
using System.Collections.Generic;
using System.Linq;
using visitor.Extension;
namespace visitor
{
namespace Extension
{
static class Extension
{
public static void RunVisitor(this IThing thing, IThingOperation thingOperation)
{
thingOperation.Visit((dynamic)thing);
}
public static ITransformedThing GetTransformedThing(this IThing thing, int arg)
{
var x = new GetTransformedThing {Arg = arg};
thing.RunVisitor(x);
return x.Result;
}
}
}
interface IThingOperation
{
void Visit(IThing iThing);
void Visit(AThing aThing);
void Visit(BThing bThing);
void Visit(CThing cThing);
void Visit(DThing dThing);
}
interface ITransformedThing { }
class ATransformedThing : ITransformedThing { public ATransformedThing(AThing aThing, int arg) { } }
class BTransformedThing : ITransformedThing { public BTransformedThing(BThing bThing, int arg) { } }
class CTransformedThing : ITransformedThing { public CTransformedThing(CThing cThing, int arg) { } }
class DTransformedThing : ITransformedThing { public DTransformedThing(DThing dThing, int arg) { } }
class GetTransformedThing : IThingOperation
{
public int Arg { get; set; }
public ITransformedThing Result { get; private set; }
public void Visit(IThing iThing) { Result = null; }
public void Visit(AThing aThing) { Result = new ATransformedThing(aThing, Arg); }
public void Visit(BThing bThing) { Result = new BTransformedThing(bThing, Arg); }
public void Visit(CThing cThing) { Result = new CTransformedThing(cThing, Arg); }
public void Visit(DThing dThing) { Result = new DTransformedThing(dThing, Arg); }
}
interface IThing {}
class Thing : IThing {}
class AThing : Thing {}
class BThing : Thing {}
class CThing : Thing {}
class DThing : Thing {}
class EThing : Thing { }
class Program
{
static void Main(string[] args)
{
var things = new List<IThing> { new AThing(), new BThing(), new CThing(), new DThing(), new EThing() };
var transformedThings = things.Select(thing => thing.GetTransformedThing(4)).Where(transformedThing => transformedThing != null).ToList();
foreach (var transformedThing in transformedThings)
{
Console.WriteLine(transformedThing.GetType().ToString());
}
}
}
}
``` | Virtual Extension Methods? | [
"",
"c#",
"extension-methods",
"virtual",
""
] |
Why does ReSharper complain when a method can become static, but is not?
Is it because only one instance of a static method is created (on the type) and thus save on performance? | I find that comment very useful as it points out two important things:
1. It makes me ask myself if the method
in question should actually be part
of the type or not. Since it doesn't use
any instance data, you should at
least consider if it could be moved
to its own type. Is it an integral part
of the type, or is it really a general
purpose utility method?
2. If it does make sense to keep the
method on the specific type, there's
a potential performance gain as the
compiler will emit different code
for a static method. | From the FxCop documentation for the same warning (emphasis added):
"Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. *This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.*" | ReSharper complains when method can be static, but isn't | [
"",
"c#",
"resharper",
"static-methods",
""
] |
I have a PHP file that spits out a form. I want to call this PHP file server-side, (currently using "include"), fill it in, and submit it.
This is better so I don't have to meddle around with the actual form PHP, just deal with the presentation layer so the data gets understood by its own PHP file.
Is this possible? The form "method" is POST. | You won't be able to fill in the form and submit it using `include()`. Submitting a form means that it has to go over HTTP to a web server, so what you're looking for is to emulate a POST request. PHP has a popular library called CURL to do this.
Try something like this:
```
$ch = curl_init('http://www.example.com/yourform.php');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'var1=value1&var2=value2&whatever=stuff');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
```
`$output` will contain the page output as if you had just submitted the form. | So you want to submit a form to yourself? Sounds like CURL will be the way to do it, but you'd be creating another HTTP session. Otherwise you can emulate the POST variables and call the form's action from your outside script. | Virtual PHP Form | [
"",
"php",
"forms",
"post",
""
] |
I have two tables in my SQL database:
Company:
* ID (autoincrement)
* name
* address
* ...
Employees:
* ID (autoincrement)
* Company\_id
* **internal\_id**
* name
* lastname
The problem is that I would like to have a employee id (internal\_id) that is relative to the **company** they belong to. I got this dilema since I'm really been searching what would be the cleanest way to implement it.
One option would be to just make a kind of SELECT MAX(internal\_id) FROM employees WHERE company\_id = X, but the problem would be that if I happen to delete the last employee the next one would be created with the ID of the next.
Any ideas or suggestions?
**PD: The reason of why I want to do this is that i dont want a user from company X create an employee that is for example ID=2000, while the last employee created in his company was, say, 1532. this would normally happen in a system in wich Company Y and Z also create employees on the same system. I want this ID not to use as a foreign\_key, but to have it for internal (even documents or reports) use.**
**PD2: In this case the employees will never have to change companies** | There are lots of questions here about creating "Business" IDs or numbers that are unrelated to the primary keys.
In your case I would create a column on the Company table "NextEmployeeID" Then when creating a new employee simply retrieve the value and increment it.
Now I leave it up to you to figure out what happens if the employee changes companies. :-) | No, don't do that! This will create many many problems in your database (you have to worry about concurrency issues among other things) to solve something that is NOT a propblem and is, in fact, correctly designed. The id should be meaningless and gaps are unimportant. You would want a unique index on the employeeid/companyid combination to ensure no employee is assigned to multiple companies.
Your employee id should be something that never needs to be changed. If you make some sort of silly company based ID and company A buys out company B and becomes company C, you end up having to change all the ids and all the related tables. In your current design you only need to update the company code but not the related tables. | Company vs Employee ID dilemma | [
"",
"php",
"mysql",
"database",
"database-design",
""
] |
HI, I'm extending a windows application written in C# to provide help to the user (in the context of the focused control) when they hit the F1 key.
What I’d like to do is make use of the Control.HelpRequested event but I’m not sure how to extend all the controls to handle this event.
<http://msdn.microsoft.com/en-us/library/system.windows.forms.control.helprequested.aspx>
It’s not really feasible to update each control “by hand” to handle this event and I really don’t like the idea of looping through all the controls in a form (as the form opens) to associate the event handler.
Is there a neat way to extend all controls of a form to handle a specific event?
This is just made up but i almost feel like i should be able to write something like this
```
[HandleEvent Control.HelpRequested, ApplyTo Typeof(Control)]
void MyEventHandler(object sender, EventArgs e)
{
// code to handle event...
}
```
Any suggestions or perhaps ideas on a different approach are much appreciated - Thanks | This example (<http://www.codeproject.com/KB/cs/ContextHelpMadeEasy.aspx>) shows how to trap the F1 key in WndProc and then show the help from one method only.
The idea in that article is to implement an interface exposing control's ID and then show context help based on that id. The F1 handler then checks if your control implements that interface, and if not, then it check's the control's parent until it finds an implementation of that interface.
But an even simpler approach (if you don't want to add an ID to each control) is to modify the F1 handler to show context help based on a static type dictionary (e.g. Dictionary), which would contain Topic IDs for every supported control. So, whenever you need to associate a topic with a specified control, you would update the dictionary.
Again, it would be wiser to add more abstraction to this approach by adding some sort of a provider (delegate or interface) to that dictionary. For example, you might need additional logic to show topics based on control's type, name, or some other property. | > I really don’t like the idea of
> looping through all the controls in a
> form (as the form opens) to associate
> the event handler.
Can I ask why not?
You could write a function that takes a delegate and a list of types as an arguement, which will have exactly the same effect as your "wished for" HandleEvent attribute. | Global event handler for all controls for User Help | [
"",
"c#",
"winforms",
"events",
"context-sensitive-help",
""
] |
I have a [Qt](https://en.wikipedia.org/wiki/Qt_%28software%29) application in [Visual Studio 2005](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005) which is linked using `\subsystem:windows` such that when I run the compiled executable it does not create a command line terminal, as well.
I would like to create a command-line mode: when I start it with the `--nogui` command line argument, then the GUI is not presented, but a simple command-line program is run. Since the linking uses `/subsystem:windows`, the command line mode doesn't show any of the `std::cout` outputs unless I link my executable with `\subsystem:console`.
Is there a way to set the compilation/linking such that the same executable can either present the GUI windows or behave as a console application based on command-line parameters?
PS. I use Qt 4.2.0 and Visual Studio 2005 and the project is in C++. | I think the preferred technique for the situation here is the ".com" and ".exe" method. In Windows from the command line, if you run a program and don't specify an extension, the order of precedence in locating the executable will [.com preferred over a .exe file](https://stackoverflow.com/questions/605101/order-in-which-command-prompt-executes-files-with-the-same-name-a-bat-vs-a-cmd/605139#605139).
Then you can use tricks to have that ".com" be a proxy for the stdin/stdout/stderr and launch the same-named .exe file. This give the behavior of allowing the program to preform in a command-line mode when called form a console (potentially only when certain command-line arguments are detected) while still being able to launch as a GUI application free of a console.
There are various articles describing this, like "How to make an application as both GUI and Console application?" (see references in link below).
I hosted a project called [dualsubsystem on google code](http://code.google.com/p/dualsubsystem/ "dualsubsystem") that updates an old codeguru solution of this technique and provides the source code and working example binaries.
I hope that is helpful! | You can't. See this article by Raymond Chen:
> [**How do I write a program that can be run either as a console or a GUI application?**](https://web.archive.org/web/20100506201350/http://blogs.msdn.com:80/oldnewthing/archive/2009/01/01/9259142.aspx)
For the reasons given in this article you sometimes see two versions of the same tool provided, one suffixed with 'w' such as in java.exe and javaw.exe on Windows.
However you might implement this clever workaround: [How to make an application as both GUI and Console application](https://learn.microsoft.com/en-us/archive/blogs/junfeng/how-to-make-an-application-as-both-gui-and-console-application). | One executable that starts as a GUI application or console application based on command line in Visual Studio 2005 | [
"",
"c++",
"visual-studio",
"qt",
"visual-studio-2005",
""
] |
I've got a static class member which is some container, like
(Foo.h)
```
class Foo
{
...
private:
static list<string> s_List;
}
```
I need to populate the list with a number of specific values. Actually it should be also **const**, but that might overcomplicate the problem further.
All the class member functions are static, so initializing it in a constructor doesn't make sense. | a common solution is to do something like this:
```
// header
class Foo
{
...
private:
static list<string> s_List;
}
// cpp
list<string> init()
{
list<string> tmp;
... fill tmp with strings
return tmp;
}
list<string> Foo::s_List(init());
```
the other method is like Neil Butterworth suggested. | Another alternative is to create a simple initialiser class:
```
list <string> Foo::s_List;
struct Init {
Init() {
Foo::s_List.insert("apple");
Foo::s_List.insert("bannana");
Foo::s_List.insert("grapes");
}
};
static Init doInit;
```
Note that, as the list is private, this will probably require you to make Init a friend of Foo. It's also often convenient to make such classes be contained by the class they are initialising.
However, I just re-read your question and another thought occurs - if the list is const, you will presumably not be changing it, in which case a simple array of strings, initialised with the strings in sorted order may be a better solution. It will certainly be faster to search (using std::binary\_search) than a list, and can of course be easily initialised. | Populate a static member container in c++ | [
"",
"c++",
"stl",
""
] |
What if I have this:
```
union{
vector<int> intVec ;
vector<float> floatVec ;
vector<double> doubleVec ;
} ;
```
Of course, I'll be using just one of the 3 vectors. But... what happens when all the 3 vectors are contructed??
Would the consructors of the 3 vectors interfere with each other?? (since the 3 of them are in the same memory address)
Thanks. | Current C++ standard does not allow non-POD types inside unions. You will get this compiler error from `gcc`:
```
error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with constructor not allowed in union
error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with destructor not allowed in union
```
New C++ standard ([C++0x](http://en.wikipedia.org/wiki/C%2B%2B0x)) proposes [unrestricted unions](http://en.wikipedia.org/wiki/C%2B%2B0x#Unrestricted_unions), but it [adds yet *more* object lifetime pitfalls to C++](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=407). | You cannot have unions containing non-POD class types. Your sample will not compile.
You can use `boost::variant` as a safe alternative to C unions. See the [documentation on boost.org](http://www.boost.org/doc/libs/1_38_0/doc/html/variant.html). You might, however, reconsider your design and use polymorphism instead. Depends on what you're trying to accomplish, of course. | Is it possible to put several objects together inside a union? | [
"",
"c++",
"unions",
""
] |
I used to run Tomcat separately on my machine. I had an Ant script that would rebuild my project, deploy it locally, and restart Tomcat. That all worked ok, but I wasn't able to debug the web app inside Eclipse.
So I learned how to setup Tomcat inside Eclipse and got my web app running. Now the problem is that I don't understand fully how to manage it this way. Eclipse is set to automatically build my project on changes, but those changes don't seem to always be reflected in the web app. Sometimes I have to manually build the project and manually "clean" the server for the changes to be reflected.
Are there rules somewhere about how to manage this setup? For instance, if I only change a JSP then will it automatically be synchronized? If I change a servlet class, then I need to manually rebuild the project? Are these rules consistent, or should I just manually rebuild and clean every time?
I would really appreciate it if someone could give me the best practice rules or point me to a good resource to learn how to manage this environment.
PS. I am using Eclipse 3.4.1 Java EE package and Tomcat v5.5 | You can use Eclipse and Tomcat in the way you mention. First the basics of how to set it up:
1. In the Servers view setup a new Tomcat server pointing to your TOMCAT\_HOME
2. Make sure your project is an Eclipse "web project". You may need to create a dummy one and copy over some of the files in .settings (look at the wst files).
3. Deploy your project to Tomcat by right clicking on the server in the Servers view and "Add and Remove Projects..." to add your project to the server.
You can run your server and test it out just like you were running Tomcat outside of Eclipse. If you run the server in Debug mode you can set breakpoints and step through the code.
As for when you will need to restart the server Eclipse is usually pretty good about auto-deploying the changes. You will pretty much never need to restart for changes to jsp pages. If you change a class it will auto-deploy the change (usually) if you change the body of a method. If you change the signature of a class (add or remove a method or change args for it) you will almost always need to restart. Any changes to configuration files (web.xml or similar) will also almost always require a restart.
To restart just click on the "Debug" or "Run" button in the Server view. All your changes will be redeployed into Tomcat.
One thing to watch out for is that in the default configuration your "webapp" directory in TOMCAT\_HOME will not be used. Instead it will use a folder under your Eclipse workspace directory (WORKSPACE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0). | If you change the structure of a class that has already been loaded and used (add/remove members, change method signature etc.) your code changes will not be reflected. This is not an eclipse issue but a JVM issue. If you make simple code changes, like logic changes inside an existing method, your changes will take effect after the class is compiled and re-deployed.
Regardless of that, if you change a public constant, you have to rebuild your project(s). | How to properly manage Tomcat web apps inside Eclipse? | [
"",
"java",
"eclipse",
"tomcat",
""
] |
Good day,
When we add a column to a table, it gets added to the end of the table. However,
I really need to add a column to the beginning of the table. The reason is that we have scripts that import data from a flat file source to a table, and that it would be really easier for us to have the columns at the beginning to the table.
Thank you!
sql server 2005 | GUI method: in SQL Server Management Studio if you right click the table and choose "Design" you can then drag the column up to the top and hit save.
**Note**: *Be aware that by doing this, SQL Server drops the table and creates it again. You won't lose your data though.* | ```
ALTER TABLE table_name ADD COLUMN column_name FIRST;
``` | SQL Server 2005: How to add a column to a table at the beginning of the table? | [
"",
"sql",
"sql-server",
""
] |
I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it.
What's the easiest way to do the XML-RPC ping in django/Python? | You can use Django's [`signals`](http://docs.djangoproject.com/en/dev/topics/signals/) feature to get a callback after a model is saved:
```
import xmlrpclib
from django.db.models.signals import post_save
from app.models import MyModel
def ping_handler(sender, instance=None, **kwargs):
if instance is None:
return
rpc = xmlrpclib.Server('http://ping.feedburner.google.com/')
rpc.weblogUpdates.ping(instance.title, instance.get_absolute_url())
post_save.connect(ping_handler, sender=MyModel)
```
Clearly, you should update this with what works for your app and read up on signals in case you want a different event. | Use pluggable apps, Luke!
<http://github.com/svetlyak40wt/django-pingback/> | Ping FeedBurner in Django App | [
"",
"python",
"django",
"xml-rpc",
""
] |
I want to round a DateTime to the nearest 5 seconds. This is the way I'm currently doing it but I was wondering if there was a better or more concise way?
```
DateTime now = DateTime.Now;
int second = 0;
// round to nearest 5 second mark
if (now.Second % 5 > 2.5)
{
// round up
second = now.Second + (5 - (now.Second % 5));
}
else
{
// round down
second = now.Second - (now.Second % 5);
}
DateTime rounded = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, second);
```
Please note that I've found [these](https://stackoverflow.com/questions/152774/is-there-a-better-way-to-trim-a-datetime-to-a-specific-precision) [two](https://stackoverflow.com/questions/166145/whats-the-best-way-to-round-a-net-date-object-to-the-nearest-minute-closed) previous questions, however they *truncate* rather than *round* the time. | The Ticks count of a DateTime represents 100-nanosecond intervals, so you can round to the nearest 5 seconds by rounding to the nearest 50000000-tick interval like this:
```
DateTime now = DateTime.Now;
DateTime rounded = new DateTime(((now.Ticks + 25000000) / 50000000) * 50000000);
```
That's more concise, but not necessarily better. It depends on whether you prefer brevity and speed over code clarity. Yours is arguably easier to understand. | (Sorry for the resurrection; I recognize it's an old and answered question - just adding some extra code for Google's sake.)
I started with [JayMcClellan's answer](https://stackoverflow.com/questions/766626/is-there-a-better-way-in-c-to-round-a-datetime-to-the-nearest-5-seconds/766652#766652), but then I wanted it to be more generic, rounding to arbitrary intervals (not just 5 seconds). So I ended up leaving Jay's method for one that uses `Math.Round` on ticks and put it into an extension method that can take arbitrary intervals and also offers the option of changing the rounding logic (banker's rounding versus away-from-zero). I'm posting here in case this is helpful to someone else as well:
```
public static TimeSpan Round(this TimeSpan time, TimeSpan roundingInterval, MidpointRounding roundingType) {
return new TimeSpan(
Convert.ToInt64(Math.Round(
time.Ticks / (decimal)roundingInterval.Ticks,
roundingType
)) * roundingInterval.Ticks
);
}
public static TimeSpan Round(this TimeSpan time, TimeSpan roundingInterval) {
return Round(time, roundingInterval, MidpointRounding.ToEven);
}
public static DateTime Round(this DateTime datetime, TimeSpan roundingInterval) {
return new DateTime((datetime - DateTime.MinValue).Round(roundingInterval).Ticks);
}
```
It won't win any awards for bare efficiency, but I find it easy to read and intuitive to use. Example usage:
```
new DateTime(2010, 11, 4, 10, 28, 27).Round(TimeSpan.FromMinutes(1)); // rounds to 2010.11.04 10:28:00
new DateTime(2010, 11, 4, 13, 28, 27).Round(TimeSpan.FromDays(1)); // rounds to 2010.11.05 00:00
new TimeSpan(0, 2, 26).Round(TimeSpan.FromSeconds(5)); // rounds to 00:02:25
new TimeSpan(3, 34, 0).Round(TimeSpan.FromMinutes(37); // rounds to 03:42:00...for all your round-to-37-minute needs
``` | Is there a better way in C# to round a DateTime to the nearest 5 seconds? | [
"",
"c#",
"algorithm",
"datetime",
"performance",
""
] |
I like how Groovy makes all of your instance variables and class variables public and writes getters and setters on your behalf. This saves a lot of unnecessary coding. On the other hand, my boss hates it, making me very sad :(
Is there a way to achieve the conciseness of Groovy in Java without having to use Groovy or some other framework/add-on?
I have a feeling the powers that be will not take kindly to the introduction of this foreign framework where I work.
So what I'm looking for is a solution to the excessive verboseness of Java without using Groovy or something like it.
Can it be done in Java alone - such as by simply making everything public? | Go with immutable datastructures. No getters, no setters, no hassle.
You may want to give [Functional Java](http://functionaljava.org) a try. It's just a regular Java library, but comes with powerful abstractions and useful (immutable) datastructures that let you say more in less code. For example, translate this:
```
List<String> s = new ArrayList<String>();
for (String x : xs) {
for (String y : ys) {
for (String z : zs) {
s.add(doSomething(x, y, z));
}
}
}
```
... to this:
```
List<String> s = xs.bind(ys, zs, doSomething);
``` | The Java language is what it is. You won't find much to change the core language without moving to a new language (like groovy). Getting buy-in from management might not be as hard as you think to move to groovy. I was in a similar position as you a few years ago. You can start introducing groovy into a few areas of your software that make sense.
A great place to start is to start using it for unit testing. Essentially when you write a class in groovy, it compiles down to Java bytecode. As long as you have the groovy jars on your classpath, others may not even know it is groovy code. By using it for testing, you can demonstrate how it simplifies your code and makes things easier. You should be able to sell that to management.
From there, keep introducing it in other new areas where a dynamic language would save you some work. Groovy and Java mix very well together since they use the same set of core libraries. | I'm looking for a solution to the excessive verboseness of Java without using Groovy | [
"",
"java",
"groovy",
"verbosity",
""
] |
I'm trying to use a radio button as a click function:
```
$("input[type=radio]").click(function(){
```
and I don't just want radio buttons, I want radio buttons with the class 'baby', or I could even do it by name if that's easier, searched google and I can't find anything :( | How about this :
```
$("input[type=radio][class=baby]").click(function(){
``` | You can have multplie selectors
```
$("input[type=radio]", ".baby").click(function(){}
```
[Here](http://www.pamaya.com/jquery-selectors-and-attribute-selectors-reference-and-examples/) you have nice examples | jQuery Form Input | [
"",
"javascript",
"jquery",
""
] |
Given a string:
```
String exampleString = "example";
```
How do I convert it to an `InputStream`? | Like this:
```
InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
```
Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as *UTF-8*.
For versions of Java less than 7, replace `StandardCharsets.UTF_8` with `"UTF-8"`. | I find that using [Apache Commons IO](http://commons.apache.org/io/) makes my life much easier.
```
String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");
```
You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project. | How do I convert a String to an InputStream in Java? | [
"",
"java",
"string",
"type-conversion",
"inputstream",
""
] |
I've heard that i++ isn't a thread-safe statement since in assembly it reduces down to storing the original value as a temp somewhere, incrementing it, and then replacing it, which could be interrupted by a context switch.
However, I'm wondering about ++i. As far as I can tell, this would reduce to a single assembly instruction, such as 'add r1, r1, 1' and since it's only one instruction, it'd be uninterruptable by a context switch.
Can anyone clarify? I'm assuming that an x86 platform is being used. | You've heard wrong. It may well be that `"i++"` is thread-safe for a specific compiler and specific processor architecture but it's not mandated in the standards at all. In fact, since multi-threading isn't part of the ISO C or C++ standards (a), you can't consider anything to be thread-safe based on what you think it will compile down to.
It's quite feasible that `++i` could compile to an arbitrary sequence such as:
```
load r0,[i] ; load memory into reg 0
incr r0 ; increment reg 0
stor [i],r0 ; store reg 0 back to memory
```
which would not be thread-safe on my (imaginary) CPU that has no memory-increment instructions. Or it may be smart and compile it into:
```
lock ; disable task switching (interrupts)
load r0,[i] ; load memory into reg 0
incr r0 ; increment reg 0
stor [i],r0 ; store reg 0 back to memory
unlock ; enable task switching (interrupts)
```
where `lock` disables and `unlock` enables interrupts. But, even then, this may not be thread-safe in an architecture that has more than one of these CPUs sharing memory (the `lock` may only disable interrupts for one CPU).
The language itself (or libraries for it, if it's not built into the language) will provide thread-safe constructs and you should use those rather than depend on your understanding (or possibly misunderstanding) of what machine code will be generated.
Things like Java `synchronized` and `pthread_mutex_lock()` (available to C/C++ under some operating systems) are what you need to look into (a).
---
(a) This question was asked before the C11 and C++11 standards were completed. Those iterations have now introduced threading support into the language specifications, including atomic data types (though they, and threads in general, are *optional,* at least in C). | You can't make a blanket statement about either ++i or i++. Why? Consider incrementing a 64-bit integer on a 32-bit system. Unless the underlying machine has a quad word "load, increment, store" instruction, incrementing that value is going to require multiple instructions, any of which can be interrupted by a thread context switch.
In addition, `++i` isn't always "add one to the value." In a language like C, incrementing a pointer actually adds the size of the thing pointed to. That is, if `i` is a pointer to a 32-byte structure, `++i` adds 32 bytes. Whereas almost all platforms have an "increment value at memory address" instruction that is atomic, not all have an atomic "add arbitrary value to value at memory address" instruction. | I've heard i++ isn't thread safe, is ++i thread-safe? | [
"",
"c++",
"c",
"multithreading",
""
] |
I ask this for deployable reasons. As in, if I write a solution in python, I feel bound to write to 2.x due to the lack of adoption of python 3. This is a major daily concern of mine, and I want to figure out what's going on.
For many of the python-based questions here, people are giving solutions that **simply do not work in python 3.x**.
So, I ask the question: What has prevented you from switching to python 3.x in your personal or work environment? The conversion script exists, and yet programmers (who are usually the earliest adopters of everything) seem to refuse to upgrade.
Why? | **[Edit 03/10/2014: This answer is now out-of-date. Django has supported Python 3 for some time.]**
**[However, it must also be noted that the django third-party packages and extensions used in many Django projects are in various stages of Python 3 compatibility implementation. More details can be found in [Django packages website](https://www.djangopackages.com/python3/) which tracks the statuses of various projects.]**
Django has not moved over to 3.0. That is all I need to know.
> ## Related Questions
>
> * [Will Python 3.0’s backwards-incompatibility affect adoption?](https://stackoverflow.com/questions/340530/will-python-30s-backwards-incompatibility-affect-adoption)
> * [Is Python 3 a good starting point when you want to learn Python?](https://stackoverflow.com/questions/352312/is-python-3-a-good-starting-point-when-you-want-to-learn-python)
> * [If I’m going to learn Python, should I learn 2.x or just jump into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0)
> * [Who’s Using Python 3.0?](https://stackoverflow.com/questions/533510/whos-using-python-3-0)
> * [Python Version for a Newbie](https://stackoverflow.com/questions/345255/python-version-for-a-newbie)
> * [Is it worth learning Python 2.6 with 3.0 coming?](https://stackoverflow.com/questions/282819/is-it-worth-learning-python-26-with-30-coming)
Most of the answers in these questions echo the same sentiments. Aside from Django, too many frameworks/libraries - WxPython, PyGame, Django, etc - have still not adopted it. I'm sure as hell not making the move until they do. | Because major libraries that my codebase depends upon have not released a 3.x version. (wxPython, matplotlib, numpy, etc.)
So the responsibility goes upstream from my point of view.
If all my dependencies were 3.x compatible, I'd probably have switched by now. | Why won't you switch to Python 3.x? | [
"",
"python",
"deployment",
"python-3.x",
""
] |
I've been tasked with implementing a web service method that can be used for many different things(read: no requirements exist) and any client's won't have to change the interface Here's what the method is supposed to look like
```
[DataContract]
public class Status
{
[DataMember(Order = 0)]
public long Code
{
get;
set;
}
[DataMember(Order = 1)]
public string Message
{
get;
set;
}
}
[DataContract]
public class Data
{
[DataMember(Order = 0)]
public string Name
{
get;
set;
}
[DataMember(Order = 1)]
public string Value
{
get;
set;
}
}
public Status InitiateTransaction(long txnTypeId, Data [] txnData);
```
The idea is that the client would pass different things in the data array based on what type of "transaction" they want to initiate. What would be the benefit of this over just creating a bunch of different specialized methods that do specific things? | If the people suggesting you implement this are subject to shame, tell them that this pattern is a sure sign of laziness. They can't be bothered to figure out what the requirements are for behavior, so they specify a single method; they can't be bothered to figure out the requirements for data, so they decide on name/value pairs.
There is only one circumstance where I have found this sort of thing to be useful. I have seen some value in defining a web service that accepts a piece of XML and returns a piece of XML, hopefully at least constrained by XML Schema. This is of some use when the service is meant to interact with some other service or other piece of code that operates in terms of XML documents. An example would be an EDI scenario, when the document formats are already defined by industry standard or agreement, and the web service is really nothing more than a proxy for the service that will do the real work.
It doesn't look like your example has that excuse. | Well, the benefit is - it's somewhat "generic" - depending on what gets passed in.
But that's its biggest weakness too, at the same time. Since it's so generic and all-purpose, you can't really enforce a lot of constraints and/or validity checks, really.
I've seen this approach in many places - web services, database schemas - and they usually work fine for two or three separate "things" but begin to fall apart the more complex they get.
I would strongly recommend creating specific, well-checked methods for each thing you want to do.
Marc
PS: also - extending an existing service with additional methods while not changing any of the existing interfaces can be done very easily and without any change to the clients, too - so you can always easily extend your service as your requirements grow, without breaking backwards compatibility. | WCF Web service method advice | [
"",
"c#",
"wcf",
"web-services",
""
] |
For writing unit tests, I know it's very popular to write test methods that look like
```
public void Can_User_Authenticate_With_Bad_Password()
{
...
}
```
While this makes it easy to see what the test is testing for, I think it looks ugly and it doesn't display well in auto-generated documentation (like sandcastle or javadoc).
I'm interested to see what people think about using a naming schema that is the method being tested and underscore test and then the test number. Then using the XML code document(.net) or the javadoc comments to describe what is being tested.
```
/// <summary>
/// Tests for user authentication with a bad password.
/// </summary>
public void AuthenticateUser_Test1()
{
...
}
```
by doing this I can easily group my tests together by what methods they are testing, I can see how may test I have for a given method, and I still have a full description of what is being tested.
we have some regression tests that run vs a data source (an xml file), and these file may be updated by someone without access to the source code (QA monkey) and they need to be able to read what is being tested and where, to update the data sources. | What about changing
```
Can_User_Authenticate_With_Bad_Password
```
to
```
AuthenticateDenieTest
AuthenticateAcceptTest
```
and name suit something like `User` | I prefer the "long names" version - although only to describe *what* happens. If the test needs a description of *why* it happens, I'll put that in a comment (with a bug number if appropriate).
With the long name, it's much clearer what's gone wrong when you get a mail (or whatever) telling you which tests have failed.
I would write it in terms of what it *should* do though:
```
LogInSucceedsWithValidCredentials
LogInFailsWithIncorrectPassword
LogInFailsForUnknownUser
```
I don't buy the argument that it looks bad in autogenerated documentation - why are you running JavaDoc over the *tests* in the first place? I can't say I've ever done that, or *wanted* generated documentation. Given that test methods typically have no parameters and don't return anything, if the method name can describe them reasonably that's all the information you need. The test runner should be capable of listing the tests it runs, or the IDE can show you what's available. I find that more convenient than navigating via HTML - the browser doesn't have a "Find Type" which lets me type just the first letters of each word of the name, for example... | Writing long test method names to describe tests vs using in code documentation | [
"",
"java",
".net",
"unit-testing",
""
] |
To display a GNOME pop-up notification at (200,400) on the screen (using Python):
```
import pynotify
n = pynotify.Notification("This is my title", "This is my description")
n.set_hint('x', 200)
n.set_hint('y', 400)
n.show()
```
I'm a gtk noob. How can I make this Notification show up centered on the screen, or at the bottom-center of the screen?
Perhaps my question should be "what Python snippet gets me the Linux screen dimensions?", and I'll plug those into set\_hint() as appropriate. | Since you're using GNOME, here's the GTK way of getting the screen resolution
```
import gtk.gdk
import pynotify
n = pynotify.Notification("This is my title", "This is my description")
n.set_hint('x', gtk.gdk.screen_width()/2.)
n.set_hint('y', gtk.gdk.screen_height()/2.)
n.show()
``` | A bit of a hack, but this works:
```
from Tkinter import *
r = Tk()
r.withdraw()
width, height = r.winfo_screenwidth(), r.winfo_screenheight()
```
Another option is:
```
from commands import getstatusoutput
status, output = getstatusoutput("xwininfo -root")
width = re.compile(r"Width: (\d+)").findall(output)[0]
height = re.compile(r"Height: (\d+)").findall(output)[0]
``` | How to center a GNOME pop-up notification? | [
"",
"python",
"user-interface",
"gtk",
"pynotify",
""
] |
I'd like to do two things on my progress bar.
1. Change the green colour to red.
2. Remove the blocks and make it in one color.
Any information about those two things I wonder how to accomplish will be greatfuly appreaciated!
Thanks. | Since the previous answers don't appear to work in with Visual Styles. You'll probably need to create your own class or extend the progress bar:
```
public class NewProgressBar : ProgressBar
{
public NewProgressBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rec = e.ClipRectangle;
rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
if(ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
rec.Height = rec.Height - 4;
e.Graphics.FillRectangle(Brushes.Red, 2, 2, rec.Width, rec.Height);
}
}
```
EDIT: Updated code to make the progress bar use the visual style for the background | OK, it took me a while to read all the answers and links. Here's what I got out of them:
**Sample Results**
The accepted answer disables visual styles, it does allow you to set the color to anything you want, but the result looks plain:

Using the following method, you can get something like this instead:

**How To**
First, include this if you haven't: `using System.Runtime.InteropServices;`
Second, you can either create this new class, or put its code into an existing `static` non-generic class:
```
public static class ModifyProgressBarColor
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr w, IntPtr l);
public static void SetState(this ProgressBar pBar, int state)
{
SendMessage(pBar.Handle, 1040, (IntPtr)state, IntPtr.Zero);
}
}
```
Now, to use it, simply call:
`progressBar1.SetState(2);`
Note the second parameter in `SetState`, `1 = normal (green);` `2 = error (red);` `3 = warning (yellow)`. | How to change the color of progressbar in C# .NET 3.5? | [
"",
"c#",
".net",
"winforms",
".net-3.5",
""
] |
In this example:
```
var p1 = new {Name = "A", Price = 3};
```
**And this translates into IL:**
```
class __Anonymous1
{
private string name ;
private int price;
public string Name{ get { return name; } set { name = value ; } }
public int Price{ get { return price; } set { price= value ; } }
}
__Anonymous1 p1 = new __Anonymous1();
p1.Name = "A";
pt.Price =3
```
According to IL, it is **Allowed**, why is it so? What is the decision behind it? Shouldn't be readonly?
Thanks
It is my first question, be gentle. | I'm not sure I understand your question... Why wouldn't it be allowed?... or what do you expect not to be allowed?
```
var p = new {Name = "A", Price = 3};
//Some Code Here
p.Name = "B";
//Some more code
p.Price = 5;
```
Likewise, if I were to create a second anonymous variable the C# compiler is smart enough to know that they have same structure, so it will generate a single anonymous class in the background.
```
var p = new {Name = "A", Price = 3};
//Some Time Later
var q = new {Name = "B", Price = 4};
//Only one anonymous class is generated in the IL
``` | Let me turn that around on you: why restrict it? | Modify fields in anonymous types? | [
"",
"c#",
".net",
""
] |
I have two tables (item and category, I think they speak for themselves) and two associated model objects. I'm facing a design decisions in the function that fetches 1 item from the database. I need this method to also return the category (name, not just id) of the item.
I have two options:
* In the item model, use an SQL join to get the data faster.
* In the item model, call the category model to get the data, for better code.
Which should I do? I need a category model in any case, because I'll also be showing a list of categories, etc. | You can always optimize later if you need to. In many cases, the overhead of the second select will be negligible.
Your time isn't so negligible. Nor is the time of whomever (you? someone else?) maintains the code.
Code it cleanly, call the category, and if it turns out to be "too slow", then change it.
Premature optimization is the root of all evil. | Without knowing ALOT more detail, I would tend to lean towards the first option if this is a speed critical portion of the application. Just make sure the code is well commented. If you have the speed to play with and there isn't too much difference in the time between the two executions, I'd do the second. Because when you come back to it in two years, it'll make a lot less sense why the item model is pulling category info otherwise. | sql join or calling another model? | [
"",
"php",
"oop",
"model",
""
] |
I have a button element that I've created like so:
```
$submit = new Zend_Form_Element_Button('submit');
$submit->setLabel('My Button');
$submit->setDecorators(array(
'ViewHelper',
array('HtmlTag', array('tag' => 'li'))
));
$submit->setAttrib('type', 'submit');
```
This generates the following HTML:
```
<li>
<label for="submit" class="optional">My Button</label>
<button name="submit" id="submit" type="submit">My Button</button>
</li>
```
I would like to wrap the inside of the button with a <span>, like this:
```
<button...><span>My Button</span></button>
```
What is the best way to do this using Zend\_Form? | I have tried and, ultimately, failed to achieve this myself using the same approach. It would seem that the easiest way to do this would be to do:
```
...
$submit->setLabel('<span>My Button</span>');
...
```
However, the span will be escaped. It's perfectly possible to turn off the escaping of a lable decorator, however, adding a label decorator renders the output incorrectly, for instance:
```
$decorator = array(
array('ViewHelper'),
array('HtmlTag', array('tag' => 'li')),
array('Label', array('escape' => false))
);
$submit = new Zend_Form_Element_Button('submit');
$submit->setLabel('<span>My Button</span>');
$submit->setDecorators($decorator);
$submit->setAttrib('type', 'submit');
```
... renders:
```
<label for="submit" class="optional"><span>My Button</span></label>
<li>
<button name="submit" id="submit" type="submit"><span>My Button</span></button>
</li>
```
...which, aside from being semantically incorrect (easily fixable), is still escaping the span tags inside the element.
**So what do you do?**
Well I think the best approach (and this is my meta-advice when it comes to tight control over Zend\_Form rendering) is to use the [ViewScript](http://framework.zend.com/manual/en/zend.form.standardDecorators.html#zend.form.standardDecorators.viewScript) decorator.
```
$submit = new Zend_Form_Element_Button('submit');
$submit->setLabel('My Button');
$submit->setDecorators(array(array('ViewScript', array('viewScript' => '_submitButton.phtml'))));
$submit->setAttrib('type', 'submit');
```
...then in *\_submitButton.phtml* define the following:
```
<li>
<?= $this->formLabel($this->element->getName(), $this->element->getLabel()); ?>
<button
<?php
$attribs = $this->element->getAttribs();
echo
' name="' . $this->escape($this->element->getName()) . '"' .
' id="' . $this->escape($this->element->getId()) . '"' .
' type="' . $this->escape($attribs['type']) . '"';
?>
<?php
$value = $this->element->getValue();
if(!empty($value))
{
echo ' value="' . $this->escape($this->element->getValue()) . '"';
}
?>
>
<span>
<?= $this->escape($this->element->getLabel()); ?>
</span>
</button>
</li>
```
The *\_submitButton.phtml* file will need to be in a view script directory (you might be best adding a specific one for your form decorators using `$view->addScriptPath('/path/to/my/form/decorators')`).
This should render what you're looking for. I've only just started looking at the ViewScript decorator due to flexibility issues I'm experiencing in work. You'll notice that my script isn't that flexible, and certainly isn't in BNF, given all the members that can be populated on the element object. That said, it's a start and it solves your problem. | You could do this:
```
$this->addElement(new Zend_Form_Element_Button(
'send',
array(
'label' => '<span>registrieren</span>',
'class' => 'button-red',
'type' => 'submit',
'escape' => false,
'required' => false,
'ignore' => false,
)
));
``` | Zend Framework Zend_Form Decorators: <span> Inside Button Element? | [
"",
"php",
"zend-framework",
"zend-form",
""
] |
I have a base class like this:
```
public class BaseModalCommand
{
protected object m_commandArgument;
protected int m_commandID;
protected int m_enableUIFlags;
public virtual void OnIdle()
{
}
public virtual void OnResume()
{
}
public virtual void OnStart(int commandID, object argument)
{
}
public virtual void OnStop()
{
}
public virtual int EnableUIFlags
{
get
{
return this.m_enableUIFlags;
}
}
}
```
The virtual methods are to be overridden in derived types. If I run it thru FxCop, it complains about not declaring visible instance fields and recommends changing it to private and exposing it as a protected property.
Any thoughts? I'm thinking this message can be ignored. | For any class, there are two kinds of uses by client code: code that references your class, and code that inherits your class. It's widely recognized that the second kind of use by far the most tightly coupled. Changes in your class directly affect their internal mechanics. Your exposing protected members like this means that changes in your base class will affect how your derived classes work in ways that are unpredictable without comparing the code of each base and derived class. Equally bad, your derived classes can modify the internals of the base class.
If you really want to expose internal data members like this, wrap private data members in protected properties (as gisresearch suggests). These properties (along with any protected methods) constitute the **inheritance interface** of your class. Like any interface exposed to outside clients (whether through just defining public methods and properties, or through explicit interface implementation), this interface is something you will need to manage, particularly in larger code bases. An interface can be changed, but should be changed as a conscious decision.
If you work with protected data members directly, you have much less control over the dependencies between base and derived classes. Trust me on this: not even being able to determine what effects a change may have can be a Very Unpleasant Thing. | As best practice, your class fields should be marked as private
and wrapped in a getter/setter property
so instead of
```
protected object m_commandArgument;
```
use
```
private object m_commandArgument;
protected object CommandArgument {get; set;}
```
Theres several advantages to this but a simple usage would be exception handling/validation in your setter.
e.g.
```
private string _email;
protected string Email
{
get { return _email; }
set
{
if(value.IndexOf("@") > 0)
_email = value;
else
throw new ArgumentException("Not a valid Email");
}
}
``` | Best way to expose protected fields | [
"",
"c#",
"properties",
"field",
""
] |
Is it possible to split the contents of file into parts that have specific pattern?
This is what I want to achieve:
* Read the file using file\_get\_contents
* Read only contents between similar commented areas.
I am not sure how complicated is that but basically If I am parsing a large html file and want only to display to the browser the specific widgets (pattern is the comment boundaries) like this:
Sample:
```
<html>
<head>
<title>test</title>
</head>
<body>
this content should not be parsed.. ignored
<!-- widget -->
this is the widget. i want to parse this content only from the file
<!-- widget -->
</body>
</html>
```
would it be possible using php and regex or anything to parse the contents between boundaries only?
I apologize but I tried to explain what I want to achieve as much as I can. hope someone helps me. | It's certainly possible, but it doesn't really need to be done with regex. I'd probably just do something like this:
```
$file = file_get_contents('http://example.com/');
$widgets = explode('<!-- widget -->', $file);
```
Now the odd elements of `$widget` (`[1], [3], [5]`, etc) contain what was between those boundaries. | You can achieve what you want with a regular expression (or if you are only ever splitting on you can probably just use that). Check the documentation. The other answer using explode() will probably also work.
```
$text = file_get_contents('/path/to/your/file');
$array = split('<!-- widget -->', $text);
```
The first entry will be everything before the first occurrence of `<!-- widget -->` and the last element will be everything after the last `<!-- widget -->`. Every odd-numbered element will be what you're looking for.
[Php split function documentation](https://www.php.net/split) | Is it possible to split the file contents using a custom pattern? | [
"",
"php",
"regex",
"parsing",
"file-get-contents",
""
] |
I have an application that reads data from a com port using javax.comm.
The problem I am having is that if the device that I'm reading from is unexpectedly disconnected I get an error in the console that says "WaitCommEvent: Error 5"
I have looked around and can't find any helpful information about this. I have set all of the notifyOn\* methods to true so I think I should be receiving all of the events but I'm not catching this one.
The error message that is printed out does not come from anywhere in my code so it must be in the javax.comm package somewhere. Can anyone tell me how to handle this error so that I can close the com port properly when it occurs?
Thanks! | IF anyone is interested in this, I found a solution. I was using the javax.comm api but to solve the problem I replaced it with rxtx api (<http://rxtx.qbang.org/wiki/index.php/Main_Page>). No code changes were needed but now when the device is disconnected I receive an IOException with the message "Underlying input stream returned zero bytes". I handle that message and kick off a new thread. In the new thread I call port.close() and port.removeEventListener(). These two calls must be done in a new thread or the application will hang. | We've been using a lot of time on getting javax.comm to work and found that in our case it was the COM driver which was causing the problems (on several Windows 7 computers).
If the driver is also your problem and you're using Windows 7 or possibly Vista (and you're using a Prolific/Logilink seriel cable) then this might be the solution :)
<http://www.akosta.dk/category/technical-notes/>
Hope you get it to work! | javax.comm: Error when device is disconnected | [
"",
"java",
"error-handling",
"javax.comm",
""
] |
I was under the assumption that STL functions could be used only with STL data containers (like `vector`) until I saw this piece of code:
```
#include <functional>
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int a[] = {9, 8, 7};
cerr << "Sum: " << accumulate(&a[0], &a[3], 0, plus<int>()) << endl;
return 0;
}
```
It compiles and runs without any warnings or errors with g++, giving the correct output sum of 24.
Is such usage of arrays with STL functions **allowed** by the C++/STL **standard**? If yes, how do archaic structures like arrays fit into the grand STL plan of templated iterators, containers and functions? Also, are there any caveats or details in such usage that the programmer should be **careful** about? | Well, you ask about an array. You can just easily get a pointer to its elements, so it basically boils down to the question whether pointers can be used transparently with STL functions. A pointer actually is the most powerful kind of an iterator. There are different kinds
* **Input iterator**: Only forward and one-pass, and only read
* **Output iterator**: Only forward and one-pass, and only write
---
* **Forward iterator**: Only forward, and read/write
* **Bidirectional iterator**: Forward and backward, and read/write
* **Random access iterator**: Arbitrary steps forward and backward in one breath, and read/write
Now each iterator in the second group supports all the things of all iterators mentioned before it. A pointer models the last kind of iterators - a random access iterator. You may add/subtract an arbitrary integer and you may read and write. And all except the output iterator has a `operator->` that can be used to access a member of the element type we iterate over.
Normally, iterators have several typedefs as members
* value\_type - what the iterator iterates over (int, bool, string, ...)
* reference - reference to the value\_type
* pointer - pointer to the value\_type
* difference\_type - what type the distance between two iterators has (returned by `std::distance`).
* iterator\_category - this is a tag-type: it is typedefed to a type that represents the kind of the iterator. either `std::input_iterator_tag`, ..., `std::random_access_iterator_tag`. Algorithms can use it to overload on different kinds of iterators (like `std::distance` is faster for random access iterators, because it can just return `a - b`)
Now, a pointer of course does not have those members. C++ has an `iterator_traits` template and specializes it for pointers. So if you want to get the value type of any iterator, you do
```
iterator_traits<T>::value_type
```
And whether it is a pointer or some other iterator, it will give you the value\_type of that iterator.
So - yes, a pointer can very well be used with STL algorithms. As someone else mentioned, even `std::vector<T>::iterator` can be a `T*`. A pointer is a very good example of an iterator even. Because it is so exceedingly simple but at the same time so powerful that it can iterate over a range. | The standard has designed iterators to feel and behave as much like pointers as possible. Also, since iterators are based on templates, the only relevant thing is that the iterator type has the proper operators defined. The result is that pointers will out-of-the-box behave just like random access iterators.
In fact, a possible implementation of `std::vector<T>::iterator` is to just make it a `T*`.
Of course, for an array you won't have the useful `begin()` and `end()` methods to find the valid iterator range, but that's the problem you always have with C style arrays.
Edit: Actually, as has been mentioned in the comments and other answers, you can implement those functions for arrays if the array is not dynamic and has not decayed into a pointer. But my basic point was that you have to be more careful than when using the standard containers. | C++ STL: Can arrays be used transparently with STL functions? | [
"",
"c++",
"arrays",
"stl",
""
] |
Trying to create a sequence in Oracle that starts with the max value from a specific table. Why does this not work?
```
CREATE SEQUENCE transaction_sequence
MINVALUE 0
START WITH (SELECT MAX(trans_seq_no)
FROM TRANSACTION_LOG)
INCREMENT BY 1
CACHE 20;
``` | If you can use PL/SQL, try (EDIT: Incorporates Neil's xlnt suggestion to start at next higher value):
```
SELECT 'CREATE SEQUENCE transaction_sequence MINVALUE 0 START WITH '||MAX(trans_seq_no)+1||' INCREMENT BY 1 CACHE 20'
INTO v_sql
FROM transaction_log;
EXECUTE IMMEDIATE v_sql;
```
Another point to consider: By setting the CACHE parameter to 20, you run the risk of losing up to 19 values in your sequence if the database goes down. CACHEd values are lost on database restarts. Unless you're hitting the sequence very often, or, you don't care that much about gaps, I'd set it to 1.
One final nit: the values you specified for CACHE and INCREMENT BY are the defaults. You can leave them off and get the same result. | Here I have my example which works just fine:
```
declare
ex number;
begin
select MAX(MAX_FK_ID) + 1 into ex from TABLE;
If ex > 0 then
begin
execute immediate 'DROP SEQUENCE SQ_NAME';
exception when others then
null;
end;
execute immediate 'CREATE SEQUENCE SQ_NAME INCREMENT BY 1 START WITH ' || ex || ' NOCYCLE CACHE 20 NOORDER';
end if;
end;
``` | How to create an Oracle sequence starting with max value from a table? | [
"",
"sql",
"oracle",
"sequence",
""
] |
I need create a 3D model of and animate a robotic arm. The arm is going to receive inputs on how to move via serial I/O.
What is the best Java IDE for me to create this 3D model with? It doesn't have to be fancy or anything, just a proof of concept. Unfortunately, I haven't had any experience with animation before, so I'd appreciate something that's easy to pick up.
Thanks a lot, I really appreciate any help.
Zain
PS: I could potentially do this in 2D as well, except I imagine that would probably entail more work since I'd have to draw a lot more images. If I'm wrong please let me know.
Below I've made an approximate ascii drawing of what the arm needs to look like, with the x's showing all the joints that need to rotate. If I didn't have to rotate the base as well, this would probably have been pretty easy to do in 2D.
```
____
/ ___|
______/ /
/x_____x|
/ / \ \___
/ / \____|
/x/
| |
| |
___| |___
|___x___|
``` | Java3D or JOGL are common libraries for creating 3D graphics in Java. If you have a simple 3D model, you can just create it programmatically using simple 3D shapes. Anything more complex will probably require a 3D modelling tool like Chad and Alex mentioned.
* <http://java.sun.com/javase/technologies/desktop/java3d/>
* <https://jogl.dev.java.net/> | You seem to have programming confused with 3D modeling. This isn't something a Java IDE is going to do for you. If you actually need a real 3D model, you could look into free 3D modeling programs like [Blender](http://en.wikipedia.org/wiki/Blender_(software)). | Easy to learn 3D IDE for Java | [
"",
"java",
"ide",
"3d",
""
] |
I have inherited some code that uses the **ref** keyword extensively and unnecessarily. The original developer apparently feared objects would be cloned like primitive types if **ref** was not used, and did not bother to research the issue before writing 50k+ lines of code.
This, combined with other bad coding practices, has created some situations that are absurdly dangerous on the surface. For example:
---
```
Customer person = NextInLine();
//person is Alice
person.DataBackend.ChangeAddress(ref person, newAddress);
//person could now be Bob, Eve, or null
```
Could you imagine walking into a store to change your address, and walking out as an entirely different person?
---
Scary, but *in practice* the use of **ref** in this application seems harmlessly superfluous. I am having trouble justifying the extensive amount of time it would take to clean it up. To help sell the idea, I pose the following question:
## How else can unnecessary use of ref be destructive?
I am especially concerned with maintenance. Plausible answers with examples are preferred.
You are also welcome to argue clean-up is not necessary. | I would say the biggest danger is if the parameter were set to `null` inside the function for some reason:
```
public void MakeNull(ref Customer person)
{
// random code
person = null;
return;
}
```
Now, you're not just a *different* person, you've been erased from existence altogether!
As long as whoever is developing this application understands that:
> By default, object references are passed by value.
and:
> With the `ref` keyword, object references are passed by reference.
If the code works as expected now and your developers understand the difference, it's probably not worth the effort it's going to take remove them all. | I'll just add the worst use of the ref keyword I've ever seen, the method looked something like this:
```
public bool DoAction(ref Exception exception) {...}
```
Yup, you had to declare and pass an Exception reference in order to call the method, then check the method's return value to see if an exception had been caught and returned via the ref exception. | Ref Abuse: Worth Cleaning Up? | [
"",
"c#",
"ref",
""
] |
How can I create a bulleted list in ReportLab? The documentation is frustratingly vague. I am trying:
```
text = ur '''
<para bulletText="•">
item 1
</para>
<para bulletText="•">
item 2
</para>
'''
Story.append(Paragraph(text,TEXT_STYLE))
```
But I keep getting errors like `list index out of range`. It seems that I can't put more than one `<para></para>` in a single call to `Paragraph()`? I also tried setting `TEXT_STYLE.bulletText="•"` but that doesn't work either... | The bulletText argument is actually a constructor to the `Paragraph` object, not the `<para>` tag :-) Try this:
```
story.append(Paragraph(text, TEXT_STYLE, bulletText='-'))
```
Have a look at the examples on page 68 (page 74 now, in 2012) of the [ReportLab Documentation](http://www.reportlab.com/docs/reportlab-userguide.pdf), though. The convention in ReportLab seems to be to use the `<bullet>` tag, and the docs do warn that you can have only one per `Paragraph` instance. We render our bullets in ReportLab like so:
```
story.append(Paragraph('<bullet>The rain in spain</bullet>', TEXT_STYLE))
``` | The very recent versions of ReportLab have ListFlowable and ListItem objects (check Chapter 9 of the current user guide). | How to create a bulleted list in ReportLab | [
"",
"python",
"pdf",
"reportlab",
""
] |
I'm very sorry for the conservative title and my question itself,but I'm lost.
The samples provided with ICsharpCode.ZipLib doesn't include what I'm searching for.
I want to decompress a byte[] by putting it in InflaterInputStream(ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream)
I found a decompress function ,but it doesn't work.
```
public static byte[] Decompress(byte[] Bytes)
{
ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream stream =
new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(new MemoryStream(Bytes));
MemoryStream memory = new MemoryStream();
byte[] writeData = new byte[4096];
int size;
while (true)
{
size = stream.Read(writeData, 0, writeData.Length);
if (size > 0)
{
memory.Write(writeData, 0, size);
}
else break;
}
stream.Close();
return memory.ToArray();
}
```
It throws an exception at line(size = stream.Read(writeData, 0, writeData.Length);) saying it has a invalid header.
My question is not how to fix the function,this function is not provided with the library,I just found it googling.My question is,how to decompress the same way the function does with InflaterStream,but without exceptions.
Thanks and again - sorry for the conservative question. | Well it sounds like the data is just inappropriate, and that otherwise the code would work okay. (Admittedly I'd use a "using" statement for the streams instead of calling `Close` explicitly.)
Where did you get your data from? | the code in lucene is very nice.
```
public static byte[] Compress(byte[] input) {
// Create the compressor with highest level of compression
Deflater compressor = new Deflater();
compressor.SetLevel(Deflater.BEST_COMPRESSION);
// Give the compressor the data to compress
compressor.SetInput(input);
compressor.Finish();
/*
* Create an expandable byte array to hold the compressed data.
* You cannot use an array that's the same size as the orginal because
* there is no guarantee that the compressed data will be smaller than
* the uncompressed data.
*/
MemoryStream bos = new MemoryStream(input.Length);
// Compress the data
byte[] buf = new byte[1024];
while (!compressor.IsFinished) {
int count = compressor.Deflate(buf);
bos.Write(buf, 0, count);
}
// Get the compressed data
return bos.ToArray();
}
public static byte[] Uncompress(byte[] input) {
Inflater decompressor = new Inflater();
decompressor.SetInput(input);
// Create an expandable byte array to hold the decompressed data
MemoryStream bos = new MemoryStream(input.Length);
// Decompress the data
byte[] buf = new byte[1024];
while (!decompressor.IsFinished) {
int count = decompressor.Inflate(buf);
bos.Write(buf, 0, count);
}
// Get the decompressed data
return bos.ToArray();
}
``` | How to use ICSharpCode.ZipLib with stream? | [
"",
"c#",
"byte",
"sharpziplib",
"compression",
""
] |
I need to get a handle to whichever control has the minimum TabIndex. I've tried using GetNextDlgTabItem() and passing a 0 pointer for the second argument, but the returned handle isn't always the first one in the screen's tab order. Thoughts? | I ended up keeping track of which field got focus on load and then just setting focus back to that when needed. | Dirty method: Try looping through your collection of controls and keep track of the one with the smallest tab index, when the loop is complete you should be able to return the index of the control in that collection with the smallest tabindex property. | Getting handle of control with minimum TabIndex | [
"",
"c#",
".net",
"winforms",
""
] |
How to get the directory of a file?
For example, I pass in a string
```
C:\Program Files\nant\bin\nant.exe
```
I want a function that returns me
```
C:\Program Files\nant\bin
```
*I would prefer a built in function that does the job, instead of having manually split the string and exclude the last one.*
**Edit: I am running on Windows** | I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.
```
path = path.substring(0,path.lastIndexOf("\\")+1);
``` | If you use `Node.js`, `path` module is quite handy.
```
path.dirname("/home/workspace/filename.txt") // '/home/workspace/'
``` | Get directory of a file name in Javascript | [
"",
"javascript",
""
] |
I have been able to get javascript intellisense working correctly for a 'class' prototype defined like this:
```
function GetCustomerList()
{
}
GetCustomerList.prototype =
{
HEADER: {
RETURN_CODE: 0,
RETURN_MESSAGE: "",
}
,
NUM_RECORDS: 0,
START_RECORD: 0,
END_RECORD: 0
};
```
I can type something like:
```
var req = new GetCustomerList();
req.HEADER.RETURN_CODE = 100;
```
And Visual Studio's intellisense knows about the HEADER property, and its own properties named 'RETURN\_CODE' and 'RETURN\_MESSAGE'. I can do:
```
req.NUM_RECORDS = 50;
```
With intellisense working perfectly.
So intellisense works with complex nested types - great. However is it possible to get intellisense with an array of complex types?
Example:
```
function Customer()
Customer.prototype = {
NAME: "",
ADDRESS: "",
ID: 0
};
function GetCustomerList()
{
}
GetCustomerList.prototype =
{
HEADER: {
RETURN_CODE: 0,
RETURN_MESSAGE: "",
}
,
NUM_RECORDS: 0,
START_RECORD: 0,
END_RECORD: 0,
CUSTOMERS: [ new CUSTOMER() ]
};
```
Where I have an array of the type 'CUSTOMER' which I have also defined a prototype for. I'd like to be able to type things like:
```
req.CUSTOMER[ 0 ].NAME
```
And have intellisense prompt me that 'NAME' is a property available for this array.
Is this possible? | **UPDATE:**
As you have already noticed, IntelliSense works for your complex types just fine, but does not work at the Array. Even if you create an array of intrinsic types like String, it still does not work.
I have researched this topic thoroughly, in theory, this should be possible, but it's not.
As a test, create javascript file name it ***"customers.js***" and include the following:
```
function Customer() {
/// <summary>This is my custom intellisense for the Customer type</summary>
///<field name="NAME" type="String">The Customer's name</field>
///<field name="ADDRESS" type="String">The customer's address</field>
///<field name="ID" type="String">The ID number</field>
}
Customer.prototype = {
NAME: "",
ADDRESS: "",
ID: 0
};
function CustomerList() {
/// <summary>The List of Customers</summary>
///<field name="HEADER" type="String">The header</field>
///<field name="CUSTOMERS" type="Array" elementType="Customer" >The list of customers in an Array</field>
}
CustomerList.prototype =
{
HEADER: {
RETURN_CODE: 0,
RETURN_MESSAGE: ""
},
NUM_RECORDS: 0,
START_RECORD: 0,
END_RECORD: 0,
CUSTOMERS: [new Customer()]
};
```
Then reference this file inside `<script src="customers.js"/>`
or
`/// <reference path="customer.js" />` inside another JS file.
See how the intellisense show the summaries correctly, but when it comes to the array, nothing.
```
var custList = new CustomerList();
custList.CUSTOMERS // intellisense
custList.CUSTOMERS[0] // no intellisense as you already know
``` | There is no way to get this to work in VS2008. It will work in the next version of VS. | How do you get VS 2008 Javascript Intellisense working for complex prototypes? | [
"",
"javascript",
"visual-studio-2008",
"intellisense",
""
] |
I am making a multithreaded pacman game.
There is a PacmanController class which extends JFrame, a Maze class which extends JPanel, a Pacman class which runs in its own thread and extends JPanel, and a Ghost class which runs in its own thread and extends JPanel. Each thread (pacman and each Ghost) continuously repaints itself and calls maze.repaint() as well.
When I add the maze to the frame, it displays fine, if I then add pacman, it still displays and animates fine.
However, when I add the Ghost to the frame after pacman, the ghost appears and pacman disappears. If I switch the order in which pacman and the ghost are added, the opposite is true i.e. only one of pacman or each instance of ghost is ever displayed - the one which is added last.
Eg:
```
add(maze);
add(pacman);
add(ghostA);
```
Only the maze and ghostA appear?
I realize this has something to do with JFrames BorderLayout, i.e. only one component can be added to the center region, but don't know how to fix it. I have tried adding pacman and ghosts to EAST WEST etc but this didn't work.
I have also tried
```
maze.add(pacman);
add(pacman); //etc
```
but this didn't work either.
Sorry for the long post, any help is much appreciated. I can't post any code as the code is too long and spread over many classes.
Many thanks! | Take a look at
[Layered panels](http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html)
or
[StackLayout](http://www.jroller.com/gfx/entry/stacklayout) | **First:** Repainting from multiple threads in Swing is a recipe for trouble. A better way is to update from the main game class and pass the `Graphics` object to all the actors to paint themselves (I'm sure there are other patterns, but I haven't done this sort of thing in a while).
**Second:** Your actors (pacman, ghosts) should not be `JPanels`. That's a recipe for even worse trouble. Make them extend an `Actor` class or something, but they should not be Swing components.
I realize that this doesn't directly answer your question, but some of your problems will go away if you design your game properly. There are a number of tutorials on game design out there on the web; I can't recommend any of them personally, but the first couple of chapters of [Killer Game Programming in Java](http://fivedots.coe.psu.ac.th/~ad/jg/) look promising.
---
**Edit:** All right, I'll try to address the actual question.
If you're using `BorderLayout`, the way to add multiple components is to specify the position:
```
setLayout(new BorderLayout());
add(maze, BorderLayout.CENTER);
add(pacman, BorderLayout.EAST);
add(ghostA, BorderLayout.WEST);
```
Alternatively (and maybe better), you could add the players to the maze:
```
setLayout(new BorderLayout());
maze.setLayout(new BorderLayout());
maze.add(pacman, BorderLayout.EAST);
maze.add(ghostA, BorderLayout.WEST);
add(maze, BorderLayout.CENTER);
```
Now while these *ought* to get all three components added to the frame, I still can't see how you could have a game where the player is a `JPanel` trying to escape `JPanels`.
Anyway, if they don't work, the next thing to do is to try a different [layout manager](http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html). | Multiple animated JPanels - only last one added to JFrame is displaying | [
"",
"java",
"multithreading",
"swing",
""
] |
I currently use CodeIgniter as my framework of choice when using PHP. One of the things I am wrestling with is the idea of a "page", and how to represent that properly within MVC. To my knowledge, CodeIgniter has a front controller that delegates to page controllers. In my thought process, each page would have it's own controller. All too often though I see someone using a page controller stuffed with many methods. So in that sense, each action becomes it's own page.
I've never really liked the idea of stuffing many methods into one controller, because it seems like there will be too much overhead if you only need one method or two in the controller at a time. It's seems more reasonable for each page to have it's own controller, and the actions would only correspond to something you can do on that particular page. Am I thinking about this the wrong way?
What makes it more confusing is I'll notice in some web applications where they will have one controller that will have multiple methods (i.e. login, register, view, edit, etc.), but then on others they actually have a login controller, and a register controller. What is the proper use of a "page controller"? | From a domain perspective I definitely say it makes more sense to have 1 controller per domain context. Not necessarily one per page although depending on the context this may be the case. What I mean by context is "actions that are closely related".
For instance an account controller should handle the login, register, logout, change password, actions. They all live within the context of an "Account"
Take Stackoverflow for example. I would have a "Questions" controller which would have actions like DisplayQuestion, AskQuestion, Delete Question, MostRecent Questions, etc. They are all different "Views/pages" that are managed by one controller. | You're right in that every public method in a controller becomes a "page". That being said, it's not necessarily a web page, an action could be a post of data and then redirect to another action/page so page does not necessarily mean "web page".
MVC uses a lot of conventions to make things work. For instance, every controller must end with "Controller". So a set of user pages (create, edit, delete, etc.) would be in a UserController. In the Views folder, each public method or action within the controller class becomes a web page within a folder that matches the prefix of the controller (In this case, a User folder). So an action called "Delete" within the controller class would point to the Delete.aspx page within the User folder.
It seems a little awkward to put all of those methods in one class, but it does a nice job of organizing like functionalities based on your object. | What Defines the Traditional "Page" Concept in MVC? | [
"",
"php",
"model-view-controller",
"codeigniter",
"controller",
""
] |
I am setting up a web server for a client. They will be using a web app (PHP/LAMP) that I am building. The server will be sitting within their network locally. There will also be a MySQL database on the same server. The load on the server will only be 20-25 concurrent users, but uptime and performance is still very important.
The application itself will be using a back-end CMS (TBD) to display content to the user using JQuery on the front-end and PHP on the back-end.
So, my question is: Is there a good set of server system requirements in terms of CPU, Cache and memory (size/type) to provide a relatively cheap solution, but still provide quality performance. | To tell you the truth, hardware isn't the biggest factor, it's coding. If you develop your application correctly and optimally, then you should be able to run at least 100 users concurrently on a machine running with 1ghz, 512mb ram, and a 5200rpm hard drive.
I recommend using VMWare to create virtual machines and separate the MySQL server from the web server. This also gives you the ability to replicate, migrate, or upgrade the machine without reconfiguring and reinstalling.
Also, run your LAMP configuration on an operating system without a GUI (Debian, Ubuntu, Fedora, etc. with no X-Window installed). These are servers, they shouldn't be wasting resources displaying pretty windows.
Finally, like Trent said, RAID configuration is a great idea, but RAID is not a backup solution. If you have two of the same hard-drives, it is very likely that if one fails, the other will shortly after. Always have a backup solution (NAS, Tape, DVD, Floppy Disk, whatever). | Just make sure you have 2 of everything ... 2 Power supplies 2 hard drives (raid 1) or better more with raid 5. Depending on how important uptime is you may even want to have an entire fail over server. As for performance you haven't given us enough info ... how heavy are the queries how much data is in the database. | Any suggestions on server configuration for my web server? | [
"",
"php",
"configuration",
"lamp",
""
] |
Basically when I have a python file like:
```
python-code.py
```
and use:
```
import (python-code)
```
the interpreter gives me syntax error.
Any ideas on how to fix it? Are dashes illegal in python file names? | You should check out [PEP 8](http://www.python.org/dev/peps/pep-0008/), the Style Guide for Python Code:
> Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
>
> Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.
In other words: rename your file :) | One other thing to note in your code is that import is not a function. So `import(python-code)` should be `import python-code` which, as some have already mentioned, is interpreted as "import python minus code", not what you intended. If you really need to import a file with a dash in its name, you can do the following::
```
python_code = __import__('python-code')
```
But, as also mentioned above, this is not really recommended. You should change the filename if it's something you control. | Is it ok to use dashes in Python files when trying to import them? | [
"",
"python",
"naming",
""
] |
I would like to know what is the fastest way in java 1.5 to compare two data structures.
My data structure represents a tree that can be pretty big. I can traverse the whole data structure and compare the 2 node by node (which I guess will be slow). Or I can compute a hash of the data structure to do it faster, right ?
What is the best (efficient and not too long) way to compute this hash ?
I wouldn't like to need too much time to compute hash...
Hope I'm clear.. :-)... | Every object inherits [`.equals()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)) and [`.hashCode()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#hashCode()) from [Object](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html).
The standard data-structures in Java should already implement a relatively fast `.hashCode()` method for you (The hash might be incrementally calculated or might require iterating over each element, check the source of the data-structure you're using to be sure).
You should be aware that [hash collisions](http://en.wikipedia.org/wiki/Hash_collision) might occur even if the data-structures aren't identical.
To have an accurate comparison I would perform a [tree traversal](http://en.wikipedia.org/wiki/Tree_traversal) simultaneously on both tree comparing each element. This way the shape of the tree as well as the contained elements would be compared in `O(n)` time where `n` is the size of the largest tree. | Have you considered keeping a running hashCode which is continually updated as elements are inserted or removed from your trees? This way, comparing a tree at any given time by hashCode will be instantaneous.
Depending on how you implement your hash function, and how frequently you insert and remove nodes, this could be a horrible solution. If your hash function is fast, you aren't making many changes, and you need to do a lot of comparisons, this could work. | Fastest way to compare two data structures in java | [
"",
"java",
""
] |
I have based many designs and frameworks that use C# Attributes over the past 4 or 5 years.
But lately I see many people openingly discouraging their use or changing their frameworks to reduce the need or use of them.
I found them to be a godsend but now I am starting to wonder what I am missing.
To clarify:
Use Convention over Configuration is becoming a major principle to follow especially in the ORM field. Is this area you can map fields with a config file (XML), use an attribute, or have a common naming convention that maps directly to fields in your database tables. I don't have any references to quote but I have read some backlash against adding another Attribute to the mix.
But I feel over the three choices I just listed that Attributes still make the most sense. A Config file is harder to maintain and a common naming convention ties you to the implementation of the database field. Attributes are placed exactly where they are needed and the implemntation can change without disconnecting from where it is used. | There are really two purposes of attributes: as user visible things, and as things emitted by a compiler.
I assume you are talking about user visible attributes.
In general, I would say that user visible attributes are not ideal.
Most of the time they are used to embed some form of custom language on top of C#. DLINQ attributes are a good example of this. A better approach, from the consumer's perspective, would be to add first class support to the host language. That would end up feeling much more natural. (having language support for defining tables and foreign keys would be much easier to work with then all the crazy linq-to-sql attributes).
In reality, however, extending a programing language is too cost prohibitive for most developers. The benefits just don't out weigh the costs.
Perhaps someday C# will have meta-programing features, which will make doing that kind of thing easy.
At the moment, however, that capability does not exist.
This leaves you with 3 options:
1. Use attributes
2. Use a dynamic language, and generate code at runtime
3. Just don't use generative programing
Usually #1 ends up being the easiest choice to make, even if it isn't ideal. | This is a hard question to give a general answer for. Attributes are another language feature that are incredibly powerful when used correctly but do have the potential for abuse. I haven't ever seen a compelling reason to dump the use of attributes altogether and really no reason to think they are a bad idea.
In fact the exact opposite is true. Attributes allow for adding framework specific information into the metadata. Information that simply cannot be easily expressed via a type hierarchy. This dramatically increases the power of frameworks that use attributes.
I've certainly seen an implementation or two where people abused them a bit but nothing spectacular. Can you be more specific? Are there specific attributes / frameworks you're talking about. | Do you think C# attributes (or similar mechanisms) are a good idea or do you discourage the use of them? | [
"",
"c#",
"attributes",
"custom-attributes",
""
] |
I am having a problem with Hibernate generating invalid SQL. Specifically, mixing and matching implicit and explicit joins. This seems to be an [open bug](http://opensource.atlassian.com/projects/hibernate/browse/HHH-3388).
However, I'm not sure *why* this is invalid SQL. I have come up with a small toy example that generates the same syntax exception.
## Schema
```
CREATE TABLE Employee (
employeeID INT,
name VARCHAR(255),
managerEmployeeID INT
)
```
## Data
```
INSERT INTO Employee (employeeID, name) VALUES (1, 'Gary')
INSERT INTO Employee (employeeID, name, managerEmployeeID) VALUES (2, 'Bob', 1)
```
## Working SQL
Both of these queries work. I realize there is a Cartesian product; that's intentional.
*Explicit JOIN:*
```
SELECT e1.name,
e2.name,
e1Manager.name
FROM Employee e1
CROSS JOIN Employee e2
INNER JOIN Employee e1Manager
ON e1.managerEmployeeID = e1Manager.employeeID
```
*Implicit JOIN:*
```
SELECT e1.name,
e2.name,
e1Manager.name
FROM Employee e1,
Employee e2,
Employee e1Manager
WHERE e1.managerEmployeeID = e1Manager.employeeID
```
## Invalid SQL
This query does NOT work on MSSQL 2000/2008 or MySQL:
```
SELECT e1.name,
e2.name,
e1Manager.name
FROM Employee e1,
Employee e2
INNER JOIN Employee e1Manager
ON e1.managerEmployeeID = e1Manager.employeeID
```
In MS2000, I get the error:
> The column prefix 'e1' does not match
> with a table name or alias name used
> in the query.
In MySQL, the error is:
> Unknown column 'e1.managerEmployeeID'
> in 'on clause'.
## Question(s)
1. Why is this syntax invalid?
2. **Bonus:** Is there a way to force Hibernate to use only explicit JOINs?
--- | It results in an error because according to the SQL standard, the `JOIN` keyword has higher precedence than the comma. The sticky point is that table aliases are not usable until *after* the corresponding table has been evaluated in the `FROM` clause.
So when you reference `e1` in your `JOIN...ON` expression, `e1` doesn't exist yet.
Please stand by while I research Hibernate and find out if you can persuade it to use `JOIN` in all cases.
---
Hmm. Everything at Hibernate.org seems to be redirecting to jboss.org. So no way to read HQL documentation online right now. I'm sure they'll figure out their name serving eventually. | This might be a bit off topic, because it doesn't concern hibernate at all, but the comment from [Bill Karwin](https://stackoverflow.com/users/20860/bill-karwin) really opened my eyes. Instead of writing the implicit joining first, you need to do the explicit joining first. This syntax is especially interesting if you have multiple implicit joins.
Check the following example in MS SQL. Not all contacts have a country code defined, but all contacts have an attribute val which will be looked up in the table Tbl. So the intuitive solution will not work:
```
SELECT * FROM
contacts, Tbl
LEFT OUTER JOIN country ON CtryCod = country.CtryCod
WHERE val = Tbl.val
```
Instead you might rather want to use the following syntax:
```
SELECT * FROM
contacts LEFT OUTER JOIN country ON CtryCod = country.CtryCod,
Tbl
WHERE val = Tbl.val
``` | Mixing implicit and explicit JOINs | [
"",
"sql",
"hibernate",
"join",
"cartesian-product",
"cross-join",
""
] |
How much of the Java SE api is actually written in Java itself? | The easiest way to find out is just to look at the [source code](http://download.java.net/jdk6/source/) (that's from Sun's J2SE website; there's also the OpenJDK source for [6](http://download.java.net/openjdk/jdk6/) and [7](http://download.java.net/openjdk/jdk7/)). It's pretty much as you'd expect - things which absolutely *have* to be written in native code, e.g. "open a socket or a file" are native, but almost everything else is written in Java (in Sun's implementation, anyway). | Download [OpenJDK](http://openjdk.java.net/) and find out!
Most of it is Java, but there are some low-level things that must be native code (graphics and file operations come to mind). | How much of the Java SE api is written in Java? | [
"",
"java",
""
] |
I have an .INF for a virtual printer that I need to install from a .NET Application. I have done this before using batch scripts, but I am looking for a snippet of code to do this in the .NET Framework.
There's nothing particular about the printer .INF, so any code that installs a printer from an INF in C# or VB.NET will work. | I believe this is possible via interop to native win32 APIs, but I've found its much, much easier just to use a System.Diagnostics.Process() to call into printui.dll via:
`rundll32.exe printui.dll,PrintUIEntry /?`
Perhaps you're already using that in the mentioned batch script, but if not the parameters are documented here: [PrintUI.DLL User's Guide and Reference](http://www.microsoft.com/windowsserver2003/techinfo/overview/printuidll.mspx)
Just be sure to test it against all operation systems you need to support. Some options either do not exist in all Windows releases or have been renamed (although I think they're the more esoteric options - installing an .INF will likely work across the board). | You are going to want to look at the WMI objects available. These give you a finer control of the local machine settings. Take a look at the [WMI code creator](http://www.microsoft.com/downloads/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&DisplayLang=en) from Microsoft, I believe this will generate some example code you can leverage to solve your problem. | How can I install a printer using .NET? | [
"",
"c#",
"vb.net",
"printing",
""
] |
I know this is gonna be a stupid question.
Pardon me as a n00b into CS
I have a new swing component that inherits from JComponent.
I am trying to paint lines on its surface to show that the lines split the control into equal parts. The code looks like
```
int spc;
spc = (int) Math.round((this.ZBar.getWidth() / this.ZBar.getModel().getModelSize()));
for (int i = 0; i <= this.ZBar.getModel().getModelSize(); i++) {
g.drawLine(i * spcing, 0, i *, this.ZBar.getHeight());
}
```
this.ZBar.getModel().getModelSize(); gives out number of parts to split into.
However, in some cases there is some more space left on the right most end of my component. I guess it is gue to the Type conversion done by Math.round. How can I solve this ?? | Thank you very much for the reply.
Solved this.
I have made all those integer mess to double.
Then used Java2D package to handle doubles.
Line2D class support creation using double parameters. | It is because that division is a int type divide. For example:
```
5 / 2 == 2
```
Math.round is doing nothing here. It is already being rounded (as Math.floor instead).
To get your intended effect, cast the int to a double before the division:
```
(double)5 / 2 == 2.5
```
Or in your specific case:
```
spc = (int) Math.round(((double)this.ZBar.getWidth() / this.ZBar.getModel().getModelSize()));
``` | Splitting a swing control into equal parts | [
"",
"java",
"swing",
""
] |
A lot of [JVM's command line arguments dealing with the garbage collector](http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#icms.available_options) have "CMS" prepended to them. What does this stand for? | [Concurrent Mark Sweep](http://java.sun.com/javase/6/docs/technotes/guides/vm/cms-6.html)
(Or as Tom mentions in the comments, *mostly* Concurrent Mark Sweep.) | It's a method or algorithm for garbage collection that, in theory, affects the performance of the application less than the older methods.
> The concurrent mark sweep collector,
> also known as the concurrent collector
> or CMS, is targeted at applications
> that are sensitive to garbage
> collection pauses. It performs most
> garbage collection activity
> concurrently, i.e., while the
> application threads are running, to
> keep garbage collection-induced pauses
> short
[G1](http://tech.puredanger.com/2008/05/09/javaone-g1-garbage-collector) is the next level being considered/developed. | What does CMS mean in relation to Java's Garbage Collector? | [
"",
"java",
"garbage-collection",
"jvm",
""
] |
I am trying to become more efficient in my SQL programming.
I am trying to run a loop to repeat an update command on field names that only change by a numerical suffix.
For example, instead of writing out `x_1, y_1`, then `x_2, y_2` for each update:
```
DECLARE @a INT
DECLARE @b VARCHAR
SET @a = 1
WHILE @a < 30
set @b = @a
BEGIN
UPDATE source set h = h + "x_"+@b
where "y_"+@b = 'Sold'
SET @a = @a + 1
END
```
Let me know if I can clarify. I'm using SQL Server 2005.
Thanks for any guidance.
---
I'm trying to apply Adams's solution and need to understand what is proper usage of N' in the following:
```
exec sp_executesql update source_temp set pmt_90_day = pmt_90_day + convert(money,'trans_total_'+@b'')
where convert(datetime,'effective_date_'+@b) <= dateadd(day,90,ORSA_CHARGE_OFF_DATE)
and DRC_FLAG_'+@b = 'C'
``` | This won't actually work, as you can't have the column name in quotes. What you're essentially doing is having SQL compare two strings that will always be different, meaning you'll never perform an update.
If you must do it this way, you'd have to have something like...
```
DECLARE @a INT
DECLARE @b VARCHAR
SET @a = 1
WHILE @a < 30
BEGIN
set @b = @a
exec sp_executesql N'UPDATE source set h = h + 'x_'+@b + N'
where y_'+@b + N' = ''Sold'''
SET @a = @a + 1
END
```
In general, however, I'd discourage this practice. I'm not a fan of dynamic SQL being generated inside another SQL statement for any sort of production code. Very useful for doing one-off development tasks, but I don't like it for code that could get executed by a user. | Adam hit a lot around the problem itself, but I'm going to mention the underlying problem of which this is just a symptom. Your data model is almost certainly bad. If you plan to be doing much (any) SQL development you should read some introductory books on data modeling. One of the first rules of normalization is that entities should not contain repeating groups in them. For example, you shouldn't have columns called "phone\_1", "phone\_2", etc.
Here is a much better way to model this kind of situation:
```
CREATE TABLE Contacts (
contact_id INT NOT NULL,
contact_name VARCHAR(20) NOT NULL,
contact_description VARCHAR(500) NULL,
CONSTRAINT PK_Contacts PRIMARY KEY CLUSTERED (contact_id)
)
CREATE TABLE Contact_Phones (
contact_id INT NOT NULL,
phone_type VARCHAR(10) NOT NULL,
phone_number VARCHAR(20) NOT NULL,
CONSTRAINT PK_Contact_Phones PRIMARY KEY CLUSTERED (contact_id, phone_type),
CONSTRAINT CK_Contact_Phones_phone_type CHECK (phone_type IN ('HOME', 'FAX', 'MOBILE'))
)
```
Now, instead of trying to concatenate a string to deal with different columns you can deal with them as a set and get at the phone numbers that you want through business logic. (Sorry that I didn't use your example, but it seemed a bit too general and hard to understand). | Using While Loop for SQL Server Update | [
"",
"sql",
"sql-server-2005",
"loops",
""
] |
Why does the following program print what it prints?
```
class Program
{
static void Main(string[] args)
{
float f1 = 0.09f*100f;
float f2 = 0.09f*99.999999f;
Console.WriteLine(f1 > f2);
}
}
```
Output is
```
false
``` | Floating point only has so many digits of precision. If you're seeing f1 == f2, it is because any difference requires more precision than a 32-bit float can represent.
I recommend reading [What Every Computer Scientist Should Read About Floating Point](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) | The main thing is this isn't just .Net: it's a limitation of the [underlying system most every language will use to represent a float](http://en.wikipedia.org/wiki/IEEE_floating_point) in memory. The precision only goes so far.
You can also have some fun with relatively simple numbers, when you take into account that it's not even base ten. 0.1 (1/10th), for example, is a repeating decimal when represented in binary, just as 1/3rd is when represented in decimal. | Why is floating point arithmetic in C# imprecise? | [
"",
"c#",
"floating-point",
""
] |
I wanted to play around with the upcoming concurrency library which
is going to be included in
Java 7 according to [**this website**](http://tech.puredanger.com/java7/#jsr166).
It seems to be named **JSR166**.
In most places its reference implementation is referred as **jsr166y**,
while few resources call it **jsr166z**.
I discovered two totally **different** javadocs for each reference implementation.
* Docs for [**jsr166y**](http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/)
* Docs for [**jsr166z**](http://www.javac.info/jsr166z/)
Now, which implementation is going to be included in Java 7?
**EDIT**
While people who answered suggest that jsr166y is the thing for Java 7,
I discovered [**this** document (TS-5515)](http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-5515&yr=2008&track=javase) from JavaOne.
This document refers to Java 7 but mentions LinkedAsyncAction
which is only present in jsr166z javadocs. (Confusion...) | JSR 166 was the original Java concurrency jsr for Java 5 that created java.util.concurrent. They did a maintenance rev in Java 6 called JSR 166x. The Java 7 maintenance rev is JSR 166y. JSR 166z is the closures prototype version.
Currently slated to be included in JSR 166y is:
* Fork/join (but NOT the ParallelArray framework)
* TransferQueue / LinkedTransferQueue collection
* Phasers (CyclicBarriers on steroids)
Push to JDK 8 (at least):
* Fences API (low level), trying to remove use of Unsafe calls
* ConcurrentReferenceHashMap (variable strong/weak refs, concurrent, etc)
For more info, [javadoc here](http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/) or join the concurrency-interest mailing list:
* <http://cs.oswego.edu/mailman/listinfo/concurrency-interest> | The link on the javac.info site (jsr166z) uses BGGA closures which will not be in JDK7.
The link on Doug Lea's site (jsr166y) should be up to date. Doug is the spec lead. The API has been pruned down to the basics as how the fork-join framework will be used in practice is not yet clear. Presumably libraries will be available at a slightly higher level, and when thing settle down more can be added to JDK8. | What's the upcoming Java concurrency library: jsr166y? jsr166z? | [
"",
"java",
"concurrency",
"java-7",
""
] |
While idly surfing the namespace I noticed an odd looking object called `Ellipsis`, it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?
```
D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
``` | This came up in another [question](https://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation) recently. I'll elaborate on my [answer](https://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation/753260#753260) from there:
[Ellipsis](http://docs.python.org/dev/library/constants.html#Ellipsis) is an object that can appear in slice notation. For example:
```
myList[1:2, ..., 0]
```
Its interpretation is purely up to whatever implements the `__getitem__` function and sees `Ellipsis` objects there, but its main (and intended) use is in the [numpy](http://www.numpy.org/) third-party library, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4 × 4 array, the top left area would be defined by the slice `[:2, :2]`:
```
>>> a
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
>>> a[:2, :2] # top left
array([[1, 2],
[5, 6]])
```
Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice `[:]` for all the dimensions in the gap it is placed, so for a 3d array, `a[..., 0]` is the same as `a[:, :, 0]` and for 4d `a[:, :, :, 0]`, similarly, `a[0, ..., 0]` is `a[0, :, :, 0]` (with however many colons in the middle make up the full number of dimensions in the array).
Interestingly, in python3, the Ellipsis literal (`...`) is usable outside the slice syntax, so you can actually write:
```
>>> ...
Ellipsis
```
EDIT: Ellipsis is also used in the standard library `typing` module: e.g. `Callable[..., int]` to indicate a callable that returns an `int` without specifying the signature, or `tuple[str, ...]` to indicate a variable-length homogeneous tuple of strings. | In Python 3, you *can*¹ use the Ellipsis literal `...` as a “nop” placeholder for code that hasn't been written yet:
```
def will_do_something():
...
```
This is **not** magic; any expression can be used instead of `...`, e.g.:
```
def will_do_something():
1
```
(Can't use the word “sanctioned”, but I can say that this use was [*not outrightly rejected*](http://mail.python.org/pipermail/python-3000/2008-January/011793.html) by Guido.)
¹ `'can' not in {'must', 'should'}` | What does the Ellipsis object do? | [
"",
"python",
"ellipsis",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.