Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a winforms app and i want to keep track of every time a user clicks certain buttons, etc as well as other actions. What is the best way for me to keep track of this information and then put it together so i can run metrics on most used features, etc.
This is a winforms app and I have users around the world. | There are 2 big issues your design has to be sure to address
1. Privacy (what Don alluded to) - You must be crystal clear what information you are collecting and sending up to your central server, ideally the users should be able to inspect the exact data you are sending back to the central server (if they wish to) - For any public software there should be a very easy way to opt out.
2. Performance and Scalability - You have to estimate how much data you really need on the server side and look at all sort of tricks that aggregate and compress the data client side (as well as have hard limits on the amount of traffic you will be sending and how often you will be sending it)
As to the client side implementation, I would recommend investigating [Sqlite.net](http://sqlite.phxsoftware.com/) or another embedded DB. Using an embedded DB to store this information on the client will give you lots of flexibility with aggregations and will have the advantage of being transactional, fast and simple to implement. Sqlite has a very generous public domain license so from a legal perspective its really easy to use in public apps. | Try doing a google scholar search. There are some interesting ideas by Ben Liblit and co-authors, and another series of ideas by Alex Orso and co-authors (disclaimer - I'm one of Alex Orso's co-authors) based on taking a sample of runtime information from each user, and putting it together in an interesting way.
<http://theory.stanford.edu/~aiken/publications/papers/pldi03b.pdf>
and
<http://www.cs.umd.edu/class/fall2006/cmsc838p/Ramss/remoteClassJournal.pdf>
are two (not necessarily the best) examples of such papers/ideas. | lightweight instrumentation for winforms app | [
"",
"c#",
"winforms",
"instrumentation",
""
] |
In Python compiled regex patterns [have a `findall` method](http://docs.python.org/library/re.html#re.findall) that does the following:
> Return all non-overlapping matches of
> pattern in string, as a list of
> strings. The string is scanned
> left-to-right, and matches are
> returned in the order found. If one or
> more groups are present in the
> pattern, return a list of groups; this
> will be a list of tuples if the
> pattern has more than one group. Empty
> matches are included in the result
> unless they touch the beginning of
> another match.
What's the canonical way of doing this in Perl? A naive algorithm I can think of is along the lines of "while a search and replace with the empty string is successful, do [suite]". I'm hoping there's a nicer way. :-)
Thanks in advance! | Use the `/g` modifier in your match. From the `perlop` manual:
> The "`/g`" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.
>
> In scalar context, each execution of "`m//g`" finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the `pos()` function; see "`pos`" in `perlfunc`. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the "`/c`" modifier (e.g. "`m//gc`"). Modifying the target string also resets the search position. | To build on Chris' response, it's probably most relevant to encase the `//g` regex in a `while` loop, like:
```
my @matches;
while ( 'foobarbaz' =~ m/([aeiou])/g )
{
push @matches, $1;
}
```
Pasting some quick Python I/O:
```
>>> import re
>>> re.findall(r'([aeiou])([nrs])','I had a sandwich for lunch')
[('a', 'n'), ('o', 'r'), ('u', 'n')]
```
To get something comparable in Perl, the construct could be something like:
```
my $matches = [];
while ( 'I had a sandwich for lunch' =~ m/([aeiou])([nrs])/g )
{
push @$matches, [$1,$2];
}
```
But in general, whatever function you're iterating for, you can probably do within the `while` loop itself. | Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)? | [
"",
"python",
"regex",
"perl",
"iterator",
""
] |
What's the easiest way to shuffle an array with python? | ```
import random
random.shuffle(array)
``` | ```
import random
random.shuffle(array)
``` | Shuffle an array with python, randomize array item order with python | [
"",
"python",
"arrays",
"random",
"shuffle",
""
] |
Lately I've found myself constantly running ILDASM to study the MSIL output of my programs.
Are there any utilities to streamline this? Ideally, it would be nice to select some source code and have it compile, disassemble and emit the selected C# code in MSIL.
Anyone know of such a thing? | [.NET Reflector](http://www.red-gate.com/products/reflector/)
I think that [RedGate](http://www.red-gate.com/) have bought the IP to this tool now. I'm fairly sure that there is a VS plugin which integrates to it to allow you to run this from vs.
[.Net Reflector Plugin](http://www.testdriven.net/reflector/)
[](https://i.stack.imgur.com/RJ7yT.gif)
(source: [mutantdesign.co.uk](http://www.mutantdesign.co.uk/reflector/TestWithReflector.gif)) | You could use [testdriven.net](http://www.testdriven.net/) an awesome unit testing plugin that gives you the ability to right click on any member and view it in reflector. | Is there a tool to select some code in Visual Studio and have it show the corresponding MSIL? | [
"",
"c#",
".net",
"visual-studio",
"cil",
""
] |
I'm trying to access an XML file within a jar file, from a separate jar that's running as a desktop application. I can get the URL to the file I need, but when I pass that to a FileReader (as a String) I get a FileNotFoundException saying "The file name, directory name, or volume label syntax is incorrect."
As a point of reference, I have no trouble reading image resources from the same jar, passing the URL to an ImageIcon constructor. This seems to indicate that the method I'm using to get the URL is correct.
```
URL url = getClass().getResource("/xxx/xxx/xxx/services.xml");
ServicesLoader jsl = new ServicesLoader( url.toString() );
```
Inside the ServicesLoader class I have
```
XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler( this );
xr.setErrorHandler( this );
xr.parse( new InputSource( new FileReader( filename )));
```
What's wrong with using this technique to read the XML file? | The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above to
```
xr.parse( new InputSource( filename ));
```
works just fine. | Looks like you want to use `java.lang.Class.getResourceAsStream(String)`, see
<https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-> | How do I read a resource file from a Java jar file? | [
"",
"java",
"jar",
"resources",
""
] |
I have a couple of tables in a SQL 2008 server that I need to generate unique ID's for. I have looked at the "identity" column but the ID's really need to be unique and shared between all the tables.
So if I have say (5) five tables of the flavour "asset infrastructure" and I want to run with a unique ID between them as a combined group, I need some sort of generator that looks at all (5) five tables and issues the next ID which is not duplicated in any of those (5) five tales.
I know this could be done with some sort of stored procedure but I'm not sure how to go about it. Any ideas? | Why not use a GUID? | The simplest solution is to set your identity seeds and increment on each table so they never overlap.
Table 1: Seed 1, Increment 5
Table 2: Seed 2, Increment 5
Table 3: Seed 3, Increment 5
Table 4: Seed 4, Increment 5
Table 5: Seed 5, Increment 5
The identity column mod 5 will tell you which table the record is in. You will use up your identity space five times faster so make sure the datatype is big enough. | Generate unique ID to share with multiple tables SQL 2008 | [
"",
"sql",
"stored-procedures",
""
] |
How can I access dynamically properties from a generated LINQ class ?
Cause I would like to be able to customize the displayed table columns
where Partner is the LINQ Class generated from a SQL Server Database Table.
```
<table class="grid">
<thead>
<tr>
<% foreach (Column c in (IEnumerable)ViewData["columns"]) { %>
<th><%= c.Title %></th>
<% } %>
</tr>
</thead>
<tbody>
<% foreach (Partner p in (IEnumerable)ViewData.Model) { %>
<tr>
<% foreach (Column c in (IEnumerable)ViewData["columns"]) { %>
????? <th> <%= p.GetProperty(c.Name) %> </th> ?????
<% } %>
</tr>
<% } %>
</tbody>
</table>
```
Any idea how the code of the `p.GetProperty(c.Name)` method could look like ?
Forgive me if the Question is very simple but as I'm new to C# and LINQ I really
couldn't figure it out. | Reflection is a pretty good fit here, but really - everything is known at compile time. So it's possible to specify everything at design time.
```
public class DataItem
{
string Title {get;set;}
object Value {get;set;}
}
public interface IDataItems
{
IEnumerable<DataItem> Items()
}
//suppose LINQ gives you this:
public partial class Customer
{
public string Name {get;set;}
public string Address {get;set;}
public int Age {get;set;}
}
//then you add this in another file.
//if there's a lot of this, it can be code genned by design-time reflection
public partial class Customer : IDataItems
{
public IEnumerable<DataItem> IDataItems.Items()
{
yield return new DataItem() {"Name", Name};
yield return new DataItem() {"Address", Address};
yield return new DataItem() {"Age", Age};
}
}
//and the foreach loops look like this:
foreach(DataItem d in ViewData.OfType<IDataItems>().First().Items())
{
d.Title;
}
foreach(IDataItems container in ViewData.OfType<IDataItems>())
{
foreach(DataItem d in container.Items())
{
d.Value;
}
}
``` | Reflection should provide what you want - in particular,
```
typeof(Partner).GetProperty(c.Name).GetValue(p, null)
```
However, you might want to do this *before* the loop:
```
var columns = (IEnumerable<string>)ViewData["columns"];
var cols = columns.Select(colName =>
typeof(Partner).GetProperty(colName)).ToList();
```
This gives you a set of re-usable `PropertyInfo` instances that you can use per row:
```
foreach (var col in cols) { %>
<th><%= col.GetValue(p,null) %></th>
<% }
```
(should that `<th/>` be a `<td/>`, by the way?)
That should be a bit more efficient than repeatedly finding each property. There are [other ways of doing this too](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx) (faster again). | dynamic property access for generated LINQ Classes | [
"",
"c#",
"asp.net-mvc",
"linq",
""
] |
Please consider the following scenario:
```
map(T,S*) & GetMap(); //Forward decleration
map(T, S*) T2pS = GetMap();
for(map(T, S*)::iterator it = T2pS.begin(); it != T2pS.end(); ++it)
{
if(it->second != NULL)
{
delete it->second;
it->second = NULL;
}
T2pS.erase(it);
//In VS2005, after the erase, we will crash on the ++it of the for loop.
//In UNIX, Linux, this doesn't crash.
}//for
```
It seems to me that in VS2005, after the "erase", the iterator will be equal to end(), hence the crash while trying to increment it.
Are there really differences between compilers in the behavior presented here?
If so, what will the iterator after the "erase" equal to in UNIX/Linux?
Thanks... | Yes, if you erase an iterator, that iterator gets a so-called *singular value*, which means it doesn't belong to any container anymore. You can't increment, decrement or read it out/write to it anymore. The correct way to do that loop is:
```
for(map<T, S*>::iterator it = T2pS.begin(); it != T2pS.end(); T2pS.erase(it++)) {
// wilhelmtell in the comments is right: no need to check for NULL.
// delete of a NULL pointer is a no-op.
if(it->second != NULL) {
delete it->second;
it->second = NULL;
}
}
```
For containers that could invalidate other iterators when you erase one iterator, `erase` returns the next valid iterator. Then you do it with
```
it = T2pS.erase(it)
```
That's how it works for `std::vector` and `std::deque`, but not for `std::map` or `std::set`. | After you call `erase` on an iterator into a `std::map`, it is invalidated. This means that you cannot use it. Attempting to use it (e.g. by incrementing it) is invalid and can cause anything to happen (including a crash). For a `std::map`, calling `erase` on an iterator does not invalidate any other iterator so (for example) after this call, (so long as `it` was not `T2pS.end()`), it will be valid:
```
T2pS.erase( it++ );
```
Of course, if you use this approach, you won't want to unconditionally increment `it` in the for loop.
For this example, though, why bother to erase in the for loop? Why not just call T2pS.clear() at the end of the loop.
On the other hand, it looks like you have a raw pointer 'on the right' of the map, but the map appears to own the pointed to object. In this case, why not make the thing on the right of the map some sort of smart pointer, such as std::tr1::shared\_ptr?
[Incidentally, I don't see any template parameters to `map`. Have you typedef'ed a specific instantiation of `std::map` as `map` in the local namespace?] | What happens to an STL iterator after erasing it in VS, UNIX/Linux? | [
"",
"c++",
"linux",
"visual-studio-2005",
"stl",
"dictionary",
""
] |
I would like to embed a text file in an assembly so that I can load the text without having to read it from disk, and so that everything I need is contained within the exe. (So that it's more portable)
Is there a way to do this? I assume something with the resource files?
And if you can, how do you do it and how do you programaticaly load the text into a string? | Right-click the project file, select Properties.
In the window that opens, go to the Resources tab, and if it has just a blue link in the middle of the tab-page, click it, to create a new resource.

Then from the toolbar above the tab-page, select to add a new text file, give it a name, it will be added to your project and opened up.
If you get this far, then in your code you can type in Resources.TheNameYouGaveTheTextFileHere and you can access its contents. Note that the first time you use the Resources class in a class, you need to add a using directive (hit Ctrl+. after typing Resources to get the menu to get VS to do it for you).
If something was unclear about the above description, please leave a comment and I'll edit it until it is complete or makes sense :) | In Visual Studio 2003, Visual Studio 2005 and possibly earlier versions (this works in 2008 as well) you can include the text file in your project, then in the 'Properties' panel, set the action to 'Embedded Resource'. Then you can access the file as a stream using `Assembly.GetManifestResourceStream(string)`.
Other answers here are more convenient. I include this for completeness.
Note that this approach will work for embedding other types of files such as images, icons, sounds, etc... | How to embed a text file in a .NET assembly? | [
"",
"c#",
".net",
"embedded-resource",
""
] |
I want to take a floating point number in C++, like 2.25125, and a int array filled with the binary value that is used to store the float in memory (IEEE 754).
So I could take a number, and end up with a int num[16] array with the binary value of the float:
num[0] would be 1
num[1] would be 1
num[2] would be 0
num[3] would be 1
and so on...
Putting an int into an array isn't difficult, just the process of getting the binary value of a float is where I'm stuck. Can you just read the binary in the memory that the float variable? If not, how could I go about doing this in C++?
EDIT: The reason for doing the comparison this way is that I am wanting to learn to do bitwise operations in C++. | Use union and bitset:
```
#include <iostream>
#include <bitset>
#include <climits>
int main()
{
union
{
float input; // assumes sizeof(float) == sizeof(int)
int output;
} data;
data.input = 2.25125;
std::bitset<sizeof(float) * CHAR_BIT> bits(data.output);
std::cout << bits << std::endl;
// or
std::cout << "BIT 4: " << bits[4] << std::endl;
std::cout << "BIT 7: " << bits[7] << std::endl;
}
```
It may not be an array but you can access bits with [] operator as if you were using an array.
Output
```
$ ./bits
01000000000100000001010001111011
BIT 4: 1
BIT 7: 0
``` | ```
int fl = *(int*)&floatVar; //assuming sizeof(int) = sizeof(float)
int binaryRepresentation[sizeof(float) * 8];
for (int i = 0; i < sizeof(float) * 8; ++i)
binaryRepresentation[i] = ((1 << i) & fl) != 0 ? 1 : 0;
```
## Explanation
`(1 << i)` shifts the value `1`, `i` bits to the left.
The `&` operator computes the *bitwise and* of the operands.
The `for` loop runs once for each of the 32 bits in the float. Each time, `i` will be the number of the bit we want to extract the value from. We compute the bitwise and of the number and `1 << i`:
Assume the number is: 1001011, and `i = 2`
`1<<i` will be equal to 0000100
```
10001011
& 00000100
==========
00000000
```
if `i = 3` then:
```
10001011
& 00001000
==========
00001000
```
Basically, the result will be a number with `i`th bit set to the `i`th bit of the original number and all other bits are zero. The result will be either zero, which means the `i`th bit in the original number was zero or nonzero, which means the actual number had the `i`th bit equal to `1`. | Floating Point to Binary Value(C++) | [
"",
"c++",
"binary",
"floating-point",
"ieee-754",
""
] |
What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python — especially with respect to when I would want to use it, and when not? | > # In Python, what is the purpose of `__slots__` and what are the cases one should avoid this?
## TLDR:
The special attribute [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:
1. **faster** attribute access.
2. **space savings** in memory.
The space savings is from
1. Storing value references in slots instead of `__dict__`.
2. Denying [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__) and [`__weakref__`](https://stackoverflow.com/questions/36787603/what-exactly-is-weakref-in-python) creation if parent classes deny them and you declare `__slots__`.
### Quick Caveats
Small caveat, you should only declare a particular slot one time in an inheritance tree. For example:
```
class Base:
__slots__ = 'foo', 'bar'
class Right(Base):
__slots__ = 'baz',
class Wrong(Base):
__slots__ = 'foo', 'bar', 'baz' # redundant foo and bar
```
Python doesn't object when you get this wrong (it probably should), problems might not otherwise manifest, but your objects will take up more space than they otherwise should. Python 3.8:
```
>>> from sys import getsizeof
>>> getsizeof(Right()), getsizeof(Wrong())
(56, 72)
```
This is because the Base's slot descriptor has a slot separate from the Wrong's. This shouldn't usually come up, but it could:
```
>>> w = Wrong()
>>> w.foo = 'foo'
>>> Base.foo.__get__(w)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: foo
>>> Wrong.foo.__get__(w)
'foo'
```
The biggest caveat is for multiple inheritance - multiple "parent classes with nonempty slots" cannot be combined.
To accommodate this restriction, follow best practices: Factor out all but one or all parents' abstraction which their concrete class respectively and your new concrete class collectively will inherit from - giving the abstraction(s) empty slots (just like abstract base classes in the standard library).
See section on multiple inheritance below for an example.
### Requirements:
* To have attributes named in `__slots__` to actually be stored in slots instead of a `__dict__`, a class must inherit from `object` (automatic in Python 3, but must be explicit in Python 2).
* To prevent the creation of a `__dict__`, you must inherit from `object` and all classes in the inheritance must declare `__slots__` and none of them can have a `'__dict__'` entry.
There are a lot of details if you wish to keep reading.
## Why use `__slots__`: Faster attribute access.
The creator of Python, Guido van Rossum, [states](http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html) that he actually created `__slots__` for faster attribute access.
It is trivial to demonstrate measurably significant faster access:
```
import timeit
class Foo(object): __slots__ = 'foo',
class Bar(object): pass
slotted = Foo()
not_slotted = Bar()
def get_set_delete_fn(obj):
def get_set_delete():
obj.foo = 'foo'
obj.foo
del obj.foo
return get_set_delete
```
and
```
>>> min(timeit.repeat(get_set_delete_fn(slotted)))
0.2846834529991611
>>> min(timeit.repeat(get_set_delete_fn(not_slotted)))
0.3664822799983085
```
The slotted access is almost 30% faster in Python 3.5 on Ubuntu.
```
>>> 0.3664822799983085 / 0.2846834529991611
1.2873325658284342
```
In Python 2 on Windows I have measured it about 15% faster.
## Why use `__slots__`: Memory Savings
Another purpose of `__slots__` is to reduce the space in memory that each object instance takes up.
[My own contribution to the documentation clearly states the reasons behind this](https://docs.python.org/3/reference/datamodel.html#slots):
> The space saved over using `__dict__` can be significant.
[SQLAlchemy attributes](http://docs.sqlalchemy.org/en/rel_1_0/changelog/migration_10.html#significant-improvements-in-structural-memory-use) a lot of memory savings to `__slots__`.
To verify this, using the Anaconda distribution of Python 2.7 on Ubuntu Linux, with `guppy.hpy` (aka heapy) and `sys.getsizeof`, the size of a class instance without `__slots__` declared, and nothing else, is 64 bytes. That does *not* include the `__dict__`. Thank you Python for lazy evaluation again, the `__dict__` is apparently not called into existence until it is referenced, but classes without data are usually useless. When called into existence, the `__dict__` attribute is a minimum of 280 bytes additionally.
In contrast, a class instance with `__slots__` declared to be `()` (no data) is only 16 bytes, and 56 total bytes with one item in slots, 64 with two.
For 64 bit Python, I illustrate the memory consumption in bytes in Python 2.7 and 3.6, for `__slots__` and `__dict__` (no slots defined) for each point where the dict grows in 3.6 (except for 0, 1, and 2 attributes):
```
Python 2.7 Python 3.6
attrs __slots__ __dict__* __slots__ __dict__* | *(no slots defined)
none 16 56 + 272† 16 56 + 112† | †if __dict__ referenced
one 48 56 + 272 48 56 + 112
two 56 56 + 272 56 56 + 112
six 88 56 + 1040 88 56 + 152
11 128 56 + 1040 128 56 + 240
22 216 56 + 3344 216 56 + 408
43 384 56 + 3344 384 56 + 752
```
So, in spite of smaller dicts in Python 3, we see how nicely `__slots__` scale for instances to save us memory, and that is a major reason you would want to use `__slots__`.
Just for completeness of my notes, note that there is a one-time cost per slot in the class's namespace of 64 bytes in Python 2, and 72 bytes in Python 3, because slots use data descriptors like properties, called "members".
```
>>> Foo.foo
<member 'foo' of 'Foo' objects>
>>> type(Foo.foo)
<class 'member_descriptor'>
>>> getsizeof(Foo.foo)
72
```
## Demonstration of `__slots__`:
To deny the creation of a `__dict__`, you must subclass `object`. Everything subclasses `object` in Python 3, but in Python 2 you had to be explicit:
```
class Base(object):
__slots__ = ()
```
now:
```
>>> b = Base()
>>> b.a = 'a'
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
b.a = 'a'
AttributeError: 'Base' object has no attribute 'a'
```
Or subclass another class that defines `__slots__`
```
class Child(Base):
__slots__ = ('a',)
```
and now:
```
c = Child()
c.a = 'a'
```
but:
```
>>> c.b = 'b'
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
c.b = 'b'
AttributeError: 'Child' object has no attribute 'b'
```
To allow `__dict__` creation while subclassing slotted objects, just add `'__dict__'` to the `__slots__` (note that slots are ordered, and you shouldn't repeat slots that are already in parent classes):
```
class SlottedWithDict(Child):
__slots__ = ('__dict__', 'b')
swd = SlottedWithDict()
swd.a = 'a'
swd.b = 'b'
swd.c = 'c'
```
and
```
>>> swd.__dict__
{'c': 'c'}
```
Or you don't even need to declare `__slots__` in your subclass, and you will still use slots from the parents, but not restrict the creation of a `__dict__`:
```
class NoSlots(Child): pass
ns = NoSlots()
ns.a = 'a'
ns.b = 'b'
```
And:
```
>>> ns.__dict__
{'b': 'b'}
```
However, `__slots__` may cause problems for multiple inheritance:
```
class BaseA(object):
__slots__ = ('a',)
class BaseB(object):
__slots__ = ('b',)
```
Because creating a child class from parents with both non-empty slots fails:
```
>>> class Child(BaseA, BaseB): __slots__ = ()
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
class Child(BaseA, BaseB): __slots__ = ()
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict
```
If you run into this problem, You *could* just remove `__slots__` from the parents, or if you have control of the parents, give them empty slots, or refactor to abstractions:
```
from abc import ABC
class AbstractA(ABC):
__slots__ = ()
class BaseA(AbstractA):
__slots__ = ('a',)
class AbstractB(ABC):
__slots__ = ()
class BaseB(AbstractB):
__slots__ = ('b',)
class Child(AbstractA, AbstractB):
__slots__ = ('a', 'b')
c = Child() # no problem!
```
### Add `'__dict__'` to `__slots__` to get dynamic assignment:
```
class Foo(object):
__slots__ = 'bar', 'baz', '__dict__'
```
and now:
```
>>> foo = Foo()
>>> foo.boink = 'boink'
```
So with `'__dict__'` in slots we lose some of the size benefits with the upside of having dynamic assignment and still having slots for the names we do expect.
When you inherit from an object that isn't slotted, you get the same sort of semantics when you use `__slots__` - names that are in `__slots__` point to slotted values, while any other values are put in the instance's `__dict__`.
Avoiding `__slots__` because you want to be able to add attributes on the fly is actually not a good reason - just add `"__dict__"` to your `__slots__` if this is required.
You can similarly add `__weakref__` to `__slots__` explicitly if you need that feature.
### Set to empty tuple when subclassing a namedtuple:
The namedtuple builtin make immutable instances that are very lightweight (essentially, the size of tuples) but to get the benefits, you need to do it yourself if you subclass them:
```
from collections import namedtuple
class MyNT(namedtuple('MyNT', 'bar baz')):
"""MyNT is an immutable and lightweight object"""
__slots__ = ()
```
usage:
```
>>> nt = MyNT('bar', 'baz')
>>> nt.bar
'bar'
>>> nt.baz
'baz'
```
And trying to assign an unexpected attribute raises an `AttributeError` because we have prevented the creation of `__dict__`:
```
>>> nt.quux = 'quux'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyNT' object has no attribute 'quux'
```
You *can* allow `__dict__` creation by leaving off `__slots__ = ()`, but you can't use non-empty `__slots__` with subtypes of tuple.
## Biggest Caveat: Multiple inheritance
Even when non-empty slots are the same for multiple parents, they cannot be used together:
```
class Foo(object):
__slots__ = 'foo', 'bar'
class Bar(object):
__slots__ = 'foo', 'bar' # alas, would work if empty, i.e. ()
>>> class Baz(Foo, Bar): pass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict
```
Using an empty `__slots__` in the parent seems to provide the most flexibility, **allowing the child to choose to prevent or allow** (by adding `'__dict__'` to get dynamic assignment, see section above) **the creation of a `__dict__`**:
```
class Foo(object): __slots__ = ()
class Bar(object): __slots__ = ()
class Baz(Foo, Bar): __slots__ = ('foo', 'bar')
b = Baz()
b.foo, b.bar = 'foo', 'bar'
```
You don't *have* to have slots - so if you add them, and remove them later, it shouldn't cause any problems.
**Going out on a limb here**: If you're composing [mixins](https://stackoverflow.com/questions/860245/mixin-vs-inheritance/27907511#27907511) or using [abstract base classes](https://stackoverflow.com/questions/372042/difference-between-abstract-class-and-interface-in-python/31439126#31439126), which aren't intended to be instantiated, an empty `__slots__` in those parents seems to be the best way to go in terms of flexibility for subclassers.
To demonstrate, first, let's create a class with code we'd like to use under multiple inheritance
```
class AbstractBase:
__slots__ = ()
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return f'{type(self).__name__}({repr(self.a)}, {repr(self.b)})'
```
We could use the above directly by inheriting and declaring the expected slots:
```
class Foo(AbstractBase):
__slots__ = 'a', 'b'
```
But we don't care about that, that's trivial single inheritance, we need another class we might also inherit from, maybe with a noisy attribute:
```
class AbstractBaseC:
__slots__ = ()
@property
def c(self):
print('getting c!')
return self._c
@c.setter
def c(self, arg):
print('setting c!')
self._c = arg
```
Now if both bases had nonempty slots, we couldn't do the below. (In fact, if we wanted, we could have given `AbstractBase` nonempty slots a and b, and left them out of the below declaration - leaving them in would be wrong):
```
class Concretion(AbstractBase, AbstractBaseC):
__slots__ = 'a b _c'.split()
```
And now we have functionality from both via multiple inheritance, and can still deny `__dict__` and `__weakref__` instantiation:
```
>>> c = Concretion('a', 'b')
>>> c.c = c
setting c!
>>> c.c
getting c!
Concretion('a', 'b')
>>> c.d = 'd'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Concretion' object has no attribute 'd'
```
## Other cases to avoid slots:
* Avoid them when you want to perform `__class__` assignment with another class that doesn't have them (and you can't add them) unless the slot layouts are identical. (I am very interested in learning who is doing this and why.)
* Avoid them if you want to subclass variable length builtins like long, tuple, or str, and you want to add attributes to them.
* Avoid them if you insist on providing default values via class attributes for instance variables.
You may be able to tease out further caveats from the rest of the `__slots__` [documentation (the 3.7 dev docs are the most current)](https://docs.python.org/3.7/reference/datamodel.html#slots), which I have made significant recent contributions to.
## Critiques of other answers
The current top answers cite outdated information and are quite hand-wavy and miss the mark in some important ways.
### Do not "only use `__slots__` when instantiating lots of objects"
I quote:
> "You would want to use `__slots__` if you are going to instantiate a lot (hundreds, thousands) of objects of the same class."
Abstract Base Classes, for example, from the `collections` module, are not instantiated, yet `__slots__` are declared for them.
Why?
If a user wishes to deny `__dict__` or `__weakref__` creation, those things must not be available in the parent classes.
`__slots__` contributes to reusability when creating interfaces or mixins.
It is true that many Python users aren't writing for reusability, but when you are, having the option to deny unnecessary space usage is valuable.
### `__slots__` doesn't break pickling
When pickling a slotted object, you may find it complains with a misleading `TypeError`:
```
>>> pickle.loads(pickle.dumps(f))
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled
```
This is actually incorrect. This message comes from the oldest protocol, which is the default. You can select the latest protocol with the `-1` argument. In Python 2.7 this would be `2` (which was introduced in 2.3), and in 3.6 it is `4`.
```
>>> pickle.loads(pickle.dumps(f, -1))
<__main__.Foo object at 0x1129C770>
```
in Python 2.7:
```
>>> pickle.loads(pickle.dumps(f, 2))
<__main__.Foo object at 0x1129C770>
```
in Python 3.6
```
>>> pickle.loads(pickle.dumps(f, 4))
<__main__.Foo object at 0x1129C770>
```
So I would keep this in mind, as it is a solved problem.
## Critique of the (until Oct 2, 2016) accepted answer
The first paragraph is half short explanation, half predictive. Here's the only part that actually answers the question
> The proper use of `__slots__` is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots
The second half is wishful thinking, and off the mark:
> While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.
Python actually does something similar to this, only creating the `__dict__` when it is accessed, but creating lots of objects with no data is fairly ridiculous.
The second paragraph oversimplifies and misses actual reasons to avoid `__slots__`. The below is *not* a real reason to avoid slots (for *actual* reasons, see the rest of my answer above.):
> They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies.
It then goes on to discuss other ways of accomplishing that perverse goal with Python, not discussing anything to do with `__slots__`.
The third paragraph is more wishful thinking. Together it is mostly off-the-mark content that the answerer didn't even author and contributes to ammunition for critics of the site.
# Memory usage evidence
Create some normal objects and slotted objects:
```
>>> class Foo(object): pass
>>> class Bar(object): __slots__ = ()
```
Instantiate a million of them:
```
>>> foos = [Foo() for f in xrange(1000000)]
>>> bars = [Bar() for b in xrange(1000000)]
```
Inspect with `guppy.hpy().heap()`:
```
>>> guppy.hpy().heap()
Partition of a set of 2028259 objects. Total size = 99763360 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1000000 49 64000000 64 64000000 64 __main__.Foo
1 169 0 16281480 16 80281480 80 list
2 1000000 49 16000000 16 96281480 97 __main__.Bar
3 12284 1 987472 1 97268952 97 str
...
```
Access the regular objects and their `__dict__` and inspect again:
```
>>> for f in foos:
... f.__dict__
>>> guppy.hpy().heap()
Partition of a set of 3028258 objects. Total size = 379763480 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1000000 33 280000000 74 280000000 74 dict of __main__.Foo
1 1000000 33 64000000 17 344000000 91 __main__.Foo
2 169 0 16281480 4 360281480 95 list
3 1000000 33 16000000 4 376281480 99 __main__.Bar
4 12284 0 987472 0 377268952 99 str
...
```
This is consistent with the history of Python, from [Unifying types and classes in Python 2.2](https://www.python.org/download/releases/2.2.2/descrintro/)
> If you subclass a built-in type, extra space is automatically added to the instances to accomodate `__dict__` and `__weakrefs__`. (The `__dict__` is not initialized until you use it though, so you shouldn't worry about the space occupied by an empty dictionary for each instance you create.) If you don't need this extra space, you can add the phrase "`__slots__ = []`" to your class. | Quoting [Jacob Hallen](http://code.activestate.com/lists/python-list/531365/):
> The proper use of `__slots__` is to save space in objects. Instead of having
> a dynamic dict that allows adding attributes to objects at anytime,
> there is a static structure which does not allow additions after creation.
> [This use of `__slots__` eliminates the overhead of one dict for every object.] While this is sometimes a useful optimization, it would be completely
> unnecessary if the Python interpreter was dynamic enough so that it would
> only require the dict when there actually were additions to the object.
>
> Unfortunately there is a side effect to slots. They change the behavior of
> the objects that have slots in a way that can be abused by control freaks
> and static typing weenies. This is bad, because the control freaks should
> be abusing the metaclasses and the static typing weenies should be abusing
> decorators, since in Python, there should be only one obvious way of doing something.
>
> Making CPython smart enough to handle saving space without `__slots__` is a major
> undertaking, which is probably why it is not on the list of changes for P3k (yet). | Usage of __slots__? | [
"",
"python",
"oop",
"python-internals",
"slots",
""
] |
I want to generate a dict with the letters of the alphabet as the keys, something like
```
letter_count = {'a': 0, 'b': 0, 'c': 0}
```
what would be a fast way of generating that dict, rather than me having to type it in? | I find this solution elegant:
```
import string
d = dict.fromkeys(string.ascii_lowercase, 0)
print(d)
# {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}
``` | ```
import string
letter_count = dict(zip(string.ascii_lowercase, [0]*26))
print(letter_count)
# {'a': 0, 'b': 0, 'c': 0, ... 'x': 0, 'y': 0, 'z': 0}
```
or maybe:
```
import string
import itertools
letter_count = dict(zip(string.ascii_lowercase, itertools.repeat(0)))
print(letter_count)
# {'a': 0, 'b': 0, 'c': 0, ... 'x': 0, 'y': 0, 'z': 0}
```
or even:
```
import string
letter_count = dict.fromkeys(string.ascii_lowercase, 0)
print(letter_count)
# {'a': 0, 'b': 0, 'c': 0, ... 'x': 0, 'y': 0, 'z': 0}
```
The preferred solution might be a different one, depending on the actual values you want in the dict.
---
I'll take a guess here: do you want to count occurences of letters in a text (or something similar)? There is a better way to do this than starting with an initialized dictionary.
Use `Counter` from the `collections` module:
```
import collections
the_text = 'the quick brown fox jumps over the lazy dog'
letter_counts = collections.Counter(the_text)
print(letter_counts)
# Counter({' ': 8, 'o': 4, 'e': 3, ... 'n': 1, 'x': 1, 'k': 1, 'b': 1})
``` | Is there a fast way to generate a dict of the alphabet in Python? | [
"",
"python",
"dictionary",
"alphabet",
""
] |
How do I generate 30 random numbers between 1-9, that all add up to 200 (or some arbitrary N), in C#?
I'm trying to generate a string of digits that can add together to be N. | I'm not sure what the statistics are on this but, the issue here is that you don't want to randomly select a number that makes it impossible to sum N with M number of entries either by overshooting or undershooting. Here's how I would do it:
```
static void Main()
{
int count = 30;
int[] numbers = getNumbers(count, 155);
for (int index = 0; index < count; index++)
{
Console.Write(numbers[index]);
if ((index + 1) % 10 == 0)
Console.WriteLine("");
else if (index != count - 1)
Console.Write(",");
}
Console.ReadKey();
}
static int[] getNumbers(int count, int total)
{
const int LOWERBOUND = 1;
const int UPPERBOUND = 9;
int[] result = new int[count];
int currentsum = 0;
int low, high, calc;
if((UPPERBOUND * count) < total ||
(LOWERBOUND * count) > total ||
UPPERBOUND < LOWERBOUND)
throw new Exception("Not possible.");
Random rnd = new Random();
for (int index = 0; index < count; index++)
{
calc = (total - currentsum) - (UPPERBOUND * (count - 1 - index));
low = calc < LOWERBOUND ? LOWERBOUND : calc;
calc = (total - currentsum) - (LOWERBOUND * (count - 1 - index));
high = calc > UPPERBOUND ? UPPERBOUND : calc;
result[index] = rnd.Next(low, high + 1);
currentsum += result[index];
}
// The tail numbers will tend to drift higher or lower so we should shuffle to compensate somewhat.
int shuffleCount = rnd.Next(count * 5, count * 10);
while (shuffleCount-- > 0)
swap(ref result[rnd.Next(0, count)], ref result[rnd.Next(0, count)]);
return result;
}
public static void swap(ref int item1, ref int item2)
{
int temp = item1;
item1 = item2;
item2 = temp;
}
```
I didn't have a lot of time to test this so apologies if there's a flaw in my logic somewhere.
EDIT:
I did some testing and everything seems solid. If you want a nice pretty spread it looks like you want something along the lines of `Total = Count * ((UPPER + LOWER) / 2)`. Although I'm fairly certain that as the difference between `UPPER` and `LOWER` increases the more flexible this becomes. | The problem is we want all numbers to be bounded 1-9 **and** add up to N. So we have to generate each number one by one and determine the real bounds for the next number.
This will of course generate statistical bias toward the end of the list, so I recommend shuffling the array once after generating.
To determine the next number's bounds, do the following: Upper bound = take the remaining sum minus (the number of elements remaining \* min). Lower bound = take the remaining sum minus (the number of elements remaining \* max).
Something like (untested):
```
public static List<int> RandomList(int digitMin, int digitMax,
int targetSum, int numDigits)
{
List<int> ret = new List<int>(numDigits);
Random random = new Random();
int localMin, localMax, nextDigit;
int remainingSum = targetSum;
for(int i=1; i<=numDigits; i++)
{
localMax = remainingSum - ((numDigits - i) * min);
if(localMax > max)
localMax = max;
localMin = remainingSum - ((length - i) * max);
if(localMin > min)
localMin = min;
nextDigit = random.Next(localMin, localMax);
ret.Add(nextDigit);
remainingSum -= nextDigit;
}
return ret;
}
```
The idea here is as you generate numbers, the range of possible values for the remaining numbers gets smaller, like a limit function zeroing in on a target sum. Sort of.
Edit: I had to change the for loop to be 1-based, because we want the number of elements left AFTER generating this one.
Edit2: Put it in a method for completeness and changed `length` to be `numDigits` for readability. | Generate a series of random numbers that add up to N in c# | [
"",
"c#",
".net",
"random",
""
] |
Is there a way to use the `new` keyword to allocate on the stack (ala `alloca`) instead of heap (`malloc`) ?
I know I could hack up my own but I'd rather not. | To allocate on the stack, either declare your object as a local variable *by value*, or you can actually use alloca to obtain a pointer and then use the in-place new operator:
```
void *p = alloca(sizeof(Whatever));
new (p) Whatever(constructorArguments);
```
However, while using alloca and in-place new ensures that the memory is freed on return, you give up automatic destructor calling. If you're just trying to ensure that the memory is freed upon exit from the scope, consider using `std::auto_ptr<T>` or some other smart pointer type. | Jeffrey Hantin is quite correct that you can use placement new to create it on the stack with alloca. But, seriously, why?! Instead, just do:
```
class C { /* ... */ };
void func() {
C var;
C *ptr = &var;
// do whatever with ptr
}
```
You now have a pointer to an object allocated on the stack. And, it'll properly be destroyed when your function exists. | new on stack instead of heap (like alloca vs malloc) | [
"",
"c++",
"stack",
"new-operator",
""
] |
I'm currently writing a quick solution for Euler Problem #4 where one must find the largest palindromic number from the product of two 3-digit numbers.
To identify if a number is palindromic, you would obviously compare a reverse of the number with the original.
**Since C# doesn't have a built in String.Reverse() method, what is the quickest way to reverse a string?**
*I will be testing all the suggested solution in a loop with 100,000,000 iterations. The correct answer will be given to the person who submitted the fastest solution.*
*I will be testing the solution in a C#.Net 3.5 console application* | I think it might be faster to do the comparison in-place. If you reverse the string, you've got to:
1. Instantiate a new string object (or StringBuffer object)
2. Copy the data (in reverse) from the first string to the new string
3. Do your comparison.
If you perform the comparison in place, you do only the last step. An even then, your comparison is only half the string (or half - 0.5, in the event of an odd number of characters). Something like the following should work:
```
static bool IsPalindromic(string s){
int len = s.Length;
int half = len-- >> 1;
for(int i = 0; i < half; i++)
if(s[i] != s[len - i])
return false;
return true;
}
```
**EDIT:**
Although this answers the OP's question, the solutions offered by [ggf31416](https://stackoverflow.com/questions/433211/quickest-method-to-reverse-in-string-in-c-net#433257) and [configurator](https://stackoverflow.com/questions/433211/quickest-method-to-reverse-in-string-in-c-net#433260) solve the OP's real need about 30% faster, by my tests. configurator's solution is a tiny bit faster than ggf31416's, if you convert it to a static method and use `int`s instead of `ulong`s (but much slower, otherwise).
---
Incidentally, running through these examples to solve the problem the OP mentions (finding the largest palindromic product of any two three-digit numbers) with the simple (perhaps naïve) loop below:
```
for(int i = 100; i < 1000; i++)
for(int j = i; j < 1000; j++) // calculations where j < i would be redundant
...
```
yields the following results on my machine:
```
IsPalindromic(product.ToString()) took 0.3064174 seconds.
ggf31416Reverse(product) == product took 0.1933994 seconds.
configuratorReverse(product) == product took 0.1872061 seconds.
```
Each produces the correct result of `913 * 993 = 906609`. | Wouldn't reversing the number be faster?
```
// unchecked code, don't kill me if it doesn't even compile.
ulong Reverse(ulong number) {
ulong result = 0;
while (number > 0) {
ulong digit = number % 10;
result = result * 10 + digit;
number /= 10;
}
return result;
}
``` | Quickest Method to Reverse in String in C#.net | [
"",
"c#",
""
] |
I have a question concerning this code which I want to run on QNX:
```
class ConcreteThread : public Thread
{
public:
ConcreteThread(int test)
{
testNumber = test;
}
void *start_routine()
{
for(int i = 0; i < 10; i++)
{
sleep(1);
cout << testNumber << endl;
}
}
private:
int testNumber;
};
class Thread
{
public:
Thread(){};
int Create()
{
pthread_t m_id;
return pthread_create(&m_id, NULL, &(this->start_routine_trampoline), this);
}
protected:
virtual void *start_routine() = 0;
private:
static void *start_routine_trampoline(void *p)
{
Thread *pThis = (Thread *)p;
return pThis->start_routine();
}
};
```
Now, when I run this code without the sleep in \*start\_routine, it will simply print the number 10 times, before continuing on to the next line of code (sequential instead of parallel). However, when I use a sleep like in the code, it doesn't print any numbers at all and simply goes on to the next line of code. Why doesn't sleep work and how can I make a thread like this work, instead of running sequential? | Note 1: If you only have 1 processor the code can only be done sequentially no matter how many threads you create. Each thread is given a slice of processor time before it is swapped out for the next threads.
Note 2: If the main thread exits pthreads will kill all child threads before they have a chance to execute.
Now to answer you questions:
Without the sleep. The thread once started has enough time in the single slice it was given to execute the loop 10 times completely.
With the sleep: Your worker thread is going to sleep for a full second. So your main thread has time to do a lot of work. If the main thread exits in this time the worker will be killed.
I would make the following changes:
```
// Remove the Create() method
// Put thread creation in the constructor.
// Make the thread variable part of the object
pthread_t m_id;
Thread()
{
if (pthread_create(&m_id, NULL, &(this->start_routine_trampoline), this) != 0)
{
throw std::runtime_error("Thread was not created");
}
}
// Make sure the destructor waits for the thread to exit.
~Thread()
{
pthread_join(m_id);
}
```
If you go and look at **boost threading** library. you will find that all the little mistakes like this have already been taken care of; Thus making threading easier to use.
Also note. That using a static may work but it is non portable. This is because pthread's is a C library and is thus expecting a function pointer with a C ABI. You are just getting lucky for your platform here. You need to define this as a function and declare the ABI by using extern "C"
```
// This needs to be a standard function with C Interface.
extern "C" void *start_routine_trampoline(void *p)
{
}
``` | Try to make the pthread\_t id a class member instead of a function local variable. That way the caller can pthread\_join it.
Not doing this is technically a resource leak (unless the thread is specifically not joinable). And joining will avoid the issue that [Martin York](https://stackoverflow.com/questions/433220/qnx-c-thread-question#433269) described.
From man pthread\_join:
> The joined thread th must be in the joinable state: it must not have
> been detached using pthread\_detach(3) or the PTHREAD\_CREATE\_DETACHED
> attribute to pthread\_create(3).
>
> When a joinable thread terminates, its memory resources (thread
> descriptor and stack) are not deallocated until another thread performs
> pthread\_join on it. Therefore, pthread\_join must be called once for
> each joinable thread created to avoid memory leaks. | QNX c++ thread question | [
"",
"c++",
"multithreading",
"qnx",
""
] |
We are getting this error on starting tomcat (both as a service and via command line):
```
This release of Apache Tomcat was packaged to run on J2SE 5.0
or later. It can be run on earlier JVMs by downloading and
installing a compatibility package from the Apache Tomcat
binary download page.
```
We have the version with a tomcat5.exe and tomcat5w.exe - no bat files :(
The path only has jdk5 on it:
```
Path=f:\Program Files\Java\jdk1.5.0_06\bin;C:\WINDOWS\System32
```
We are using Tomcat5.5, with jdk 1.5.0\_06 installed on the same machine.
```
java version "1.5.0_06"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
```
The JAVA\_HOME also points to the same version:
```
F:\Development\Program Files\Apache Software Foundation\Tomcat 5.5\bin>set j
JAVA_HOME=f:\Program Files\Java\jdk1.5.0_06
```
Any tips on where I am going wrong?
Thanks
Chris | You only have the exe version and not the bat files, because you've downloaded the Windows Installer and not the zip file. The bat files are only included in the zip file. You can download the zip and copy the bat files to the bin directory. No need to uninstall.
I bet that you have a PATH problem. Check if there is an old version of Java in a system directory. Also, make sure that you modify the PATH system wide and not per command line session. | You can configure a different version of Java in the start.bat file. The same goes for the service (but in a different place).
I suggest to add an `echo %JAVA_HOME%` (if you use the start.bat) to see what is really happening.
If you use the service, open the properties for the service (use the icon tomcat puts in the systray). On the tab "Java", you'll find the JVM which the service uses. | tomcat error - "This release of Apache Tomcat was packaged to run on J2SE 5.0" | [
"",
"java",
"tomcat",
""
] |
I've been struggling with this for the past couple hours now and I really don't know what could be wrong. I'm simply trying to get Javascript to communicate text with Flash. I found this great example with this source
<http://blog.circlecube.com/wp-content/uploads/2008/02/ActionscriptJavascriptCommunication.zip>
I ran the html file locally and it works just fine sending and retrieving text from flash. Then I load that same exact sample into my dev google app server and I can't send the text from javascript to flash. Oddly enough though flash is able to send Javascript text. Can anybody see if they can get this running with GAE? Thanks a million! | I do not see a call to the allowDomain function in your code. With out that the security sandbox will not allow your flash application to communicate with flash and vice versa on the server. Add a call to `System.security.allowDomain("mydomain.com", "mySecondDomain.com", "etc.com")` for every domain the flash app will be executed on. Also the embed code also needs to specify access for JavaScript by including the parameter `<param name="allowScriptAccess" value="always" />`. | It probably doesn't have to do with Google app engine per se, since the whole thing's running in the browser -- unless there's some sort of server dependency somewhere you haven't mentioned. Assuming that's not the case...
If you're able to get Flash to call into JavaScript with ExternalInterface.call(), but not JavaScript to call back into Flash, then it's probably one or two things: your EI callback & handler aren't wired up properly (in Flash), or your JavaScript doesn't have a handle on the SWF object in the browser.
You might try posting some code, but in the meantime, here's something I know works in both IE and FireFox. First, the browser code:
```
<html>
<head>
<script language="JavaScript" type="text/javascript">
var swfReady = false;
function callbacksInitialized()
{
swfReady = true;
}
function helloFlash()
{
if (swfReady)
{
// Get a handle on the Flash object
var swfObject = navigator.appName.indexOf("Microsoft") != -1 ? window["HelloMac"] : document["HelloMac"] ;
// Call back into the Flash file
swfObject.helloFlash(document.getElementById("txtMessage").value);
}
}
function helloMac(message)
{
alert(message);
}
</script>
</head>
<body scroll="no">
<div align="center">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="HelloMac" width="600" height="300"
codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
<param name="movie" value="HelloMac.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#869ca7" />
<param name="allowScriptAccess" value="sameDomain" />
<embed src="HelloMac.swf" quality="high" bgcolor="#869ca7"
width="600" height="300" name="HelloMac" align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer">
</embed>
</object>
<br /><br />
<input type="text" id="txtMessage" value="Hello, Flash!" /><br />
<input id="btnSend" type="button" value="Send to Flash" onclick="helloFlash();" />
</div>
</body>
</html>
```
And now, the Flash code (in my case, it's Flex, so hopefully it's clear):
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()" height="300" width="600">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.external.ExternalInterface;
private function init():void
{
addCallbacks();
}
private function addCallbacks():void
{
ExternalInterface.addCallback("helloFlash", this_helloFlash);
ExternalInterface.call("callbacksInitialized");
}
// Display a message from the host
private function this_helloFlash(message:String):void
{
Alert.show(message);
}
// Send a string to the host
private function helloMac():void
{
if (ExternalInterface.available)
{
ExternalInterface.call("helloMac", txtMessage.text);
}
}
]]>
</mx:Script>
<mx:VBox horizontalCenter="0" verticalCenter="0">
<mx:TextInput id="txtMessage" text="Hello, Mac!" />
<mx:Button id="btnSend" label="Send to Host" click="helloMac()" />
</mx:VBox>
</mx:Application>
```
The example demonstrates Flash calling into JavaScript with some text, and JavaScript calling back into Flash in the same way. Some points to pay attention to:
* Make sure you **wait** to call into
Flash until Flash has notified the
browser it's ready to begin receiving
calls (as indicated by my
callbacksInitialized() method).
* Test to be sure you're using the
appropriate browser-specific object
reference (e.g., window["HelloMac"]
vs. document["HelloMac"]).
Without knowing more, I'm guessing it's one of these two items, since that's been my experience. Hope it helps! I'll keep an eye on the post for follow-ups in case you have any. | Problem with Flash ExternalInterface on Google App Engine | [
"",
"javascript",
"flash",
"google-app-engine",
""
] |
In firefox, I have the following fragment in my .css file
```
tree (negative){ font-size: 120%; color: green;}
```
Using javascript, how do I change the **rule**, to set the color to red?
**NOTE:
I do not want to change the element.
I want to change the rule.
Please do not answer with something like**
...
element.style.color = 'red'; | What you're looking for is the `document.styleSheets` property, through which you can access your css rules and manipulate them. Most browsers have this property, however the interface is slightly different for IE.
For example, try pasting the following in FF for this page and pressing enter:
```
javascript:alert(document.styleSheets[0].cssRules[1].cssText)
```
For me that yields the string `"body { line-height: 1; }"`. There are methods/properties that allow you to manipulate the rules.
Here's a library that abstracts this interface for you (cross-browser): <http://code.google.com/p/sheetup/> | ```
function changeCSSRule (stylesheetID, selectorName, replacementRules) {
var i, theStylesheet = document.getElementById(stylesheetID).sheet,
thecss = (theStylesheet.cssRules) ? theStylesheet.cssRules : theStylesheet.rules;
for(i=0; i < thecss.length; i++){
if(thecss[i].selectorText == selectorName) {
thecss[i].style.cssText = replacementRules;
}
}
};
``` | In firefox, how can I change an existing CSS rule | [
"",
"javascript",
"css",
"firefox",
""
] |
This is easy for non-inlines. Just override the following in the your admin.py AdminOptions:
```
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'photo':
kwargs['widget'] = AdminImageWidget()
return db_field.formfield(**kwargs)
return super(NewsOptions,self).formfield_for_dbfield(db_field,**kwargs)
```
I can't work out how to adapt this to work for inlines. | It works exactly the same way. The TabularInline and StackedInline classes also have a formfield\_for\_dbfield method, and you override it the same way in your subclass. | Since Django 1.1, formfield\_overrides is also working
```
formfield_overrides = {
models.ImageField: {'widget': AdminImageWidget},
}
``` | How do I add a custom inline admin widget in Django? | [
"",
"python",
"django",
"django-admin",
""
] |
I am working on an application that will be used as an extensible framework for other applications.
One of the fundamental classes is called Node, and Nodes have Content. The SQL tables look like this:
TABLE Node ( NodeId int, .... etc )
TABLE NodeContentRelationship ( NodeId int, ContentType string, ContentId int)
It will be up to the developers extending the application to create their own content types.
Clearly this is bad from a relationship-database point of view as it is not possible to add a foreign key relationship to NodeContentRelationship.ContentId, even though it *is* a foreign key column.
However, the solution is quite simple and powerful so I am reluctant to change it.
What do you think - am I in for a world of pain down the track? | Why is it impossible to set `NoteContentRelationship.ContentId` as a foreign key? You can easily use a relational inheritance model with a table `Content` representing an abstract base class, and various tables `AnimalContent`, `CarContent`, etc. representing derived classes. | Beware the [Inner Platform Effect](http://thedailywtf.com/Articles/The_Inner-Platform_Effect.aspx).
If you're trying to build an 'extensible framework' which allows developers to store data of different 'content types' and relate them to each other in a generic fashion, you may find that others have already [solved](http://www.microsoft.com/sqlserver/2008/en/us/default.aspx) [this](http://www.oracle.com/index.html) [problem](http://www.mysql.com/). | SQL : one foreign key references primary key in one of several tables | [
"",
"sql",
"database",
"foreign-keys",
"relationship",
""
] |
I have a very large Ruby on Rails application that I would like to port to PHP 5.2 or maybe PHP 5.3 (if 5.3 ever gets released).
I've been looking for a some way of automatically converting the simple stuff like simple classes and the ERB templates. I would expect that I'd have to do the more complicated stuff myself in cases where the languages are just too dissimilar.
Can anyone suggest an approach for doing this? Or a script that can automate some of it?
**EDIT:**
There is a business case for doing this. Whether it is a sound business case is another issue which I don't care to discuss here. We have a framework that is similar enough to Rails - the real issue is conversion from Ruby to PHP rather than Rails to PHP. I'm not really looking for something that will magically do all the work, just something simple that will give a headstart. Even if all it did was change:
```
def somemethod somearg
some.ruby.code
end
```
to:
```
public function somemethod($somearg) {
// some.ruby.code
}
```
and left the innards as ruby in php comments that would still make the job easier.
Ideally there would be something out there that does this or similar already. Otherwise I might have to the write tool myself. | I completely agree with troelskn, this is a massive undertaking and I think that you'll have very little luck finding any form of automated process for porting the app.
Your best bet is finding a framework that is very similar in design and porting all the classes one by one.
The most tedious thing here will be where the database is involved. As far as I know, there is still no ORM solution for PHP that comes even close to Rails' ActiveRecord. You'll have to write a lot of the database code glue code yourself, and write all the model findersm, etc yourself. There may have been some improvements in this area since last time I checked, but PHP by nature has some problems with the ActiveRecord design pattern.
Again, I have to echo what I am sure a lot of people are thinking... why on *Earth* would you want to port an app from RoR to PHP. It sounds like an expensive thing to consider, both in time and money, with no clear advantage -- unless of course you've hit a wall with Ruby where it simply can not do something PHP can do. And I find this hard to believe. | It's a non-trivial effort to port applications between any two languages. In this case, it's even worse, because of the dissimilarities between php and ruby. You can't hope to get any kind of automated process for this.
If you need to do this (And the *why* is a different story on its own), you could try to use one of the php-frameworks that are closest in design to rails. The best candidates are probably either [Symfony](http://www.symfony-project.org/) or [Maintainable PHP Framework](http://framework.maintainable.com/mvc/1_intro.php).
I wonder though - What are your reason for this undertaking?
EDIT:
In php, a lot of symbols are global and immutable, once defined. For example, classes and functions can't be redefined, and there is no namespace support either. In ruby, it is possible - and very commonly used - to manipulate classes at runtime. This is impossible to convert automatically, and in many cases just plain out impossible to do. Even if you hacked around it with phps magic methods (`__get`/`__set`/`__call`), the performance penalty would be so severe, that it would render your application unusable. The only way to do this, is by hand.
You could perhaps use a tool, such as [rumld](http://rumld.rubyforge.org/) to give you a starting point. See also [this](https://stackoverflow.com/questions/52016/uml-for-ruby), for more ruby-to-uml tools. | Port a Ruby/Rails application to PHP 5 | [
"",
"php",
"ruby",
""
] |
I want every cell in each row except the last in each row. I tried:
```
$("table tr td:not(:last)")
```
but that seems to have given me every cell except the very last in the table. Not quite what I want.
I'm sure this is simple but I'm still wrapping my head around the selectors. | Try:
```
$('table tr td:not(:last-child)')
``` | You could try
```
$("table td:not(:last-child)")
```
or
```
$("table td:not(:nth-child(n))")
```
where n is 1-based index of a child element
or
```
$("table td").not(":last-child")
``` | jQuery: how to select every cell in a table except the last in each row? | [
"",
"javascript",
"jquery",
""
] |
As prescribed by Yahoo!, gzip'ng files would make your websites load faster. The problem? I don't know how :p | <http://www.webcodingtech.com/php/gzip-compression.php>
Or if you have Apache, try <http://www.askapache.com/htaccess/apache-speed-compression.html>
Some hosting services have an option in the control panel. It's not always possible, though, so if you're having difficulty, post back with more details about your platform. | If you are running Java Tomcat then you set a few properties on your Connector ( in conf/server.xml ).
Specifically you set:
1. compressableMimeType ( what types to compress )- compression ( off | on | )- noCompressionUserAgents ( if you don't want certain agents to receive gzip, list them here )
Here's the tomcat documentation which discusses this:
<http://tomcat.apache.org/tomcat-5.5-doc/config/http.html> | How do I gzip my web files | [
"",
"php",
".htaccess",
""
] |
I was debugging something and discovered some strangeness in JavaScript:
```
alert(1=='') ==> false
alert(0=='') ==> true
alert(-1=='') ==> false
```
It would make sense that an implied string comparison that 0 should = '0'. This is true for all non-zero values, but why not for zero? | According to the Mozilla documentation on [Javascript Comparison Operators](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators)
> If the two operands are not of the same type, JavaScript converts the
> operands then applies strict
> comparison. If either operand is a
> number or a boolean, the operands are
> converted to numbers; if either
> operand is a string, the other one is
> converted to a string
What's actually happening is that the strings are being converted to numbers.
For example:
`1 == '1'` becomes `1 == Number('1')` becomes `1 == 1`: `true`
Then try this one:
`1 == '1.'` becomes `1 == Number('1.')` becomes `1 == 1`: `true`
If they were becoming strings, then you'd get `'1' == '1.'`, which would be false.
It just so happens that `Number('') == 0`, therefore `0 == ''` is true | When javascript does implicit type conversions, the empty string literal will match the 0 integer. Do your comparison like this and you'll get your expected result:
```
alert(1==='') ==> false
alert(0==='') ==> false
alert(-1==='') ==> false
``` | Implied string comparison, 0=='', but 1=='1' | [
"",
"javascript",
""
] |
I'm working with PyGTK, trying to come up with a combination of widgets that will do the following:
* Let me add an endless number of widgets in a column
* Provide a vertical scrollbar to get to the ones that run off the bottom
* Make the widgets' width adjust to fill available horizontal space when the window is resized
Thanks - I'm new to GTK. | * An endless number of widgets in a column: Sounds like a GtkVBox.
* Vertical scrollbar: Put your VBox in a GtkScrolledWindow.
* Horizontal stretching: This requires setting the appropriate properties for the VBox, ScrolledWindow, and your other widgets. At least in Glade the defaults seem to mostly handle this (You will probably want to change the scrollbar policy of the ScrolledWindow).
Now for the trick. If you just do what I've listed above, the contents of the VBox will try to resize vertically as well as horizontally, and you won't get your scrollbar. The solution is to place your VBox in a GtkViewport.
So the final hierarchy is ScrolledWindow( Viewport( VBox( widgets ) ) ). | What Steve said in code:
```
vbox = gtk.VBox()
vbox.pack_start(widget1, 1, 1) ## fill and expand
vbox.pack_start(widget2, 1, 1) ## fill and expand
vbox.pack_start(widget3, 1, 1) ## fill and expand
swin = gtk.ScrolledWindow()
swin.add_with_viewport(vbox)
``` | Which GTK widget combination to use for scrollable column of widgets? | [
"",
"python",
"gtk",
"pygtk",
"widget",
""
] |
I have a windows service that has a custom configuration section. In the configSectionHandler class I am using attributes on the properties to validate the settings like this:
```
//ProcessingSleepTime Property
[ConfigurationProperty("ProcessingSleepTime", DefaultValue = 1000, IsRequired = false)]
[IntegerValidator(MinValue = 5, MaxValue = 60000)]
public Int32 ProcessingSleepTime
{
get
{
if (this["ProcessingSleepTime"] == null)
return 100;
return (Int32)this["ProcessingSleepTime"];
}
set
{
this["ProcessingSleepTime"] = value;
}
}
```
If a value in the configuration file fails validation, a ConfigurationErrorsException is thrown. In a windows service this happens as it is trying to start and it's really ugly (it offers to launch the debugger). How can I gracefully handle this error? I tried wrapping the OnStart method in a try/catch but it had no effect.
Thanks. | Or better yet (as you might need multiple such a properties), using the code from @Ricardo Villiamil, create:
```
int GetIntFromConfigSetting(string settingName, int defaultValue)
{
int retValue = defaultValue;
if(this.ContainsKey(settingName))
{
int sleepInterval;
if(Int32.TryParse(this[settingName], out sleepInterval)
{
retValue = sleepInterval;
}
}
return retValue;
}
```
Then use it from any property you need to.
EDIT: actually, after re-reading the question once more, looks like this solves your problem only half-way, as if the value is out of the defined range, it will throw exception anyway.
EDIT2: You can hook the [AppDomain.UnhandledException event](http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx) in the static ctor of your config section handler. The static ctor is ran before any instance or static member of a class are accessed, so it guarantees that you will intercept the exception even if the main method of your service is not yet called.
And then, when you intercept and log the error, you can exit the service with some error code != 0 ( Environment.Exit(errorCode) ), so the service manager knows it failed, but not try to invoke a debugger. | Ok I think I have it. In my service I have code that looks like this in the constructor:
config = ConfigurationManager.GetSection("MyCustomConfigSection") as MyCustomConfigSectionHandler;
This is where the error is thrown. I can catch the error and log it. The error must be rethrown in order to prevent the service from continuing. This still causes the ugly behavior but at least I can log the error thereby informing the user of why the service did not start | How/Where to handle ConfigurationErrorsException in a windows service? | [
"",
"c#",
"windows-services",
"configuration-files",
""
] |
I'm dealing with an Oracle DBA at the moment, who has sent me some profiling he's done. One of the terms in his report is 'Buffer Gets', any idea what this actually means? My guess is bytes retrieved from a buffer, but I have no idea really. Here is some sample output:
```
Buffer Gets Executions Gets per Exec %Total Time (s) Time (s) Hash Value
--------------- ------------ -------------- ------ -------- --------- ----------
137,948,100 31,495 4,380.0 98.4 6980.57 6873.46 4212400674
Module: JDBC Thin Client
SELECT fieldOne, fieldTwo, fieldThree, fieldFour, fieldFive FROM TableExample
WHERE fieldOne = 'example'
```
It would also be handy to know what 'Gets per Exec' means, as I guess they are related? I'm a programmer, but not a DBA. | Oracle storage is arranged into blocks of a given size (e.g. 8k). Tables and indexes are made up of a series of blocks on the disk. When these blocks are in memory they occupy a buffer.
When Oracle requires a block it does a **buffer get**. First it checks to see if it already has the block it needs in memory. If so, the in-memory version is used. If it does not have the block in memory then it will read it from disk into memory.
So a buffer get represents the number of times Oracle had to access a block. The reads could have been satisfied either from memory (the buffers) or have resulted in a physical IO.
Since physical IO is so expensive (compared to memory or CPU) one approach to tuning is to concentrate on reduction in buffer gets which is assumed will flow on to reduce physical IO. | Just to answer one part of your question that WW didn't:
"Gets per Exec" is simply the gets divided by the number of executions of the statement. You might have a statement that is very efficient but executed many times; this would have a high number of total buffer gets but a low gets per exec ratio. | In Oracle what does 'Buffer Gets' actually refer to? | [
"",
"sql",
"oracle",
""
] |
In the application that I am working on, the logging facility makes use of `sprintf` to format the text that gets written to file. So, something like:
```
char buffer[512];
sprintf(buffer, ... );
```
This sometimes causes problems when the message that gets sent in becomes too big for the manually allocated buffer.
Is there a way to get `sprintf` behaviour without having to manually allocate memory like this?
EDIT: while `sprintf` is a C operation, I'm looking for C++ type solutions (if there are any!) for me to get this sort of behaviour... | No you can't use `sprintf()` to allocate enough memory. Alternatives include:
* use `snprintf()` to truncate the message - does not fully resolve your problem, but prevent the buffer overflow issue
* double (or triple or ...) the buffer - unless you're in a constrained environment
* use C++ `std::string` and `ostringstream` - but you'll lose the printf format, you'll have to use the << operator
* use [Boost Format](http://www.boost.org/doc/libs/1_41_0/libs/format/doc/format.html) that comes with a printf-like % operator | You can use asprintf(3) (note: non-standard) which allocates the buffer for you so you don't need to pre-allocate it. | Using sprintf without a manually allocated buffer | [
"",
"c++",
"c",
"string",
"memory",
""
] |
When using `call_user_func_array()` I want to pass a parameter by reference. How would I do this. For example
```
function toBeCalled( &$parameter ) {
//...Do Something...
}
$changingVar = 'passThis';
$parameters = array( $changingVar );
call_user_func_array( 'toBeCalled', $parameters );
``` | To pass by reference using `call_user_func_array()`, the parameter in the array must be a reference - it does not depend on the function definition whether or not it is passed by reference. For example, this would work:
```
function toBeCalled( &$parameter ) {
//...Do Something...
}
$changingVar = 'passThis';
$parameters = array( &$changingVar );
call_user_func_array( 'toBeCalled', $parameters );
```
See the notes on the [`call_user_func_array()` function documentation](https://www.php.net/manual/en/function.call-user-func-array.php) for more information. | Directly, it may be impossible -- however, if you have control both over the function you are implementing *and* of the code that *calls* it - then there is one work-around that you *might* find suitable.
Would you be okay with having to embed the variable in question into an object? The code would look (somewhat) like this if you did so.
```
function toBeCalled( $par_ref ) {
$parameter = $par_ref->parameter;
//...Do Something...
$par_ref->parameter = $parameter;
}
$changingVar = 'passThis';
$parembed = new stdClass; // Creates an empty object
$parembed->parameter = array( $changingVar );
call_user_func_array( 'toBeCalled', $parembed );
```
You see, an object variable in PHP is merely a *reference* to the *contents* of the object --- so if you pass an object to a function, any changes that the function makes to the *content* of the object will be reflected in what the calling function has access to as well.
Just make sure that the calling function never does an assignment to the object variable *itself* - or that will cause the function to, basically, *lose* the reference. Any assignment statement the function makes must be *strictly* to the *contents* of the object. | Is it possible to pass parameters by reference using call_user_func_array()? | [
"",
"php",
"reference",
"callback",
""
] |
I am working on refactoring some old code and have found few structs containing zero length arrays (below). Warnings depressed by pragma, of course, but I've failed to create by "new" structures containing such structures (error 2233). Array 'byData' used as pointer, but why not to use pointer instead? or array of length 1? And of course, no comments were added to make me enjoy the process...
Any causes to use such thing? Any advice in refactoring those?
```
struct someData
{
int nData;
BYTE byData[0];
}
```
NB It's C++, Windows XP, VS 2003 | Yes this is a C-Hack.
To create an array of any length:
```
struct someData* mallocSomeData(int size)
{
struct someData* result = (struct someData*)malloc(sizeof(struct someData) + size * sizeof(BYTE));
if (result)
{ result->nData = size;
}
return result;
}
```
Now you have an object of someData with an array of a specified length. | There are, unfortunately, several reasons why you would declare a zero length array at the end of a structure. It essentially gives you the ability to have a variable length structure returned from an API.
Raymond Chen did an excellent blog post on the subject. I suggest you take a look at this post because it likely contains the answer you want.
Note in his post, it deals with arrays of size 1 instead of 0. This is the case because zero length arrays are a more recent entry into the standards. His post should still apply to your problem.
<http://blogs.msdn.com/oldnewthing/archive/2004/08/26/220873.aspx>
**EDIT**
Note: Even though Raymond's post says 0 length arrays are legal in C99 they are in fact still not legal in C99. Instead of a 0 length array here you should be using a length 1 array | Array of zero length | [
"",
"c++",
"arrays",
"visual-c++",
"flexible-array-member",
""
] |
I've run into a really strange bug, that I'm hoping someone can explain. I have a simple `std::vector<V3x>`, where `V3x` is a 3d vector (the linear algebra kind.) The following code causes a `std::length_error` exception to be thrown:
```
std::vector<V3x> vertices;
int vertexCount = computeVertexCount();
vertices.resize(vertexCount); // throws std::length_error
```
I've verified that `computeVertexCount()` returns a value of `35`, which is far far below `vector::max_size()` so there's no way it's asking for too much memory.
I traced the exception down into the definition of `std::vector`, to the following two functions.
```
void resize(size_type _Newsize, _Ty _Val)
{ // determine new length, padding with _Val elements as needed
if (size() < _Newsize)
// NOTE: here, _Newsize - size() = 35
_Insert_n(end(), _Newsize - size(), _Val);
else if (_Newsize < size())
erase(begin() + _Newsize, end());
}
void _Insert_n(const_iterator _Where,
size_type _Count, const _Ty& _Val)
{ // insert _Count * _Val at _Where
// NOTE: here, _Count = 3435973836
...
}
```
So when the `_Count` parameter is passed between `resize()` and `_Insert_n()`, the value changes from 35 to 3435973836. I'm assuming the memory has somehow become corrupted, but I have no idea how that could be.
For a little more context in case it's part of the problem, this code sits in a .dll plugin that I'm loading from Softimage XSI.
Does anyone know what might cause something like this to happen?
**EDIT: SOLUTION**
nobugz, I could kiss you.
The size of std::vector was changing inside my .dll, because of `_HAS_ITERATOR_DEBUGGING` in VS2008. The search led me to [someone with the same problem](http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/efef799e-5d88-4a95-be39-4cd674be5d14/), and it was fixed by adding the following at the top of my project:
```
// fix stack corruption errors caused by VS2008
#define _HAS_ITERATOR_DEBUGGING 0
#define _SECURE_SCL 0
``` | The value 3435973836 is significant. In hex, that's 0xcccccccc. That's the value assigned to local variables in Debug mode by the stack frame initialization code. When you see it back while debugging, you'd say "ah, variable not initialized". Maybe that gets you a bit closer to solving this.
You mention DLL. That's relevant too. Iterator debugging might get you into trouble, you cannot mix code that has it turned off with code that doesn't. Since the DLL is probably compiled without it, try #define \_HAS\_ITERATOR\_DEBUGGING 0. | Whenever a parameter or local variable changes unexpectedly, there's a good chance it's due to stack corruption. This can occur whenever you use an uninitialized local variable or store data beyond the memory allocated to a local string or array.
A simple way to debug this:
1. Load your program into a debugger.
2. Insert a breakpoint at the first line of code in the offending function.
3. Execute the program until it hits the breakpoint.
4. Set a watch on the variable that changes unexpectedly.
5. Step through the function until the unexpected change occurs.
The change will occur when the un-allocated (or mis-allocated) memory is written. The target of the write is the offending variable. | C++ Parameter's Value Changes Between Stack Frames in std::vector | [
"",
"c++",
"debugging",
"memory",
"parameters",
"vector",
""
] |
Is there a way to initialize all elements of an array to a constant value through generics? | I would use an extender (.net 3.5 feature)
```
public static class Extenders
{
public static T[] FillWith<T>( this T[] array, T value )
{
for(int i = 0; i < array.Length; i++)
{
array[i] = value;
}
return array;
}
}
// now you can do this...
int[] array = new int[100];
array.FillWith( 42 );
``` | Personally, I would use a good, old for loop, but if you want a one-liner, here it is:
```
T[] array = Enumerable.Repeat(yourConstValue, 100).ToArray();
``` | How to initialize an array through generics? | [
"",
"c#",
"generics",
""
] |
*LIKE* operator in MySql is used to find rows that contain our query text, for example:
```
select name from user where name like "%john%"
```
which will return `John Smith`, `Peter Johnson` etc.
What if I need the opposite - to find rows that are *CONTAINED* in our query text? For example I give it `John Smith and Peter Johnson are best friends` and want it to find me all names from the table that could be found in this string.
How to do that? | Here's a way you can achieve what you describe:
```
SELECT name FROM user
WHERE 'John Smith and Peter Johnson are best friends' LIKE
CONCAT('%', name, '%')
``` | ```
select name
from users
where instr('John Smith and Peter Johnson', name) > 0
```
I would rather use this method instead of:
```
select *
from users
WHERE 'John Smith and Peter Johnson' LIKE CONCAT('%', name ,'%')
```
because if there is any chance that the `name` could contain the `%` or `_` character (eg. name='v%alue') then the above query would still return that record incorrectly. Also note that if your column could contain backslashes and/or "[C escape characters](https://en.wikipedia.org/wiki/Escape_sequences_in_C "C escape characters")" then they would also need to be escaped. This is all explained in [MySQL String Comparison Functions](http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html "MYSQL String Comparison Functions"). For example the below SQL would return 1:
```
SELECT 'val\%ue' LIKE CONCAT('%', 'al\\\\\%u' ,'%');
```
*The single backslash needed to be escaped with `\\\\` and the `%` character was escaped: `\%`.* | MySQL: What is a reverse version of LIKE? | [
"",
"sql",
"mysql",
""
] |
There's no strongly typed View() method to return an ActionResult. So, suppose I have
```
class Edit : ViewPage<Frob>
```
In my FrobController, I will do something like "return View("Edit", someFrob);". There's no checking going on here, so I have to always manually synchronize the view and controller's use of it. This is suboptimal, and I'm not aware of any built-in fixes.
I added this method to my controller base class:
```
public ActionResult ViewPage<V, M>(V view, M model)
where V : ViewPage<M>
where M : class {
return View(typeof(V).Name, model);
}
```
> Note: The reason I take a view
> object that's never used is because,
> AFAIK, there's no way to get C#'s type
> inference to work otherwise. If I
> removed the view parameter, I'd need
> to specify V explicitly, which also
> means specifying M explicitly too...
> sigh.
So now, I can do this:
```
return ViewPage(new Views.Frob.Edit(), myFrob);
```
I'm specifying the exact view (no problem if it gets renamed), and myFrob is typechecked to be the right model type. The ugly side is that I new up a Edit. Alternatively, I could write:
```
return ViewPage((Views.Frob.Edit)null, myFrob);
```
One downside is that the the model must be an exact match. So with a ViewPage>, I cannot pass in a List. I thought this might work:
```
public ActionResult ViewPage<V, M, T>(V view, T model)
where V : ViewPage<M>
where M : class
where T : M {
return View(typeof(V).Name, model);
}
```
But C#'s type inference can't figure it out. The other potential problem is that the name of the view type might not be the right name, as I think it can be overridden by attributes. But that's an easy fix if I run into it.
Questions:
1. How can I make this syntax cleaner?
2. What downsides am I missing here?
Edit: With respect to the Controller knowing about the View, it only slightly does. The only thing it gets from the view is the Type, for which it grabs the name. So that's equivalent to passing in the string name. And the strongly typed model, which must match or it'll fail. So it doesn't really know too much about the View -- its just a trick to get the compiler to catch errors. | The first problem I see is that you've now made your Controller aware of the View. That's a line you should never cross. | Take a look at this example: <http://oddiandeveloper.blogspot.com/2008/11/strongly-typed-view-names.html>
You can call yout View like this:
```
return View(typeof(Views.en.Home.about), AboutModel);
``` | Strongly typing ASP.NET Controller.View() method for model type | [
"",
"c#",
"asp.net-mvc",
""
] |
I've been thinking about using extension methods as a replacement for an abstract base class. The extension methods can provide default functionality, and can be 'overridden' by putting a method of the same signature in a derived class.
Any reason I shouldn't do this?
Also, if I have two extension methods with the same signature, which one is used? Is there a way of establishing priority? | I agree with Michael. Base classes should contain all base functionality Extension methods should, obviously, extend the base functionality. In dynamic languages like Ruby it is often typical to use extension methods to provide addition functionality instead of using subclasses. Basically, extension methods are there to replacing using subclassses, not to replace using base classes.
The only exception to this that I've seen is if you have multiple type that have different class hierachies (like winform controls), you can make a subclass of each that all implement and interface and then extend that interface, thereby giving "base" functionality to a group of different controls, without extending everything like Control or Object.
Edit: answering your second question
I think the compiler will catch this for you. | In general, you shouldn't provide "base" functionality through extension methods. They should only be used to "extend" class functionality. If you have access to the base class code, and the functionality you're trying to implement is logically part of the inheritance heirarchy, then you should put it in the abstract class.
My point is, just because you *can* doesn't mean you *should*. It's often best just to stick with good old fashioned OOP and use the newer language features when plain old OO programming falls short of providing you a reasonable solution. | Overriding Extension Methods | [
"",
"c#",
""
] |
So I was thinking one way that you can bring method chaining into PHP with the built-in global functions would be to "borrow" the |> (pipe) operator from F#. It would pipe the results on the left into the first parameter of the function on the right. Of course PHP would have to revisit the parameter order of some of their functions.
This would allow you to write:
```
function StrManip($val) {
return str_repeat(strtolower(trim($val)),2);
}
```
Like this:
```
function StrManip($val) {
return $val |> trim() |> strtolower() |> str_repeat(2);
}
``` | It looks like what he wants is a String class with methods that mirror the builtin functions. This is a guess, but maybe you could use the \_\_call magic method to do the work like this:
**(untested)**
```
class String {
private $_value = '';
public function __construct($value) {
$_value = $value;
}
public function __call ($name, $arguments) {
return new String($name($_value, $arguments));
}
}
$string = new String($string);
echo $string->trim()->strtolower()->str_repeat(2);
```
You would have to do some parsing to get the $arguments part to work, and it would create a lot of objects when you chain the methods, but in theory this should get you some functionality you are looking for. | Something much like that can be accomplished using fluent object methods. For example:
```
class Foo
{
public function bar()
{
echo 'Hello<br/>';
return $this;
}
public function bar2()
{
echo 'Goodbye<br/>';
return $this;
}
}
$foo = new Foo();
$foo->bar()->bar2();
```
Outputs the following:
Hello
Goodbye | Good or Bad? Bring "Function Chaining" Capabilities to PHP | [
"",
"php",
"language-features",
""
] |
```
#include<iostream>
class name
{
public:
int a;
name():a(0){};
};
void add(name * pname)
{
pname = NULL;
}
int main()
{
name varName();
name * pName = new name();
add(pName);
add(&varName);//error C2664: 'add' : cannot convert parameter 1 from 'name __cdecl *)(void)' to 'name *'
}
``` | I think it's worth telling you about a similar problem, that also causes trouble:
```
struct foo { };
struct bar { bar(foo f); };
int main() {
// does *not* create a bar object initialized by a default constructed
// foo object.
bar b(foo());
}
```
What b really is is a function that returns a `bar` and takes as first argument a pointer to a function that returns a foo taking no arguments. It's the same as:
```
bar b(foo(*)());
```
If you want to create a bar object initialized by a default constructed foo, put parentheses around the argument. That makes it doesn't look like a function declaration anymore, and the compiler will interpret it like you want:
```
bar b((foo()));
```
---
There are also non-obvious cases where a compiler error should be risen. GCC gets this wrong, but Comeau gets it right again. Consider the following snippet
```
struct foo {
static bool const value = false;
};
int main() {
int v(int(foo::value));
}
```
You will probably expect that this takes the static constant, and casts it to `int`, initializing the `v` variable to `0`? No, it won't according to the Standard, because the initializer can be interpreted as a declaration, according to pure syntax analysis, as the following shows
```
struct foo {
static int value;
};
// valid, parentheses are redundant! Defines `foo::value`.
int (foo::value);
```
Whenever the initializer can be interpreted as a declaration, in such a situation whole the declaration will declare a function. So, the line in `main` declares a function like the following, omitting the redundant and meaningless parentheses
```
int v(int foo::value);
```
And this will cause a compiler error when parsing the function declaration, because a function parameter name may not be qualified. | The error is on the first line of the main function:
```
name varName();
```
You are **not** creating an instance of class *name* with the default constructor, you are actually declaring a new function called *varName*, with no parameters, which returns a *name* instance.
You should instead write:
```
name varName;
``` | Is this' type variableofType()' function or object? | [
"",
"c++",
"function",
"pointers",
""
] |
I've got ~20 columns in a grid each of which can be shown or hidden via a checkbox in another dialog.
The visibility state of any given column will be stored inside an XML file which is accessed via an Options class.
I'm trying to decide how best to represent those Boolean visibility values inside the Options class. I'm fairly sure I'll want properties exposing each column's visibility, but underneath those should there be a bool for each column or should I consider using a Dictionary or similar to hold all the column visibility values in one place?
The way I see it individual bools is probably a bit more robust and less likely to result in missing column values or some such, but a Dictionary would probably reduce the total amount of code. | The way I elected to do it was to create an Enum with an entry for each column combined with a Dictionary to hold the visibility state and a property exposing each column value.
This makes it easy to store and retrieve the column values from my XML file (just enumerate through the Enum storing/retrieving the desired value from the dictionary for each Enum) while also providing a bit more safety than just using a naked dictionary. | If it's the only property you need to store for the columns, you could use a single string where 1 means the column is visible and 0 hidden.
<Columns Visible="00001011110111010101" /> | What is the best way to store configuration values for several dozen columns? | [
"",
"c#",
".net",
""
] |
What is the current status of TagLib# (TagLib sharp)?
The official homepage www.taglib-sharp.com (link removed due to the NSFW nature of the new site that's parked at that address. -BtL) doesn't exist anymore!
I've found the project on [ohloh](http://www.ohloh.net/p/5598) where the old homepage is still linked. Also the download link points to the old site.
BUT the ohloh development pages are linked to a mono-project [SVN repository](http://anonsvn.mono-project.com/source/trunk/taglib-sharp), which seems to be under active development (last commit date: 2009/02/20, current version number: 2.0.3.2).
Furthermore, on the [developer.novell.com wiki](http://developer.novell.com/wiki/index.php/TagLib_Sharp) the same SVN repo is linked.
So, is there any **up-to-date homepage** or, at least, any **up-to-date binary+documentation releases**? | The page at Novell (<http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html>) is no longer updated.
The source code is now hosted at <https://github.com/mono/taglib-sharp> and the best way to install and use the latest version is using NuGet. Open the Package Manager Console in Visual Studio and type:
```
PM> Install-Package taglib
```
This question is also answered at [TagLib# Windows distribution? Or another good ID3 reader?](https://stackoverflow.com/questions/2181445/taglib-windows-distribution-or-another-good-id3-reader) | Looks like it moved here: <http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html> | What happened to the "TagLib#" library? | [
"",
"c#",
"mp3",
"id3",
"taglib-sharp",
""
] |
Is there a way in Python to override a class method at instance level?
For example:
```
class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
``` | Please do not do this as shown. You code becomes unreadable when you monkeypatch an instance to be different from the class.
You cannot debug monkeypatched code.
When you find a bug in `boby` and `print type(boby)`, you'll see that (a) it's a Dog, but (b) for some obscure reason it doesn't bark correctly. This is a nightmare. Do not do it.
Please do this instead.
```
class Dog:
def bark(self):
print "WOOF"
class BobyDog( Dog ):
def bark( self ):
print "WoOoOoF!!"
otherDog= Dog()
otherDog.bark() # WOOF
boby = BobyDog()
boby.bark() # WoOoOoF!!
``` | Yes, it's possible:
```
class Dog:
def bark(self):
print "Woof"
def new_bark(self):
print "Woof Woof"
foo = Dog()
funcType = type(Dog.bark)
# "Woof"
foo.bark()
# replace bark with new_bark for this object only
foo.bark = funcType(new_bark, foo, Dog)
foo.bark()
# "Woof Woof"
``` | Override a method at instance level | [
"",
"python",
""
] |
I have a table where each row has a few fields that have ID's that relate to some other data from some other tables.
Let's say it's called `people`, and each person has the ID of a `city`, `state` and `country`.
So there will be three more tables, `cities`, `states` and `countries` where each has an ID and a name.
When I'm selecting a person, what's the easiest way to get the **names** of the `city`, `state` and `country` in a single query?
**Note:** I know this is possible with joins, however as there are more related tables, the nested joins makes the query hard to read, and I'm wondering if there is a cleaner way. It should also be possible for the person to have those fields empty. | Assuming the following tables:
```
create table People
(
ID int not null primary key auto_increment
,FullName varchar(255) not null
,StateID int
,CountryID int
,CityID int
)
;
create table States
(
ID int not null primary key auto_increment
,Name varchar(255) not null
)
;
create table Countries
(
ID int not null primary key auto_increment
,Name varchar(255) not null
)
;
create table Cities
(
ID int not null primary key auto_increment
,Name varchar(255) not null
)
;
```
With the Following Data:
```
insert into Cities(Name) values ('City 1'),('City 2'),('City 3');
insert into States(Name) values ('State 1'),('State 2'),('State 3');
insert into Countries(Name) values ('Country 1'),('Country 2'),('Country 3');
insert into People(FullName,CityID,StateID,CountryID) values ('Has Nothing' ,null,null,null);
insert into People(FullName,CityID,StateID,CountryID) values ('Has City' , 1,null,null);
insert into People(FullName,CityID,StateID,CountryID) values ('Has State' ,null, 2,null);
insert into People(FullName,CityID,StateID,CountryID) values ('Has Country' ,null,null, 3);
insert into People(FullName,CityID,StateID,CountryID) values ('Has Everything', 3, 2, 1);
```
Then this query should give you what you are after.
```
select
P.ID
,P.FullName
,Ci.Name as CityName
,St.Name as StateName
,Co.Name as CountryName
from People P
left Join Cities Ci on Ci.ID = P.CityID
left Join States St on St.ID = P.StateID
left Join Countries Co on Co.ID = P.CountryID
``` | JOINS are the only way to really do this.
You might be able to change your schema, but the problem will be the same regardless.
(A City is always in a State, which is always in a Country - so the Person could just have a reference to the city\_id rather than all three. You still need to join the 3 tables though). | What's the best way to get related data from their ID's in a single query? | [
"",
"sql",
"mysql",
"join",
"relational",
""
] |
I'm looking for a portable and easy-to-use string library for C/C++, which helps me to work with Unicode input/output. In the best case, it will store its strings in memory in UTF-8, and allow me to convert strings from ASCII to UTF-8/UTF-16 and back. I don't need much more besides that (ok, a liberal license won't hurt). I have seen that C++ comes with a [`<locale>`](http://dinkumware.com/manuals/default.aspx?manual=compleat&page=locale2.html) header, but this seems to work on `wchar_t` only, which may or may not be UTF-16 encoded, plus I'm not sure how good this is actually.
Uses cases are for example: On Windows, the unicode APIs expect UTF-16 strings, and I need to convert ASCII or UTF-8 strings to pass it on to the API. Same goes for XML parsing, which may come with UTF-16, but I actually only want to process internally with UTF-8 (or, for that matter, if I switch internally to UTF-16, I'll need a conversion to that anyway).
So far, I've taken a look at the [ICU](http://www.icu-project.org/), which is quite huge. Moreover, it wants to be built using it own project files, while I'd prefer a library for which there is either a CMake project or which is easy to build (something like compile all these .c files, link and good to go), instead of shipping something large as the ICU along my application.
Do you know such a library, which is also being maintained? After all, this seems to be a pretty basic problem. | [UTF8-CPP](https://github.com/nemtrif/utfcpp) seems to be exactly what you want. | I'd recommend that you look at the [GNU iconv](http://www.gnu.org/software/libiconv/) library. | Portable and simple unicode string library for C/C++? | [
"",
"c++",
"c",
"unicode",
""
] |
I've got a multidimensional associative array which includes an elements like
```
$data["status"]
$data["response"]["url"]
$data["entry"]["0"]["text"]
```
I've got a strings like:
```
$string = 'data["status"]';
$string = 'data["response"]["url"]';
$string = 'data["entry"]["0"]["text"]';
```
How can I convert the strings into a variable to access the proper array element? This method will need to work across any array at any of the dimensions. | Quick and dirty:
```
echo eval('return $'. $string . ';');
```
Of course the input string would need to be be sanitized first.
If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe.
It does, however, make assumptions about the string format:
```
<?php
$data['response'] = array(
'url' => 'http://www.testing.com'
);
function extract_data($string) {
global $data;
$found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
if (!$found_matches) {
return null;
}
$current_data = $data;
foreach ($matches[1] as $name) {
if (key_exists($name, $current_data)) {
$current_data = $current_data[$name];
} else {
return null;
}
}
return $current_data;
}
echo extract_data('data["response"]["url"]');
?>
``` | PHP's [variable variables](https://www.php.net/language.variables.variable) will help you out here. You can use them by prefixing the variable with another dollar sign:
```
$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"
``` | Convert a String to Variable | [
"",
"php",
"arrays",
"string",
"variables",
""
] |
This always forces us to return a single parameter in case I need to return multiple, say a List and a String. This restriction is not there in function arguments. | This problem is what functional languages such as F#, haskell etc. attempt to address. The problem is that in hardware, a function's return value was originally returned via a CPU register, so you could only return a single value. C syntax passed on this legacy and C++ (and C#, Java) also inherited this. | In fact, some languages do what you exactly want. For example Python, look at this code. It returns 2 values: 1 string and another int.
```
>>> def myFunc():
... string_val = "techmaddy"
... int_val = 10
... return string_val, int_val
...
>>>
>>> s, i = myFunc()
>>>
>>> print s
techmaddy
>>>
>>> print i
10
```
I hope it would help.
PS: Under the covers, I guess Python is boxing it in a list and un-boxing it. I don't know Python that well to tell you what exactly it does. | why do functions dont have parameterized return types, as it has parameterized input? | [
"",
"java",
"function",
"return-type",
""
] |
How do I convert a string to the variable name in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
For example, if the program contains a object named `self.post` that contains a variable named, I want to do something like:
```
somefunction("self.post.id") = |Value of self.post.id|
``` | As referenced in Stack Overflow question *[Inplace substitution from ConfigParser](https://stackoverflow.com/questions/295028/)*, you're looking for `eval()`:
```
print eval('self.post.id') # Prints the value of self.post.id
``` | Note: do **not** use eval in any case where you are getting the name to look up from user entered input. For example, if this comes from a web page, there is nothing preventing anyone from entering:
```
__import__("os").system("Some nasty command like rm -rf /*")
```
as the argument. Better is to limit to well-defined lookup locations such as a dictionary or instance using [getattr()](https://docs.python.org/2/library/functions.html#getattr). For example, to find the "post" value on self, use:
```
varname = "post"
value = getattr(self, varname) # Gets self.post
```
Similarly to set it, use setattr():
```
value = setattr(self, varname, new_value)
```
To handle [fully qualified names](https://en.wikipedia.org/wiki/Fully_qualified_name), like "post.id", you could use something like the below functions in place of getattr() / [setattr()](https://docs.python.org/2/library/functions.html#setattr).
```
def getattr_qualified(obj, name):
for attr in name.split("."):
obj = getattr(obj, attr)
return obj
def setattr_qualified(obj, name, value):
parts = name.split(".")
for attr in parts[:-1]:
obj = getattr(obj, attr)
setattr(obj, parts[-1], value)
``` | Convert a string to preexisting variable names | [
"",
"python",
""
] |
Is it possible to get the value from the first page to the second page, BUT without `FORM`?
Shall we use
```
window.parent.document.getElementById("").value..
```
But this is working in `popup` window, but I need this for between two pages which redirecting from the first page to the second page. | If you are redirecting from one page to another, you MUST use form elements to pass from page to page or use a querystring value. That is it, Javascript does NOT have any knowledge of the structure of the previous page.. | or you can use cookies... | Get the value from one window to another window - JavaScript | [
"",
"javascript",
""
] |
**My goal is to get Limewire(JAVA) and Songbird(XULRunner) to run together.**
I was thinking the best way is to run the XUL application(songbird) inside a JAVA swing panel. Is there another way?
Would it be better or possible to have the GUI entirely in XUL, and then access my JAVA objects somehow?
How would I go about doing this?
Thanks | Take a look at [JRex](http://jrex.mozdev.org/), as it might let you peek into a couple of ideas.
Other than that, I'd also research about [Rhinohide](http://zelea.com/project/textbender/o/rhinohide/description.xht) as well. | Take a look at [DJ Native Swing](http://djproject.sourceforge.net/ns/ "DJ Native Swing"), a native Swing implementation using SWT and Xulrunner. | Embedding XULRunner application on Java | [
"",
"java",
"embed",
"xul",
"xulrunner",
""
] |
What XML libraries are out there, which are minimal, easy to use, come with little dependencies (ideally none), can be linked statically and come with a liberal license? So far, I've been a pretty happy user of [TinyXML](http://www.grinninglizard.com/tinyxml/), but I'm curious what alternatives I have missed so far. | I recommend [rapidxml](http://rapidxml.sourceforge.net/). It's an order of magnitude smaller than tinyxml, and doesn't choke on doctypes like tinyxml does.
If you need entity support or anything advanced, forget about static linking and use expat or libxml2. | [expat](http://expat.sourceforge.net/) is a very fast C XML parser (although a C++ wrapper exists) that's widely used in many open-source projects. If I remember correctly, it has very few dependencies, and it's licensed under the very liberal MIT License. | Minimal XML library for C++? | [
"",
"c++",
"c",
"xml",
""
] |
I am a COM object written in ATL that is used from a C++ application, and I want to pass an array of BYTEs between the two. My experience of COM/IDL so far is limited to passing simple types (BSTRs, LONGs, etc.).
Is there a relatively easy way to have the COM object pass an array to the caller? For example, I want to pass a raw image (TIFF) instead of messing with temporary files. | Try passing a safearray variant to the COM Object. Something like this to put a BYTE array inside a safearray variant....
```
bool ArrayToVariant(CArray<BYTE, BYTE>& array, VARIANT& vtResult)
{
SAFEARRAY FAR* psarray;
SAFEARRAYBOUND sabounds[1];
sabounds[0].lLbound=0;
sabounds[0].cElements = (ULONG)array.GetSize();
long nLbound;
psarray = SafeArrayCreate(VT_UI1, 1, sabounds);
if(psarray == NULL)
return false;
for(nLbound = 0; nLbound < (long)sabounds[0].cElements ; nLbound++){
if(FAILED(SafeArrayPutElement(psarray, &nLbound, &array[nLbound]))){
SafeArrayDestroy(psarray);
return false;
}
}
VariantFree(vtResult);
vtResult.vt = VT_ARRAY|VT_UI1;
vtResult.parray = psarray;
return true;
}
``` | SAFEARRAYs are the way to go if you want OLE-Automation compliance, and maybe use the COM interface from other languages such as VB6. But there is an alternative in IDL, for example: -
```
void Fx([in] long cItems, [in, size_is(cItems)] BYTE aItems[]);
```
This describes a method where the marshalling code can infer the number of bytes to be transfered by inspecting the value of the first parameter.
This is fine if your clients are all written in C/C++, but i *think* that an interface containing this would not be automation-compliant, so not usable from VB6, and *possibly* the standard marshaler will not be able to do the marshaling, so you'd need to generate your own proxy/stub DLL from the IDL. Not hard to do, but a bit harder than using SAFEARRAYs. | Passing an array using COM? | [
"",
"c++",
"com",
""
] |
I want to develop ASP.NET C# based MMOG (Massively multiplayer online game). I would be using ASP.NET Ajax control kit, jquery and MS SQL server 2005.
Q.1)How feasible .NET 3.5, ASP.NET with C# in handling thousands of users simultaneously.
I would also incorporate ASP.NET ajax based chatting system with chat rooms alongside the MMOG.
Q.2) Do you know any of the sites (MMOG) using ASP.NET ?
Q.3) What are the best practices for Chatting System as mentioned above? | ASP.NET and MSSQL 2005 definitely have no "built in" scaling problems. You will have to take care to build you application right and be prepared to dish out some money for proper hardware.
See for example the [hardware setup](https://blog.stackoverflow.com/2009/01/new-stack-overflow-server-glamour-shots/) that is scheduled to tackle the stackoverflow load. | 1. ASP.NET can handle it with the proper server configuration, hardware, and performance considerations when creating the application.
2. I tried to do some googling and didn't find anything right away, but I'm sure that there are some out there.
3. For the chat piece you might look at a product such as CuteChat that already exists and has been tried and tested for a long time. | Feasibility of ASP.NET based MMOG | [
"",
"c#",
"asp.net",
"asp.net-ajax",
"chat",
""
] |
I've got the following piece of code in an aspx webpage:
```
Response.Redirect("/Someurl/");
```
I also want to send a different referrer with the redirect something like:
```
Response.Redirect("/Someurl/", "/previousurl/?message=hello");
```
Is this possible in Asp.net or is the referrer handled solely by the browser?
Cheers
Stephen | Referrer is readonly and meant to be that way. I do not know why you need that but you can send query variables as instead of
```
Response.Redirect("/Someurl/");
```
you can call
```
Response.Redirect("/Someurl/?message=hello");
```
and get what you need there, if that helps. | `Response.Redirect` sends an answer code (HTTP 302) to the browser which in turn issues a new request (at least this is the expected behavior). Another possibility is to use `Server.Transfer` (see [here](http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx)) which doesn't go back to the browser.
Anyway, both of them don't solve your request. Perhaps giving some more detail on your case can help find another solution. ;-) | Response.Redirect with Different Referrer | [
"",
"c#",
"asp.net",
"response.redirect",
"referrer",
"referer",
""
] |
Sometimes the overhead of creating a new model type is annoying. In these cases, I want to set ViewData, and the options seem to be:
1. Simply set viewdata with a string key, and cast it out. This has obvious problems.
2. Store the identifier (string key) somewhere (where? on the controller?) and cast it out on the viewpage. While solving one of the problems, I'm still casting, which is problematic, and kills type inference.
3. Use the MVCContrib strongly typed Set/Get functions. These are nice sometimes, but if the type isn't very descriptive, say a boolean "IsNew", they don't work too well. It also kills type inference and it's still pretty much just doing a cast, so I must manually sync up the view and controller.
So, instead I'm thinking of using a phantom type to combine both the type and key identifier. It'd be equivalent to this psuedo-C#:
```
class ViewDataKey<T> = string
```
This would let me create identifiers in the controller like this:
```
public static readonly ViewDataKey<bool> IsNew = "IsNew";
```
With some simple extension methods, setting the data would be:
```
ViewData.Set(IsNew, true);
```
Getting it out is just as easy:
```
var isNew = ViewData.Get(FrobNozzleController.IsNew);
```
Notice we don't need to specify the type of isNew, it's safely inferred. The key and type definitons are stored in one location.
Questions:
1. Where should the key be stored? For "global-ish" ViewData, some common class works fine. But for View/Controller specific data? Is there any downside to putting it on the controller? (Apart from the long name of the controller?)
2. Are there any easier ways, or things already built-in? | I think this is what the model does in the MVC pattern. Why you don't use a typed view instead?
I believe you just make things more complicated by introducing yet another dependency between the controller and the view. I don't see any specific benefit in terms of line of code or something like that. You have to declare the existence of the variable, which you'd also do in the model class definition.
You don't get any significant advantage by doing so. | One idea would be to create tuples for a strongly typed view in cases where you don't want to create a specific view model class:
```
class SimpleModel<T>
class SimpleModel<T, U>
class SimpleModel<T, U, V>
```
Then make a strongly typed view, as usual. Now you have the advantages of strong typing without having to make a new class for every case.
.NET 4.0 has Tuple, etc., built in. | Strongly typed ASP.NET MVC ViewData extensions - where to put identifiers? | [
"",
"c#",
"asp.net-mvc",
""
] |
Is there any way in JavaScript how to find out user clicked through the same domain 2 or more times?
I need to popup a window after user clicked anywhere on the site for 3 times. I know how to do it after one click - with `document.referrer` or `addEventListener`, but then I'm lost.
I need something that will capture all click events (not only links) and count them. | I tried this and it worked fine:
```
window.onload = function() {
var clicked = readCookie('popunder');
if(clicked == null) {
clicked = 0;
}
var allLinks = document.getElementsByTagName("a");
for(i=0;i<=allLinks.length;i++) {
allLinks[i].addEventListener("click",countClicks,true);
}
function countClicks() {
if(clicked == 2) {
popunder(); //something to do
} else {
clicked++;
doCookie('popunder', clicked, 1);
alert(clicked);
}
}
function popunder() { alert('thats 3 clicks!'); }
function doCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
} else {
var expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var readName = name + "=";
var cSplit = document.cookie.split(';');
for(var i=0;i < cSplit.length;i++) {
var sc = cSplit[i];
while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length);
if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length);
}
return null;
}
}
``` | Sure. You need to store a list of users' click events, either in a cookie, or in a server-side data store. On every recorded click, increment the count by one, and do your thing when the number hits 3.
Try using session cookies to store state between pages -- they're fast, pretty widely compatible, and will zero out when the browser shuts down, to keep from spamming your users' cookie jars. | How to find out user clicked 3 times through my website with Javascript | [
"",
"javascript",
"click",
"dom-events",
""
] |
I coded up 4 .java files. The thing is that I can only execute my .java files from my IDE, how do I execute the .class files like an application? I study at uni, and I was told that Java is platform independent. Any tutorial/book recommendations would be highly appreciated.
Thanks | The basic idea (to give you some things to search for) is:
* Bundle your compiled .class files into a 'jar'.
* Add a manifest to your jar specifying a main class to run.
You might find your IDE already creates this when you run a 'clean build'. Netbeans puts this into a 'dist' folder.
Modern JREs will allow you to run the jar by double clicking it etc.
You can also go a bit further by wrapping the jar in a native executable using a tool such as JSmooth. | Look at [executable jar](http://java.sun.com/docs/books/tutorial/deployment/jar/). Here is the precise one, without any details, [Creating executable jar files](http://csdl.ics.hawaii.edu/~johnson/613f99/modules/04/jar-files.html). | how do I convert my java files into an application? | [
"",
"java",
"executable",
"executable-jar",
""
] |
I have a SQL table like so:
Update: I'm changing the example table as the existing hierarchical nature of the original data (State, Cities, Schools) is overshadowing the fact that a simple relationship is needed between the items.
```
entities
id name
1 Apple
2 Orange
3 Banana
4 Carrot
5 Mushroom
```
I want to define two-way relationships between these entities so a user viewing one entity can see a list of all related entities.
The relationships are defined by an end user.
What is the best way to represent these relationships in the database and subsequently query and update them?
**One way as I see it...**
My instinct says a relationship table like so:
```
entity_entity
entity_id_a entity_id_b
1 2
5 1
4 1
5 4
1 3
```
That being the case, given a supplied entity\_id of 4, how would one get all related records, which would be 1 and 5?
Likewise a query of entity\_id = 1 should return 2, 3, 4, and 5.
Thanks for your time and let me know if I can clarify the question at all. | Define a constraint: `entity_id_a < entity_id_b`.
Create indexes:
```
CREATE UNIQUE INDEX ix_a_b ON entity_entity(entity_id_a, entity_id_b);
CREATE INDEX ix_b ON entity_entity(entity_id_b);
```
Second index doesn't need to include `entity_id_a` as you will use it only to select all `a`'s within one `b`. `RANGE SCAN` on `ix_b` will be faster than a `SKIP SCAN` on `ix_a_b`.
Populate the table with your entities as follows:
```
INSERT
INTO entity_entity (entity_id_a, entity_id_b)
VALUES (LEAST(@id1, @id2), GREATEST(@id1, @id2))
```
Then select:
```
SELECT entity_id_b
FROM entity_entity
WHERE entity_id_a = @id
UNION ALL
SELECT entity_id_a
FROM entity_entity
WHERE entity_id_b = @id
```
`UNION ALL` here lets you use above indexes and avoid extra sorting for uniqueness.
All above is valid for a symmetric and anti-reflexive relationship. That means that:
* If **a** is related to **b**, then
**b** is related to **a**
* **a** is never related to **a** | I think the structure you have suggested is fine.
To get the related records do something like
```
SELECT related.* FROM entities AS search
LEFT JOIN entity_entity map ON map.entity_id_a = search.id
LEFT JOIN entities AS related ON map.entity_id_b = related.id
WHERE search.name = 'Search term'
```
Hope that helps. | What is the best way to represent a many-to-many relationship between records in a single SQL table? | [
"",
"sql",
"database",
"many-to-many",
"entity-relationship",
"relational",
""
] |
Preface: I have jQuery and jQuery UI included on a page.
I have this function defined:
```
function swap(sel) {
if (1 == 1) {
$(sel).hide('drop',{direction:'left'});
}
}
```
How do I fix the (1 == 1) part to test to see if the element is already hidden and then bring it back if it is. I'm sure this is easy, but I'm new to jQuery. | if you don't like `toggle`, then this may help you:
```
function swap(sel) {
if($(sel).is(':visible')) {
$(sel).hide('drop',{direction:'left'});
} else {
$(sel).show('drop',{direction:'left'});
}
}
``` | As the other answerers have said, `toggle()` is the best solution. However if for some reason you can't/don't want to use toggle, and if your selector is for only one element:
```
function swap(sel) {
if ($(sel).is(':visible')) { // Is this element visible?
$(sel).hide('drop',{direction:'left'});
}
}
```
**Caveat:** The :visible check will return a false positive if the element or any of its parents are `:hidden`. If that's important to you, you might want to [check out this solution](http://remysharp.com/2008/10/17/jquery-really-visible/) which attempts to check for any of that, as well. | jQuery UI - a swap function that hides and unhides elements by selector | [
"",
"javascript",
"jquery",
"jquery-ui",
""
] |
I want to auto-generate a HTML table from some custom data. One of the columns in my data is a number in the range 0-100, and I'd like to show it in a more graphical way, most desirably a colored horizontal bar. The length of the bar would represent the value, and the color would also change (i.e. below 20 it's red, etc.)
Something like this (created with paint.net):
[](https://i.stack.imgur.com/HoUoM.png)
(source: [thegreenplace.net](http://eli.thegreenplace.net/files/temp/df.png))
One way this can be achieved is by generating an appropriate .PNG and placing it there as an image. But I think that it can probably be done with some concoction of HTML/CSS/Javascript in an automatic way (i.e. the values thrown into the table are numeric, and JS converts them to bars before showing).
Perhaps someone has done something like this already and can share?
Thanks in advance
P.S: If it can work in IE6, that would be best (don't ask...)
P.P.S: It should work offline, so existing webservices (like Google charts) won't help | AListApart has a great article on how to generate charts using purely CSS. It's nice because it is accessible, meaning even without CSS it will provide meaningful data.
<http://www.alistapart.com/articles/accessibledatavisualization>
**Update:** According to one of the commenters on this answer, this solution will also work in IE6. | This is doable.
2 options:
1) put an image in every cell using the img tag and resize the image using the width attribute
2) put a div with a pre-set height and change the width according to the value you want it to display. Use the background color of the div as your color - no images needed.
example:
```
<table style="border: 1px solid black">
<tr><th>name</th><th>value</th></tr>
<tr><td>hi</td><td><div style="height: 10px; width: 35px; background-color: #236611">35</div></td></tr>
<tr><td>yes</td><td><div style="height: 10px; width: 15px; background-color: #236611">15</div></td></tr>
<tr><td>see?</td><td><div style="height: 10px; width: 75px; background-color: #2366aa">75</div></td></tr>
</table>
```
... you could/should tweak the sizes to look nicer of course :-) | Turning numbers into colored bars automatically in HTML/Javascript | [
"",
"javascript",
"html",
"css",
""
] |
Is it possible to pass a function as a parameter in C#? I can do it using the Func or Action classes, but this forces me to declare the entire function signature at once. When I try to use Delegate, I get a compile error saying it can't convert a method group to a Delegate.
I'm working on [Axial](http://www.codeplex.com/axial) and I'm trying to allow users to call web services. What I'm going for is the ability to create the Visual Studio proxy class and then pass in the generated function. The function signature doesn't matter because the generated code only uses the function name. However, I'd like to pass in the function instead of the name for two reasons: the ability to use the proxy's Url property and a compiler error if the web service doesn't exist or is updated in Visual Studio.
```
public void AlertIt(object o) {
Axial.DOM.Window.Alert(o.ToString());
}
public void CallAddService() {
object[] param = new object[] { int.Parse(txtA.Text), int.Parse(txtB.Text) };
Axial.ServerScript.CallWebService(new WSProxy.WS().Add, param, AlertIt, AlertIt);
}
class Axial.ServerScript {
public void CallWebService(Delegate method, object[] param, Action<object> successCallback, Action<object> failureCallback) {
// translate to javascript (already working)
}
}
``` | I think what you want is:
```
static object InvokeMethod(Delegate method, params object[] args){
return method.DynamicInvoke(args);
}
static int Add(int a, int b){
return a + b;
}
static void Test(){
Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4));
}
```
Prints "9". | Converting a method group, anonymous method or lambda expression to a delegate requires the compiler to know the exact delegate type. However, you could potentially use lambda expressions and captured variables to make this simpler:
```
public void InvokeMethod(Action action)
{
action();
}
public int Add(int a, int b)
{
return a + b;
}
public void Test()
{
InvokeMethod(() => Add(2, 3));
}
```
That basically delays invocation in the normal way, but by wrapping the actual call to `Add` in a plain `Action` delegate.
If that doesn't fulfil your requirements, perhaps you can tell us a bit more about what you're really trying to achieve.
EDIT: If this is generated code, you can cast to a `Func<...>` with the right type arguments - assuming there aren't too many. Other than that, there's no real way of just passing in a method group. There's been occasional calls for an "infoof(...)" operator (like typeof but for members) which would give you a MemberInfo, but that doesn't actually exist. | How to pass a function as a parameter in C#? | [
"",
"c#",
"reflection",
""
] |
I have the following snippet of code that's generating the "Use new keyword if hiding was intended" warning in VS2008:
```
public double Foo(double param)
{
return base.Foo(param);
}
```
The `Foo()` function in the base class is protected and I want to expose it to a unit test by putting it in wrapper class solely for the purpose of unit testing. I.e. the wrapper class will not be used for anything else. So one question I have is: **is this accepted practice?**
Back to the `new` warning. **Why would I have to new the overriding function in this scenario?** | The `new` just makes it absolutely clear that you know you are stomping over an existing method. Since the existing code was `protected`, it isn't as big a deal - you can safely add the `new` to stop it moaning.
The difference comes when your method does something different; any variable that references the *derived* class and calls `Foo()` would do something different (even with the same object) as one that references the *base* class and calls `Foo()`:
```
SomeDerived obj = new SomeDerived();
obj.Foo(); // runs the new code
SomeBase objBase = obj; // still the same object
objBase.Foo(); // runs the old code
```
This could obviously have an impact on any existing code that knows about `SomeDerived` and calls `Foo()` - i.e. it is now running a completely different method.
Also, note that you could mark it `protected internal`, and use `[InternalsVisibleTo]` to provide access to your unit test (this is the most common use of `[InternalsVisibleTo]`; then your unit-tests can access it directly without the derived class. | The key is that you're *not* overriding the method. You're hiding it. If you were overriding it, you'd need the `override` keyword (at which point, unless it's virtual, the compiler would complain because you *can't* override a non-virtual method).
You use the `new` keyword to tell both the compiler and anyone reading the code, "It's okay, I know this is only hiding the base method and not overriding it - that's what I meant to do."
Frankly I think it's rarely a good idea to hide methods - I'd use a different method name, like Craig suggested - but that's a different discussion. | Use new keyword if hiding was intended | [
"",
"c#",
"inheritance",
"warnings",
"new-operator",
""
] |
How do I force my application to run as 32-bit on a 64-bit machine?
The code is written in C#. | Right click your project, and select properties.
In properties, select the build tab. Under platform target, select x86.
Hit `Ctrl`+`Shift`+`S` to save all files, right click the solution and select "Clean" to get rid of old binaries. Any builds after that should be 32 bit | Command-line form:
```
corflags application.exe /32BIT+
```
(reference: <https://learn.microsoft.com/en-us/dotnet/framework/tools/corflags-exe-corflags-conversion-tool>) | Running a C# application as 32-bit on a 64-bit machine | [
"",
"c#",
".net",
"process",
"x86",
"32bit-64bit",
""
] |
On my java project, I have a bunch of strings externalized on a `messages.properties` file. On its respective `Messages.java` file I had the same number of public static String-typed attributes, so I could access those externalized texts.
Then, I implemented a method called `getString`, which receives the name of the constant as its argument and returns the wanted text. This way, there is no need to declare all the public static Strings-typed attributes inside the `Messages.java` file.
But after doing this my log became filled with "*NLS unused message*" messages.
Do you know if there's a way to prevent those warning messages to be logged?
Thanks in advance. | Messages sounds like a class you wrote, because I don't see it in my JDK 6 javadocs.
It sounds like you've tried to reinvent java.util.ResourceBundle. I'd recommend using that instead and ditching your class. It'll have the added advantage of handling I18N properly.
I don't see any value in hard-coding the public static message keys in the class. It's just another thing you'll have to maintain. If I understand what you're doing properly, I'd throw away your Messages and use ResourceBundle instead. | Your `Messages` class - it sounds like it extends `org.eclipse.osgi.util.NLS`.
If this is the case, it is designed to fill the requirements:
* to provide compile time checking that a message exists.
* to avoid the memory usage of a map containing both keys and values (this would be the case in a resource bundle approach).
* good i18n support.
i.e. NLS populates the value of the `Message.staticVariable` with the value of the `staticVariable` found in messages.properties.
The warning logging provides information about a mismatch between the `Messages.java` and the `messages.properties` file.
Your `getString()` method sounds like it does not use any of the advantages of NLS, so as others have suggested, you may be better off using a ResourceBundle. | How do I avoid unwanted log messages on java project? | [
"",
"java",
"nls",
""
] |
I would like to use `Dictionary` as `TKey` in another `Dictionary`. Something similar to python. I tried this but it gives me errors.
```
Dictionary<Dictionary<string, string>, int> dict = new Dictionary<Dictionary<string, string>, int>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["abc"] = "def";
dict[dict["abc"] = 20;
``` | What error is it giving you? Is it complaining about your missing bracket on line 4?
Line 4 looks like it should be:
```
dict[dict["abc"]] = 20;
```
However, you probably mean this, since "abc" is not a key of dict:
```
dict[dict2["abc"]] = 20;
```
But `dict2["abc"]` is a `string`, when the key of dict is supposed to be a `Dictionary<string, string>`.
But let's re-examine your original goal at this point before going to far down this path. You shouldn't be using mutable types as dictionary keys in the first place.
This may be the code you're looking for:
```
Dictionary<string, int> dict = new Dictionary<string, int>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["abc"] = "def";
dict[dict2["abc"]] = 20;
```
But it's hard to tell for sure. | Just to throw this in there, I often find that dealing with complicated dictionaries like you describe it's far better to use real names with them rather than trying to let the reader of the code sort it out.
You can do this one of two ways depending on personal preference. Either with a using statement to create a complier alias. Note you have to use the fully qualified type name since this is a compiler alias.
```
using ComplexKey = System.Collections.Generic.Dictionary<String, String>;
using ComplexType = System.Collections.Generic.Dictionary<
System.Collections.Generic.Dictionary<String, String>,
String
>;
```
Or you can go the full blown type way and actually create a class that inherits from Dictionary.
```
class ComplexKey : Dictionary<String, String> { ... }
class ComplexType : Dictionary<ComplexKey, String> { ... }
```
Doing this will make it far easier for both you and the reader of your code to figure out what you're doing. My general rule of thumb is if I'm creating a generic of a generic it's time to look at building some first class citizens to represent my logic rather. | using dictionary as a key in other dictionary | [
"",
"c#",
"dictionary",
""
] |
How do I get an old VC++ 6.0 MFC program to read and display UTF8 in a TextBox or MessageBox? Preferably without breaking any of the file reading and displaying that is currently written in there (fairly substantial).
I read a line into CString strStr, then used this code:
```
int nLengthNeeded = MultiByteToWideChar(CP_UTF8,0,strStr,1024,0,0);
wchar_t * pWCMessage = new wchar_t[ nLengthNeeded ];
MultiByteToWideChar(CP_UTF8,0,strStr,1024,pWCMessage,nLengthNeeded);
nLengthNeeded = MultiByteToWideChar(CP_UTF8,0,"Error Title",50,0,0);
wchar_t * pWCTitle = new wchar_t[ nLengthNeeded ];
MultiByteToWideChar(CP_UTF8,0,"Error Title",50,pWCTitle,nLengthNeeded);
MessageBoxW(NULL,pWCMessage,pWCTitle,MB_ICONINFORMATION);
```
Still not sure how I would get it into a textbox, but it turns out I don't need to do that anyway. | I feel like this won't be helpful, but it's a starting point... I'm assuming it doesn't 'just work', and I don't think you want to try to screw around with wacky code pages that may or may not get you what you want.
How about just using MultiByteToWideChar(CP\_UTF8, ...) to convert it to utf16 and then calling the W versions of those functions (or defining UNICODE/\_UNICODE for the project).
I know that will work for MessageBox, and I can't imagine the text box doesn't have unicode support.
If you need to get the output back to UTF8 - just use WideCharToMultiByte(). | take a look at:
[widechartomultibyte](http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx) and [for more general info](http://msdn.microsoft.com/en-us/library/ey142t48.aspx)
when/if you run into trouble, make sure you post your code. It's been a while since I did that and I remember it being a bit tricky. | UTF-8 From File to TextBox VC++ 6.0 | [
"",
"c++",
"mfc",
"utf-8",
"visual-c++-6",
""
] |
I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)?
```
>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)'
>>> addrs = "Zip: 10010 State: NY"
>>> y = re.search(my_regex, addrs)
>>> y.groupdict('zip')
{'zip': 'Zip: 10010'}
>>> y.group(2)
'State: NY'
``` | regex definition:
```
(?P<zip>...)
```
Creates a named group "zip"
```
Zip:\s*
```
Match "Zip:" and zero or more whitespace characters
```
\d
```
Match a digit
```
\w
```
Match a word character [A-Za-z0-9\_]
```
y.groupdict('zip')
```
The groupdict method returns a dictionary with named groups as keys and their matches as values. In this case, the match for the "zip" group gets returned
```
y.group(2)
```
Return the match for the second group, which is a unnamed group "(...)"
Hope that helps. | The **search** method will return an object containing the results of your regex pattern.
**groupdict** returns a dictionnary of groups where the keys are the name of the groups defined by (?P...). Here *name* is a name for the group.
**group** returns a list of groups that are matched. "State: NY" is your third group. The first is the entire string and the second is "Zip: 10010".
This was a relatively simple question by the way. I simply looked up the method documentation on google and found [this page](http://pydoc.org/1.6/pre.html). Google is your friend. | Python-Regex, what's going on here? | [
"",
"python",
"regex",
""
] |
I'm using Spring + JPA + Hibernate. I'm trying to enable Hibernate's second level cache. In my Spring's `applicationContext.xml` I have:
```
<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>
```
When I run I get the error:
```
Caused by: org.hibernate.HibernateException: Could not instantiate cache implementation
at org.hibernate.cache.CacheFactory.createCache(CacheFactory.java:64)
Caused by: org.hibernate.cache.NoCachingEnabledException: Second-level cache is not enabled for usage [hibernate.cache.use_second_level_cache | hibernate.cache.use_query_cache]
at org.hibernate.cache.NoCacheProvider.buildCache(NoCacheProvider.java:21)
```
So it's complain I don't have second level cache enabled. I attempt to enable it by adding to my `applicationContext.xml`:
```
<prop key="hibernate.cache.use_second_level_cache">true</prop>
```
But still no joy. I also tried adding this to my ehcache.xml:
```
<property name="hibernate.cache.use_second_level_cache">true</property>
```
But it still doesn't work. Changing the `provider_class` to `org.hibernate.cache.EhCacheProvider` doesn't help either:
```
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
```
My entity classes are annotated to use caching
```
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
```
So, how do I enable second level cache?
**Edit:** This is under the bean:
```
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
```
**Resolved:** Since I'm using `LocalEntityManagerFactoryBean` it gets its settings from `META-INF/persistence.xml`. My settings in `applicationContext.xml` weren't even being read. | I didn't answer this, but it's not obvious that the poster found the answer himself. I'm reposting his answer:
### Resolved
Since I'm using `LocalEntityManagerFactoryBean` it gets its settings from `META-INF/persistence.xml`. My settings in `applicationContext.xml` weren't even being read. | Try this:
```
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.max_fetch_depth">4</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
```
And if you are using Maven add this to your POM file:
```
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.3.0</version>
</dependency>
```
Or download the latest jar from <http://ehcache.org/> | Hibernate second level cache with Spring | [
"",
"java",
"hibernate",
"spring",
"jpa",
"jakarta-ee",
""
] |
I need a basic example of how to use the `IComparable` interface so that I can sort in ascending or descending order and by different fields of the object type I'm sorting. | Well, since you are using `List<T>` it would be a lot simpler to just use a `Comparison<T>`, for example:
```
List<Foo> data = ...
// sort by name descending
data.Sort((x,y) => -x.Name.CompareTo(y.Name));
```
Of course, with LINQ you could just use:
```
var ordered = data.OrderByDescending(x=>x.Name);
```
But you can re-introduce this in `List<T>` (for in-place re-ordering) quite easily; Here's an example that allows `Sort` on `List<T>` with lambda syntax:
```
using System;
using System.Collections.Generic;
class Foo { // formatted for vertical space
public string Bar{get;set;}
}
static class Program {
static void Main() {
List<Foo> data = new List<Foo> {
new Foo {Bar = "abc"}, new Foo {Bar = "jkl"},
new Foo {Bar = "def"}, new Foo {Bar = "ghi"}
};
data.SortDescending(x => x.Bar);
foreach (var row in data) {
Console.WriteLine(row.Bar);
}
}
static void Sort<TSource, TValue>(this List<TSource> source,
Func<TSource, TValue> selector) {
var comparer = Comparer<TValue>.Default;
source.Sort((x,y)=>comparer.Compare(selector(x),selector(y)));
}
static void SortDescending<TSource, TValue>(this List<TSource> source,
Func<TSource, TValue> selector) {
var comparer = Comparer<TValue>.Default;
source.Sort((x,y)=>comparer.Compare(selector(y),selector(x)));
}
}
``` | Here's a simple example:
```
public class SortableItem : IComparable<SortableItem>
{
public int someNumber;
#region IComparable<SortableItem> Members
public int CompareTo(SortableItem other)
{
int ret = -1;
if (someNumber < other.someNumber)
ret = -1;
else if (someNumber > other.someNumber)
ret = 1;
else if (someNumber == other.someNumber)
ret = 0;
return ret;
}
#endregion
}
```
*"That's great, but what if I want to be able to control the sort order, or sort by another field?"*
Simple. All we need to do is add few more fields to the object. First we'll add a string for a different sort type and then we'll add a boolean to denote whether we're sorting in descending or ascending order and then add a field which determines which field we want to search by.
```
public class SortableItem : IComparable<SortableItem>
{
public enum SortFieldType { SortNumber, SortString }
public int someNumber = -1;
public string someString = "";
public bool descending = true;
public SortFieldType sortField = SortableItem.SortFieldType.SortNumber;
#region IComparable<SortableItem> Members
public int CompareTo(SortableItem other)
{
int ret = -1;
if(sortField == SortableItem.SortFieldType.SortString)
{
// A lot of other objects implement IComparable as well.
// Take advantage of this.
ret = someString.CompareTo(other.someString);
}
else
{
if (someNumber < other.someNumber)
ret = -1;
else if (someNumber > other.someNumber)
ret = 1;
else if (someNumber == other.someNumber)
ret = 0;
}
// A quick way to switch sort order:
// -1 becomes 1, 1 becomes -1, 0 stays the same.
if(!descending) ret = ret * -1;
return ret;
}
#endregion
public override string ToString()
{
if(sortField == SortableItem.SortFieldType.SortString)
return someString;
else
return someNumber.ToString();
}
}
```
*"Show me how!"*
Well since you asked so nicely.
```
static class Program
{
static void Main()
{
List<SortableItem> items = new List<SortableItem>();
SortableItem temp = new SortableItem();
temp.someString = "Hello";
temp.someNumber = 1;
items.Add(temp);
temp = new SortableItem();
temp.someString = "World";
temp.someNumber = 2;
items.Add(temp);
SortByString(items);
Output(items);
SortAscending(items);
Output(items);
SortByNumber(items);
Output(items);
SortDescending(items);
Output(items);
Console.ReadKey();
}
public static void SortDescending(List<SortableItem> items)
{
foreach (SortableItem item in items)
item.descending = true;
}
public static void SortAscending(List<SortableItem> items)
{
foreach (SortableItem item in items)
item.descending = false;
}
public static void SortByNumber(List<SortableItem> items)
{
foreach (SortableItem item in items)
item.sortField = SortableItem.SortFieldType.SortNumber;
}
public static void SortByString(List<SortableItem> items)
{
foreach (SortableItem item in items)
item.sortField = SortableItem.SortFieldType.SortString;
}
public static void Output(List<SortableItem> items)
{
items.Sort();
for (int i = 0; i < items.Count; i++)
Console.WriteLine("Item " + i + ": " + items[i].ToString());
}
}
``` | How do I use the IComparable interface? | [
"",
"c#",
".net",
"icomparable",
""
] |
I am trying to find out programatically the max permgen and max heap size with which a the JVM for my program has been invoked, not what is currently available to them.
Is there a way to do that?
I am familiar with the methods in Java Runtime object, but its not clear what they really deliver.
Alternatively, is there a way to ask Eclipse how much was allocated for these two? | Try this ones:
```
MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
mem.getHeapMemoryUsage().getUsed();
mem.getNonHeapMemoryUsage().getUsed();
```
But they only offer snapshot data, not a cummulated value. | Try something like this for max perm gen:
```
public static long getPermGenMax() {
for (MemoryPoolMXBean mx : ManagementFactory.getMemoryPoolMXBeans()) {
if ("Perm Gen".equals(mx.getName())) {
return mx.getUsage().getMax();
}
}
throw new RuntimeException("Perm gen not found");
}
```
For max heap, you can get this from Runtime, though you can also use the appropriate MemoryPoolMXBean. | How to get the max sizes of the heap and permgen from the JVM? | [
"",
"java",
"memory-management",
"jvm",
""
] |
I want to get hold of the mouse position in a timeout callback.
As far as I can tell, this can't be done directly. One work around might be to set an onmousemove event on document.body and to save this position, fetching later. This would be rather expensive however, and isn't the cleanest of approaches. | I think you'll have to do the same thing as @Oli, but then if you're using jQuery, it would be much more easier.
<http://docs.jquery.com/Tutorials:Mouse_Position>
```
<script type="text/javascript">
jQuery(document).ready(function(){
$().mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
</script>
``` | The direct answer is **no** but as you correctly say, you can attach events to everything and poll accordingly. It *would* be expensive to do serious programming on every onmousemove instance so you might find it better to create several zones around the page and poll for a onmouseover event.
Another alternative would be to (and I'm not sure if this works at all) set a recurring timeout to:
1. Add a onmousemove handler to body
2. Move the entire page (eg change the body's margin-top)
3. when the onmousemove handler triggers, get the position and remove the handler. You might need a timeout on this event too (for when the mouse is out of the viewport)
Uberhack but it *might* work. | Javascript: Is it possible to get hold of the mouse position outside of an event handler? | [
"",
"javascript",
"events",
"mouse",
""
] |
**Follow up to**: [How to safely update a file that has many readers and one writer?](https://stackoverflow.com/questions/421357/how-to-safely-update-a-file-that-has-many-readers-and-one-writer)
In my previous questions, I figured out that you can use FileChannel's lock to ensure an ordering on reads and writes.
But how do you handle the case if the writer fails mid-write (say the JVM crashes)? This basic algorithm would look like,
```
WRITER:
lock file
write file
release file
READER:
lock file
read file
release file
```
If the JVM crashes during `write file`, sure the lock would be released, but now I have an incomplete file. I want something complete to always be readable. Either the old content the new content and nothing in between.
My first strategy was to write to a temporary file, and then copy the contents into the "live" file (while ensure good locking). The algorithm for this is,
```
WRITER:
lock temp file
write temp file
lock file
copy temp to file
release file
release temp
delete temp
READER:
lock file
read file
release file
```
One nice thing is the `delete temp` won't delete the temp if it has already been locked by another writer.
But that algorithm doesn't handle if the JVM crashes during `copy temp to file`. So then I added a `copying` flag,
```
WRITER:
lock temp file
write temp file
lock file
create copying flag
copy temp to file
delete copying flag
release file
release temp
delete temp
READER:
lock file
if copying flag exists
copy temp to file
delete copying flag
delete temp
end
read file
release file
```
There won't ever be two things accessing the `copying` file as it is guarded by the file lock.
Now, is this the way to do it? It seems very complicated to ensure something very simple. Is there some Java library that handles this for me?
**EDIT**
Well, I managed I make a mistake in my third attempt. The reader doesn't hold the lock to temp when it does `copy temp to file`. Also its not a simple fix to simply lock the temp file! That would cause the writer and reader to acquire locks in different orders and can lead to deadlock. This is getting more complicated all the time. Here's my fourth attempt,
```
WRITER:
lock file
write temp file
create copying flag
copy temp to file
delete copying flag
delete temp
release file
READER:
lock file
if copying flag exists
copy temp to file
delete copying flag
delete temp
end
read file
release file
```
This time the temp file is guarded by main lock, so it doesn't even need its own lock.
**EDIT 2**
When I say JVM crash, I actually mean say the power went out and you didn't have a UPS.
**EDIT 3**
I still managed to make another mistake. You shouldn't lock on the file you are writing to or reading from. This will cause problems, since you can't get both the read and write lock unless you use RandomAccessFile in Java, which does not implement Input/Output stream.
What you want to do instead is just lock on a lock file that guards the file you are read or writing. Here's the updated algorithm:
```
WRITER:
lock
write temp file
create copying flag
copy temp to file
delete copying flag
delete temp
release
READER:
lock
if copying flag exists
copy temp to file
delete copying flag
delete temp
end
read file
release
```
lock and release guards the file, the temp file and the copying flag. The only problem is now the reader lock can't be shared, but it never could be really. The reader always had a chance to modify the file, therefore it would have been wrong to make a shareable lock in the first place. | despite the fact that there is no bullet-proof, cross-OS, cross-FS solution, the "write to unique temp file and rename" strategy is still your best option. most platforms/filesystems attempt to make file renaming (effectively) atomic. note, you want to use a +separate+ lock file for locking.
so, assuming you want to update "myfile.txt":
* lock "myfile.txt.lck" (this is a separate, empty file)
* write changes to a unique temp file, e.g. "myfile.txt.13424.tmp" (use `File.createTempFile()`)
* for extra protection, but possibly slower, fsync the temp file before proceeding (`FileChannel.force(true)`).
* rename "myfile.txt.13424.tmp" to "myfile.txt"
* unlock "myfile.txt.lck"
on certain platforms (windows), you need to do a little more dancing due restrictions on file ops (you can move "myfile.txt" to "myfile.txt.old" before renaming, and use the ".old" file to recover from if you need to when reading). | I don't think there is a perfect answer. I don't exactly know what you need to do, but can you do the writing to a new file, and then on success, rename files, rather than copying. Renaming is quick, and hence should be less prone a crash. This still won't help if it fails at the rename stage, but you've minimized the window of risk.
Again, I'm not sure if it is applicable or relevant to your needs, but can you write some file block at the end of the file to show all the data has been written? | How to ensure file integrity on file write failures? | [
"",
"java",
"file",
"locking",
"integrity",
""
] |
Let's say I have some Java code:
```
public class SomeClass {
static {
private final double PI = 3.14;
private final double SOME_CONSTANT = 5.76;
private final double SOME_OTHER_CONSTANT = 756.33;
}
//rest of class
}
```
If a thread is initializing SomeClass's `Class` object and is in the middle of initializing the values in the static block when a second thread wants to load SomeClass's `Class` again, what happens to the static block? Does the second thread ignore it assuming it's already initialized even though the first thread is not done? Or does something else happen? | If the first thread hasn't finished initializing SomeClass, the second thread will block.
This is detailed in the Java Language Specification in [section 12.4.2](http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2). | Static class initialization is guaranteed to be thread-safe by Java. | Thread safety of static blocks in Java | [
"",
"java",
"multithreading",
"static",
""
] |
I have an array of doubles and I want the index of the highest value. These are the solutions that I've come up with so far but I think that there must be a more elegant solution. Ideas?
```
double[] score = new double[] { 12.2, 13.3, 5, 17.2, 2.2, 4.5 };
int topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderByDescending(x => x.Item).Select(x => x.Index).First();
topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderBy(x => x.Item).Select(x => x.Index).Last();
double maxVal = score.Max();
topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).Where(x => x.Item == maxVal).Select(x => x.Index).Single();
``` | I suggest writing your own extension method (edited to be generic with an `IComparable<T>` constraint.)
```
public static int MaxIndex<T>(this IEnumerable<T> sequence)
where T : IComparable<T>
{
int maxIndex = -1;
T maxValue = default(T); // Immediately overwritten anyway
int index = 0;
foreach (T value in sequence)
{
if (value.CompareTo(maxValue) > 0 || maxIndex == -1)
{
maxIndex = index;
maxValue = value;
}
index++;
}
return maxIndex;
}
```
Note that this returns -1 if the sequence is empty.
A word on the characteristics:
* This works with a sequence which can only be enumerated once - this can sometimes be very important, and is generally a desirable feature IMO.
* The memory complexity is O(1) (as opposed to O(n) for sorting)
* The runtime complexity is O(n) (as opposed to O(n log n) for sorting)
As for whether this "is LINQ" or not: if it had been included as one of the standard LINQ query operators, would you count it as LINQ? Does it feel particularly alien or unlike other LINQ operators? If MS were to include it in .NET 4.0 as a new operator, would it be LINQ?
EDIT: If you're really, really hell-bent on using LINQ (rather than just getting an elegant solution) then here's one which is still O(n) and only evaluates the sequence once:
```
int maxIndex = -1;
int index=0;
double maxValue = 0;
int urgh = sequence.Select(value => {
if (maxIndex == -1 || value > maxValue)
{
maxIndex = index;
maxValue = value;
}
index++;
return maxIndex;
}).Last();
```
It's hideous, and I don't suggest you use it at all - but it will work. | Meh, why make it overcomplicated? This is the simplest way.
```
var indexAtMax = scores.ToList().IndexOf(scores.Max());
```
Yeah, you could make an extension method to use less memory, but unless you're dealing with huge arrays, you will *never* notice the difference. | How do I get the index of the highest value in an array using LINQ? | [
"",
"c#",
"linq",
""
] |
I have several objects in the database. Url to edit an object using the generic view looks like `site.com/cases/edit/123/` where `123` is an id of the particular object. Consider the `cases/url.py` contents:
```
url(r'edit/(?P<object_id>\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'),
```
where `update_object` is a generic view. How to construct the `post_save_redirect` to point to `site.com/cases/edit/123/`. My problem is, that I don't know how to pass the `id` of the object to redirect function. I tried something like:
```
'post_save_redirect': 'edit/(?P<object_id>\d{1,5})/'
'post_save_redirect': 'edit/' + str(object_id) + '/'
```
but obviously none of these work. `reverse` function was suggested, but how to pass the particular `id`?
```
'post_save_redirect': reverse('cases_edit', kwargs = {'object_id': ???})
```
`{% url %}` in the temple also requires passing the `id` of the particular object. The `id` can be passed via `extra_context`:
```
extra_context = {'object_id': ???}
```
In all the cases the problem is to get `object_id` from the url.
regards
chriss | In short what you need to do is wrap the update\_object function.
```
def update_object_wrapper(request, object_id, *args, **kwargs):
redirect_to = reverse('your object edit url name', object_id)
return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs)
``` | First, read up on the [reverse](http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse) function.
Second, read up on the `{%` [url](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url) `%}` tag.
You use the `reverse` function in a view to generate the expected redirect location.
Also, you should be using the `{% url %}` tag in your templates. | how to pass id from url to post_save_redirect in urls.py | [
"",
"python",
"django",
"django-urls",
""
] |
We have a webapp where people can upload various image file types and on the backend we convert them to a standard type (typically png or jpeg). Right now we are using ImageIO to do this. However the new requirement is to be able to support eps files. I haven't found any libraries that support EPS in ImageIO, or much in the way of support for reading eps files in java.
Any suggestions for reading eps files and converting them? | I'm pretty sure ImageMagick (a C library) can do that (though I believe it requires GhostScript), and there's a JNI wrapper for ImageMagick called [JMagick](http://www.jmagick.org/index.html) that allows access to ImageMagick from Java. If you can deal with JNI, JMagick might do the trick. | [Freehep](http://java.freehep.org/freehep1.x/) has a [Java PostScript Viewer](http://java.freehep.org/freehep1.x/psviewer/) that you might be able to rework into a PS converter. | Need to convert EPS files to jpg/png in Java | [
"",
"java",
"eps",
""
] |
SO has plenty of Q&As about how to accomplish various tasks using dynamic SQL, frequently the responses are accompanied with warnings and disclaimers about the advisability of actually using the approach provided. I've worked in environments ranging from "knowing how to use a cursor is a bad sign" to "isn't sp\_executesql neat!".
When it comes to production systems should dynamic sql always be avoided or should it have a valid place in the programming toolbox. If not/so, Why? | Answers to some of your questions can be found here [The Curse and Blessings of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html)
Sometimes you have to use dynamic SQL because it will perform better | It depends on what you mean by dynamic sql. Queries built where parameter values substituted directly into the sql string are dangerous and should be avoided except for the very rare case where there is no other option.
Dynamic SQL using the appropriate parameterized query mechanism supported by your platform can be very powerful. | Dynamic SQL in production systems | [
"",
"sql",
""
] |
I need ideas to implement a (really) high performance in-memory Database/Storage Mechanism in Java. In the range of storing 20,000+ java objects, updated every 5 or so seconds.
Some options I am open to:
Pure JDBC/database combination
JDO
JPA/ORM/database combination
An Object Database
Other Storage Mechanisms
What is my best option? What are your experiences?
EDIT: I also need like to be able to Query these objects | You could try something like [Prevayler](http://prevayler.org/old_wiki/Welcome.html) (basically an in-memory cache that handles serialization and backup for you so data persists and is transactionally safe). There are other similar projects.
I've used it for a large project, it's safe and extremely fast.
If it's the same set of 20,000 objects, or at least not 20,000 new objects every 5 seconds but lots of changes, you might be better off cacheing the changes and periodically writing the changes in batch mode (jdbc batch updates are much faster than individual row updates). Depends on whether you need each write to be transactionally wrapped, and whether you'll need a record of the change logs or just aggregate changes.
**Edit**: as other posts have mentioned Prevayler I thought I'd leave a note on what it does:
Basically you create a searchable/serializable object (typically a Map of some sort) which is wrapped in a Prevayler instance, which is serialized to disk. Rather than making changes directly to your map, you make changes by sending your Prevayler instance a serializable record of your change (just an object that contains the change instruction). Prevayler's version of a transaction is to write your serialization changes to disk so that in the event of failure it can load the last complete backup and then replay the changes against that. It's safe, although you do have to have enough memory to load all of your data, and it's a fairly old API, so no generic interfaces, unfortunately. But definitely stable and works as advertised. | I highly recommend **[H2](http://www.h2database.com/html/main.html)**. This is a kind of "second generation" version of HSQLDB done by one of the original authors. **H2** allows us to unit-test our DAO layer without requiring an actual PostgreSQL database, which is **awesome**.
There is an active net group and mailing list, and the author Thomas Mueller is very responsive to queries (hah, little pun there.) | Highest Performance Database in Java | [
"",
"java",
"database",
"performance",
"embedded-database",
""
] |
I'm used to using Telerik Grids and I'm able to display them in an outlook style, i.e. a picture on the far left, a bold title and a few other lines of text under the main title.
Is there a way do this using a standard .Net2.0 Windows control? Either with a cheap control, or the existing datagridview or listview?
Basically, I need to be able to produce a layout as follows:
```
Job Title
Engineer: Fred Bloggs
Product: Some random product
```
So, I'll have 2000 or so of these items in a grid with a status image next to each of them, what's the best way to achieve this? | Here is help with using a listview for the list. I would go with the list because you will only have one column, so no need for the grid.
You want to use :
```
private void lstItems_DrawItem(object sender, DrawItemEventArgs e)
```
Then use the e.Graphics to get an object you can draw directly to.
I used this [tutorial](http://www.codeproject.com/KB/books/1930110286_10.aspx) to help me learn about drawing in the ListView | I can't give you an example as I don't have time to write it at this time, but you could create a UserControl which lays out the row as you would like to see it. Then you would have to create your own DataGridViewCell which can handle a UserControl rather than the standard cell types which MS provides. For each of your entries, create and fill the user control and add it to another row in the DataGridView. | DataGridView/ListView - Display in an Outlook style? | [
"",
"c#",
"visual-studio",
"datagridview",
"datagridviewcolumn",
""
] |
What is a reasonable amount of time to wait for a web request to return? I know this is maybe a little loaded as a question, but all I am trying to do is verify if a web page is available.
Maybe there is a better way?
```
try
{
// Create the web request
HttpWebRequest request = WebRequest.Create(this.getUri()) as HttpWebRequest;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
// 2 minutes for timeout
request.Timeout = 120 * 1000;
if (request != null)
{
// Get response
response = request.GetResponse() as HttpWebResponse;
connectedToUrl = processResponseCode(response);
}
else
{
logger.Fatal(getFatalMessage());
string error = string.Empty;
}
}
catch (WebException we)
{
...
}
catch (Exception e)
{
...
}
``` | You need to consider how long the consumer of the web service is going to take e.g. if you are connecting to a DB web server and you run a lengthy query, you need to make the web service timeout longer then the time the query will take. Otherwise, the web service will (erroneously) time out.
I also use something like (consumer time) + 10 seconds. | Offhand I'd allow 10 seconds, but it really depends on what kind of network connection the code will be running with. Try running some test pings over a period of a few days/weeks to see what the typical response time is. | Timeout for Web Request | [
"",
"c#",
""
] |
I am using the (.NET 3.5 SP1) System.Xml.Linq namespace to populate an html template document with div tags of data (and then save it to disk). Sometimes the div tags are empty and this seems to be a problem when it comes to HTML. According to my research, the DIV tag is not self-closing. Therefore, under Firefox at least, a `<div />` is considered an opening div tag without a matching closing tag.
So, when I create new div elements by declaring:
```
XElement divTag = new XElement("div");
```
**How can I force the generated XML to be `<div></div>` instead of `<div />` ?** | I'm not sure why you'd end up with an empty DIV (seems a bit pointless!) But:
```
divTag.SetValue(string.Empty);
```
Should do it. | With
XElement divTag = new XElement("div", String.Empty);
you get the explicit closing tag | Explicit Element Closing Tags with System.Xml.Linq Namespace | [
"",
"c#",
"xml",
"linq-to-xml",
""
] |
How do I read the response headers returned from a PyCurl request? | There are several solutions (by default, they are dropped). Here is an
example using the option HEADERFUNCTION which lets you indicate a
function to handle them.
Other solutions are options WRITEHEADER (not compatible with
WRITEFUNCTION) or setting HEADER to True so that they are transmitted
with the body.
```
#!/usr/bin/python
import pycurl
import sys
class Storage:
def __init__(self):
self.contents = ''
self.line = 0
def store(self, buf):
self.line = self.line + 1
self.contents = "%s%i: %s" % (self.contents, self.line, buf)
def __str__(self):
return self.contents
retrieved_body = Storage()
retrieved_headers = Storage()
c = pycurl.Curl()
c.setopt(c.URL, 'http://www.demaziere.fr/eve/')
c.setopt(c.WRITEFUNCTION, retrieved_body.store)
c.setopt(c.HEADERFUNCTION, retrieved_headers.store)
c.perform()
c.close()
print retrieved_headers
print retrieved_body
``` | ```
import pycurl
from StringIO import StringIO
headers = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.HEADER, 1)
c.setopt(c.NOBODY, 1) # header only, no body
c.setopt(c.HEADERFUNCTION, headers.write)
c.perform()
print headers.getvalue()
```
Add any other curl setopts as necessary/desired, such as FOLLOWLOCATION. | How to read the header with pycurl | [
"",
"python",
"curl",
"pycurl",
""
] |
I would like to print my Swing JComponent via iText to pdf.
```
JComponent com = new JPanel();
com.add( new JLabel("hello") );
PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream( dFile ) );
document.open( );
PdfContentByte cb = writer.getDirectContent( );
PdfTemplate tp = cb.createTemplate( pageImageableWidth, pageImageableHeight );
Graphics2D g2d = tp.createGraphics( pageImageableWidth, pageImageableHeight, new DefaultFontMapper( ) );
g2d.translate( pf.getImageableX( ), pf.getImageableY( ) );
g2d.scale( 0.4d, 0.4d );
com.paint( g2d );
cb.addTemplate( tp, 25, 200 );
g2d.dispose( );
```
Unfortunately nothing is shown in the PDF file.
Do you know how to solve this problem? | I have figured it out adding addNotify and validate helps.
```
com.addNotify( );
com.validate( );
``` | I needed to call
```
com.addNotify()
com.setSize()
com.validate()
``` | How do I paint Swing Components to a PDF file with iText? | [
"",
"java",
"swing",
"pdf",
"pdf-generation",
"itext",
""
] |
I'm working on an application that loads untrusted assemblies via an interface. Each of those assemblies should be able to add one or more GameAction objects to a thread-safe queue used by the server.
The first iteration of design was to just pass the queue--something like this:
```
public interface IGameClient
{
void HandleStateChange(IGameState gameState,
ref Queue<IGameAction> actionQueue);
}
```
But, the problem with this is that it gives an untrusted assembly access to a shared queue, allowing it to manipulate other members of the queue and discover information about other queue actions.
The second pass was:
```
public interface IGameClient
{
void HandleStateChange(IGameState gameState);
GameActionDelegate event HasNewEvent; // passes IGameAction as a parameter
}
```
The problem with this is that it doesn't necessarily allow for the ordering or grouping of actions.
What I'm really hoping for is to be able to pass a reference to an object that encapsulates the thread-safe queue, but only exposes Enqueue(). But, I'm afraid that an untrusted assembly could manipulate a private Queue object using reflection.
So, what's the best way to handle this? | Thoughts in no particular order:
1) Events *do* guarantee ordering (or at least, your implementation could guarantee whatever ordering you want, and the simplest implementations will preserve ordering).
2) I don't see why you'd want to pass the queue by reference in the first example of the interface. It may be worth checking that you understand [parameter passing and "ref"](http://pobox.com/~skeet/csharp/threads/parameters.html).
3) If you come up with an interface which only exposes Enqueue then the implementation presumably won't *be* a `Queue<T>`. It might *contain* a `Queue<T>`, but if you really don't trust assemblies not to mess around with your private members, you should load them in such a way that you don't grant them the relevant reflection permissions.
Another alternative might be to pass in an `Action<IGameAction>` which the client can call when it wants to add an item to the queue. The delegate would be created from whatever Enqueue method you've got. | Don't expose the queue at all--simply expose a method on a facade that allows the GameClient to submit an entry that the GameServer will place on the internal queue. | Write-only queue? | [
"",
"c#",
".net",
"security",
""
] |
I think I am being a bonehead, maybe not importing the right package, but when I do...
```
from pysqlite2 import dbapi2 as sqlite
import types
import re
import sys
...
def create_asgn(self):
stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)"
stmt2 = "insert into asgn values ('?', ?)"
self.cursor.execute(stmt, (sys.argv[2],))
self.cursor.execute(stmt2, [sys.argv[2], sys.argv[3]])
...
I get the error pysqlite2.dbapi2.OperationalError: near "?": syntax error
```
This makes very little sense to me, as the docs show that pysqlite is qmark parametrized. I am new to python and db-api though, help me out! THANKS | That's because parameters can only be passed to VALUES. The table name can't be parametrized.
Also you have quotes around a parametrized argument on the second query. Remove the quotes, escaping is handled by the underlining library automatically for you. | Try removing the quotes in the line that assigns to `stmt2`:
```
stmt2 = "insert into asgn values (?, ?)"
```
Also, as nosklo says, you can't use question-mark parameterisation with CREATE TABLE statements. Stick the table name into the SQL directly. | Python pysqlite not accepting my qmark parameterization | [
"",
"python",
"sqlite",
"pysqlite",
"python-db-api",
""
] |
Is there a [ternary conditional operator](https://en.wikipedia.org/wiki/%3F:#Python) in Python? | Yes, it was [added](https://mail.python.org/pipermail/python-dev/2005-September/056846.html "[Python-Dev] Conditional Expression Resolution") in version 2.5. The expression syntax is:
```
a if condition else b
```
First `condition` is evaluated, then exactly one of either `a` or `b` is evaluated and returned based on the [Boolean](https://en.wikipedia.org/wiki/Boolean_data_type "Boolean data type") value of `condition`. If `condition` evaluates to `True`, then `a` is evaluated and returned but `b` is ignored, or else when `b` is evaluated and returned but `a` is ignored.
This allows short-circuiting because when `condition` is true only `a` is evaluated and `b` is not evaluated at all, but when `condition` is false only `b` is evaluated and `a` is not evaluated at all.
For example:
```
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
```
Note that conditionals are an *expression*, not a *statement*. This means you can't use **statements** such as `pass`, or assignments with `=` (or "augmented" assignments like `+=`), within a conditional **expression**:
```
>>> pass if False else pass
File "<stdin>", line 1
pass if False else pass
^
SyntaxError: invalid syntax
>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression
>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
File "<stdin>", line 1
(x = 1) if False else (y = 2)
^
SyntaxError: invalid syntax
```
(In 3.8 and above, the `:=` "walrus" operator allows simple assignment of values *as an expression*, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)
Similarly, because it is an expression, the `else` part is *mandatory*:
```
# Invalid syntax: we didn't specify what the value should be if the
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True
```
You can, however, use conditional expressions to assign a variable like so:
```
x = a if True else b
```
Or for example to return a value:
```
# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
return a if a > b else b
```
Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will *do the same thing* with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to *do something different* depending on the condition, then use a normal `if` **statement** instead.
---
Keep in mind that it's frowned upon by some Pythonistas for several reasons:
* The order of the arguments is different from those of the classic `condition ? a : b` ternary operator from many other languages (such as [C](https://en.wikipedia.org/wiki/C_%28programming_language%29), [C++](https://en.wikipedia.org/wiki/C%2B%2B), [Go](https://en.wikipedia.org/wiki/Go_%28programming_language%29), [Perl](https://en.wikipedia.org/wiki/Perl), [Ruby](https://en.wikipedia.org/wiki/Ruby_%28programming_language%29), [Java](https://en.wikipedia.org/wiki/Java_%28programming_language%29), [JavaScript](https://en.wikipedia.org/wiki/JavaScript), etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).
* Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
* Stylistic reasons. (Although the 'inline `if`' can be *really* useful, and make your script more concise, it really does complicate your code)
If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, `x = 4 if b > 8 else 9` is read aloud as `x will be 4 if b is greater than 8 otherwise 9`.
Official documentation:
* [Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions "Conditional expressions")
* [Is there an equivalent of C’s ”?:” ternary operator?](https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator "Is there an equivalent of C’s ”?:” ternary operator?") | You can index into a tuple:
```
(falseValue, trueValue)[test]
```
`test` needs to return *True* or *False*.
It might be safer to always implement it as:
```
(falseValue, trueValue)[test == True]
```
or you can use the built-in [`bool()`](https://docs.python.org/3.3/library/functions.html#bool "bool") to assure a [Boolean](https://en.wikipedia.org/wiki/Boolean_data_type "Boolean data type") value:
```
(falseValue, trueValue)[bool(<expression>)]
``` | Does Python have a ternary conditional operator? | [
"",
"python",
"operators",
"conditional-operator",
""
] |
I was looking a lot for method to get parent process in .NET, but found only P/Invoke way. | This code provides a nice interface for finding the Parent process object and takes into account the possibility of multiple processes with the same name:
Usage:
```
Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id);
```
Code:
```
public static class ProcessExtensions {
private static string FindIndexedProcessName(int pid) {
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;
for (var index = 0; index < processesByName.Length; index++) {
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int) processId.NextValue() == pid) {
return processIndexdName;
}
}
return processIndexdName;
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int) parentId.NextValue());
}
public static Process Parent(this Process process) {
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}
``` | Here is a solution. It uses p/invoke, but seems to work well, 32 or 64 cpu:
```
/// <summary>
/// A utility class to determine a process parent.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ParentProcessUtilities
{
// These members must match PROCESS_BASIC_INFORMATION
internal IntPtr Reserved1;
internal IntPtr PebBaseAddress;
internal IntPtr Reserved2_0;
internal IntPtr Reserved2_1;
internal IntPtr UniqueProcessId;
internal IntPtr InheritedFromUniqueProcessId;
[DllImport("ntdll.dll")]
private static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, ref ParentProcessUtilities processInformation, int processInformationLength, out int returnLength);
/// <summary>
/// Gets the parent process of the current process.
/// </summary>
/// <returns>An instance of the Process class.</returns>
public static Process GetParentProcess()
{
return GetParentProcess(Process.GetCurrentProcess().Handle);
}
/// <summary>
/// Gets the parent process of specified process.
/// </summary>
/// <param name="id">The process id.</param>
/// <returns>An instance of the Process class.</returns>
public static Process GetParentProcess(int id)
{
Process process = Process.GetProcessById(id);
return GetParentProcess(process.Handle);
}
/// <summary>
/// Gets the parent process of a specified process.
/// </summary>
/// <param name="handle">The process handle.</param>
/// <returns>An instance of the Process class.</returns>
public static Process GetParentProcess(IntPtr handle)
{
ParentProcessUtilities pbi = new ParentProcessUtilities();
int returnLength;
int status = NtQueryInformationProcess(handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
if (status != 0)
throw new Win32Exception(status);
try
{
return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
}
catch (ArgumentException)
{
// not found
return null;
}
}
}
``` | How to get parent process in .NET in managed way | [
"",
"c#",
"process",
"pinvoke",
"parent",
"managed",
""
] |
I'm trying to new up a LocalCommand instance which is a private class of System.Data.SqlClient.SqlCommandSet. I seem to be able to grab the type information just fine:
```
Assembly sysData = Assembly.Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
localCmdType = sysData.GetType("System.Data.SqlClient.SqlCommandSet+LocalCommand");
```
but Activator.CreateInstance throws an exception when I try to instantiate it:
```
object item = Activator.CreateInstance(localCmdType,
new object[] { commandText, parameters, num7, commandType });
```
System.MissingMethodException: Constructor on type 'System.Data.SqlClient.SqlCommandSet+LocalCommand' not found.
The constructor arguments match the signature I see in Reflector. Is new'ing up a private class with an internal ctor supported with a different CreateInstance overload or what? | My first thought would be to get the `ConstructorInfo` using `ConstructorInfo constructorInfo = Type.GetConstructor()`, and then `constructorInfo.Invoke()` that. I suspect that `Activator.CreateInstance` makes it hard to call constructors you wouldn't normally have access to, although I don't remember trying it myself. | I got it to work this way:
```
using System;
using System.Reflection;
class Test
{
public String X { get; set; }
Test(String x)
{
this.X = x;
}
}
class Program
{
static void Main()
{
Type type = typeof(Test);
ConstructorInfo c = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] { typeof(String) }, null);
Object o = c.Invoke(new Object[] { "foo" });
}
}
```
The trick was to go after the constructor specifically with `GetConstructor` rather then trying to find it in the results of `GetConstructors`. Go figure. | Activator.CreateInstance with private sealed class | [
"",
"c#",
"reflection",
"ado.net",
""
] |
What does it mean by POD type?cv-qualified? | Very Nice article on [POD](http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html) | POD, Plain Old Data, is any C++ type that has an equivalent in C.
cv-qualified type is a type that have been qualified either as a const or volatile.
```
// non cv_qualified
int one;
char *two;
// cv-qualified
const int three;
volatile char * four;
```
POD type's data members must be public and can be of any the primitive types: bool, numeric types, enumeration types, data-pointer types, pointer-to-function type, also arrays of any of the previous.
```
struct A //POD
{
int n;
double y;
};
struct B //non-POD
{
private:
int n;
double y;
};
``` | Terms new to beginners in c++? | [
"",
"c++",
""
] |
If you are doing something like the following:
```
var i = $('input[@name=some_field]');
if (i.val() != '' && !(i.val() >=1 && i.val() <= 36) || i.val() == 'OT')) {
i.focus();
}
```
is `i.val()` fast enough to use it multiple times or should you do:
```
var value = i.val();
```
first and then use value in the if statement, like:
```
var i = $('input[@name=some_field]');
var value = i.val();
if (value != '' && !(value >=1 && value <= 36) || value == 'OT')) {
i.focus();
}
```
...? | This isn't necessarily a jQuery question but it applies pretty well to most programming languages. And in fact, there's a lot more to this question than just performance issues.
One thing to keep in mind is that if you store the value, then there is no possibility that it will change during the execution of your subsequent code. Most of the time, this is what you expect and want. But it is also possible in some circumstances that the call to val() will return a different value, especially if you are looping and doing something that takes any significant time.
In your particular example, the chances of this occurring are pretty low because it's only a few calls and not in a looping construct. Given that there are only a few calls, performance likely won't be a major concern here. But the theory of the point remains - if you want to guarantee that the value doesn't change, put it in a variable. Since it also gives you the best of the performance considerations, I think this would be a best practice in most cases. | When called without any parameters, I don't believe val() would be significantly slower then just accessing the value property directly. Based on my reading of the jQuery source code, essentially all the val() method does is check whether the element is a select, and if not, simply returns the content of the value property (with \r characters removed). There's going to be some overhead from the function call, and a little overhead for the string replace, but nothing I've read indicates that the overhead would be significant.
If you're really concerned, try benchmarking the code in question over a large number of iterations. Otherwise, just pick which ever method looks cleanest to your eyes and go for it. | jQuery: is val() fast enough to use repeatedly or is it better to put the value in a variable | [
"",
"javascript",
"jquery",
""
] |
I looked in [Stevens](http://www.google.com/search?q=advanced+programming+in+the+unix+environment&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a), and in the [Posix Programmer's Guide](https://rads.stackoverflow.com/amzn/click/com/0937175730), and the best I can find is
> An array of strings called the *enviroment* is made available when the process begins.
> This array is pointed to by the external variable `environ`, which is defined as:
>
> `extern char **environ;`
It's that *environ* variable that has me hesitating. I want to say
-The calling process/shell has already allocated the block of null terminated strings
-the 'external' variable `environ` is used as the entry point by *getenv()*.
-*ipso facto* feel free to call *getenv()* within a static initializer.
But I can't find any guarantee that the 'static initialization' of *environ* precedes all the other static initialization code. Am I overthinking this?
# Update
On *my* platform (AMD Opteron, Redhat 4, GCC 3.2.3), setting **LD\_DEBUG** shows that *environ* gets set *before* my static initializers are called. This is a nice thing to know; thanks, @codelogic. But it is not necessarily the result I'd get on all platforms.
Also, while I agree intuitively with @ChrisW on the behavior of the C/C++ runtime library, this is just my intuition based on experience. So anyone who can pipe up with a quote from someplace authoritative guaranteeing that *environ* is there before static initializers are called, bonus points! | I think you can run your program with LD\_DEBUG set to see the exact order:
```
LD_DEBUG=all <myprogram>
```
**EDIT:**
If you look at the source code of the runtime linker (glibc 2.7), specifically in files:
* sysdeps/unix/sysv/linux/init-first.c
* sysdeps/i386/init-first.c
* csu/libc-start.c
* sysdeps/i386/elf/start.S
you will see that argc, argv and environ (alias for `__`environ) are set before any global constructors are called (the init functions). You can follow the execution starting right from \_start, the actual entry point (start.S). As you've quoted Stevens *"An array of strings called the enviroment is made available when the process begins"*, suggesting that environment assignment happens at the very beginning of the process initialization. This backed by the linker code, which does the same, should give you sufficient peace of mind :-)
**EDIT 2:** Also worth mentioning is that environ is set early enough that even the runtime linker can query it to determine whether or not to output verbosely (LD\_DEBUG). | Given that both the environment setup and the invoking of the static initializers are functions that the language run-time has to perform *before* main() is invoked, I am not sure you will find a guarantee here. That is, I am not aware of a specific requirement here that this *has* to work and that the order is guaranteed prior to main() in, say, the ANSI language and library specifications or anything....but I didn't check to make sure either.
At the same time, I am not aware of a specific requirement that restricts which run-time library functions can be called from a static initializer. And, more to the point, it would feel like a run-time bug (to me) if you couldn't access the environment from one.
On this basis, I vote that I would expect this to work, is a safe assumption, and current data points seem to support this line of reasoning. | Is it safe to use getenv() in static initializers, that is, before main()? | [
"",
"c++",
"c",
"unix",
"posix",
"environment",
""
] |
I would like to write an simple application able to retrieve some certain data from another process(application)'s allocated memory.
Say I already know a process' id and I would like to obtain a value in this process' memory always from a fixed offset (like 0x523F1C), is this doable in the user-mode, or it has to be in kernel-mode?
Any hints or info are highly appreciated.
My environment is Windows XP, and I am using Visual C++ and Qt for GUI.
Thanks in advance :)
EDIT:
(a) thanks guys. basically it's working (when setting a break point and hook over the value it's correct), but when doing a normal release build the value obtained is always the initialized :(
will have to work more to figure it out...
(b) Since the application I am trying to obtain value from isn't written by me, can I still do the interprocess communications / shared memory techniques?
EDIT 2:
thanks again for the quick response! :D | Use ReadProcessMemory - you'll need a handle with PROCESS\_VM\_READ access to the other process[1], but if you're an administrator (or possibly, if you have SE\_DEBUG privs) it should be straightforward.
```
BOOL WINAPI ReadProcessMemory(
__in HANDLE hProcess,
__in LPCVOID lpBaseAddress,
__out LPVOID lpBuffer,
__in SIZE_T nSize,
__out SIZE_T* lpNumberOfBytesRead
);
```
[1]
```
HANDLE hProc = OpenProcess(PROCESS_VM_READ, false, pid);
```
Edit: b) No, unless you use CreateRemoteThread - but you normally need to have shimmed your own DLL into the remote process before you can meaningfully create threads in that process. This is advanced, fun and dangerous :) | If you're doing interprocess communications / shared memory, I would suggest using [Boost::Interprocess](http://www.boost.org/doc/libs/1_35_0/doc/html/interprocess.html) instead as it will make life much easier. | Get the value from a fixed memory offset : Visual C++ Programming | [
"",
"c++",
"visual-c++",
""
] |
One thing that's always confused me is input escaping and whether or not you're protected from attacks like SQL injection.
Say I have a form which sends data using HTTP POST to a PHP file. I type the following in an input field and submit the form:
```
"Hello", said Jimmy O'Toole.
```
If you print/echo the input on the PHP page that receives this POST data, it comes out as:
```
\"Hello\", said Jimmy O\'Toole.
```
This is the point where it gets confusing. If I put this input string into (My)SQL and execute it, it'll go into the database fine (since quotes are escaped), but would that stop SQL injection?
If I take the input string and call something like [`mysqli real_escape_string`](http://www.php.net/mysqli_real_escape_string) on it, it comes out like this:
```
\\"Hello\\", said Jimmy O\\'Toole.
```
So when it goes into the database via (My)SQL, it ends up as:
```
\"Hello\", said Jimmy O\'Toole.
```
This obviously has too many slashes.
So if the input comes through HTTP POST as escaped, do you have to escape it again to make it safe for (My)SQL? Or am I just not seeing something obvious here?
Thanks in advance for any help. | Ah, the wonders of [magic quotes](http://php.net/magic_quotes). It is making those unnecessary escapes from your POST forms. You should disable (or neutralize) them, and many of your headaches go away.
Here's an exemplary article of the subject: <http://www.sitepoint.com/blogs/2005/03/02/magic-quotes-headaches/>
Recap: disable magic quotes, use `real_escape_string()`. | Instead of relying on escaping I would use parametrized SQL queries and let the mysql driver do whatever escaping it needs. | Understanding input escaping in PHP | [
"",
"php",
"mysql",
"escaping",
"sql-injection",
"magic-quotes",
""
] |
I have a small AJAX application, written in PHP that I did not secure from the start. I would like some recommendations on how to now secure the app, things to implement and check for. I have not found any exhaustive guides on google, and hope that some can be recommended.
It is a small application that connects to and displays records from a mysql database. It is not using any external libraries.
I am unsure about how to protect on passing in variables, such as:
```
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
```
Should I simply declare $cmd to something before check isset? | If you are talking about securing the app (as opposed to the server/ environment it is on - which I am not really qualified to address) then I would consider the following:
1. Ensure any user inputs are parsed/cleaned to ensure they can't do things such as [SQL injection attacks](http://www.unixwiz.net/techtips/sql-injection.html). This includes any ajax requests where the user input can be stored on the query string. **In fact anything passed into the app from the query string should be validated/cleaned in this manner**.
2. Do you use any passwords? If so use SSL to stop any packet sniffing. And [hash your passwords in your database with a salt](http://phpsec.org/articles/2005/password-hashing.html)
3. A quick Google dug up this which looks pretty good: <http://www.securityfocus.com/infocus/1706>
4. Some tips on securing user input <http://www.dagondesign.com/articles/writing-secure-php-scripts-part-1/> | The most important rule when handling user input is: *Validate input, escape output*. | Guide for securing an ajax php webapp | [
"",
"php",
"ajax",
"security",
""
] |
In C#, is there an inline shortcut to instantiate a List<T> with only one item?
I'm currently doing:
```
new List<string>( new string[] { "title" } ))
```
Having this code everywhere reduces readability. I've thought of using a utility method like this:
```
public static List<T> SingleItemList<T>( T value )
{
return (new List<T>( new T[] { value } ));
}
```
So I could do:
```
SingleItemList("title");
```
Is there a shorter / cleaner way? | Simply use this:
```
List<string> list = new List<string>() { "single value" };
```
You can even omit the () braces:
```
List<string> list = new List<string> { "single value" };
```
Update: of course this also works for more than one entry:
```
List<string> list = new List<string> { "value1", "value2", ... };
``` | ```
var list = new List<string>(1) { "hello" };
```
Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.
Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once. | Shortcut for creating single item list in C# | [
"",
"c#",
""
] |
I'm working on a macro system for Python ([as discussed here](https://stackoverflow.com/questions/454648/pythonic-macro-syntax)) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extended dynamically at runtime.
To do this, I'm considering using a sort of partial evaluation on the code at compile-time. If parsing fails for a given expression, due to a macro for its syntax not being available, the compiler halts evaluation of the function/block and generates the code it already has with a stub where the unknown expression is. When this stub is hit at runtime, the function is recompiled against the current macro set. If this compilation fails, a parse error would be thrown because execution can't continue. If the compilation succeeds, the new function replaces the old one and execution continues.
The biggest issue I see is that you can't find parse errors until the affected code is run. However, this wouldn't affect many cases, e.g. group operators like [], {}, (), and `` still need to be paired (requirement of my tokenizer/list parser), and top-level syntax like classes and functions wouldn't be affected since their "runtime" is really load time, where the syntax is evaluated and their objects are generated.
Aside from the implementation difficulty and the problem I described above, what problems are there with this idea? | Here are a few possible problems:
* You may find it difficult to provide the user with helpful error messages in case of a problem. This seems likely, as any compilation-time syntax error could be just a syntax extension.
* Performance hit.
I was trying to find some discussion of the pluses, minuses, and/or implementation of dynamic parsing in Perl 6, but I couldn't find anything appropriate. However, you may find this quote from Nicklaus Wirth (designer of Pascal and other languages) interesting:
> The phantasies of computer scientists
> in the 1960s knew no bounds. Spurned
> by the success of automatic syntax
> analysis and parser generation, some
> proposed the idea of the flexible, or
> at least extensible language. The
> notion was that a program would be
> preceded by syntactic rules which
> would then guide the general parser
> while parsing the subsequent program.
> A step further: The syntax rules would
> not only precede the program, but they
> could be interspersed anywhere
> throughout the text. For example, if
> someone wished to use a particularly
> fancy private form of for statement,
> he could do so elegantly, even
> specifying different variants for the
> same concept in different sections of
> the same program. The concept that
> languages serve to communicate between
> humans had been completely blended
> out, as apparently everyone could now
> define his own language on the fly.
> The high hopes, however, were soon
> damped by the difficulties encountered
> when trying to specify, what these
> private constructions should mean. As
> a consequence, the intreaguing idea of
> extensible languages faded away rather
> quickly.
*Edit*: Here's Perl 6's [Synopsis 6: Subroutines](http://svn.pugscode.org/pugs/docs/Perl6/Spec/S06-routines.pod), unfortunately in markup form because I couldn't find an updated, formatted version; search within for "macro". Unfortunately, it's not *too* interesting, but you may find some things relevant, like Perl 6's one-pass parsing rule, or its syntax for abstract syntax trees. The approach Perl 6 takes is that a macro is a function that executes immediately after its arguments are parsed and returns either an AST or a string; Perl 6 continues parsing as if the source actually contained the return value. There is mention of generation of error messages, but they make it seem like if macros return ASTs, you can do alright. | Here are some ideas from my master's thesis, which may or may not be helpful.
The thesis was about robust parsing of natural language.
The main idea: given a context-free grammar for a language, try to parse a given
text (or, in your case, a python program). If parsing failed, you will have a partially generated parse tree. Use the tree structure to suggest new grammar rules that will better cover the parsed text.
I could send you my thesis, but unless you read Hebrew this will probably not be useful.
In a nutshell:
I used a [bottom-up](http://en.wikipedia.org/wiki/Bottom-up_parser) [chart parser](http://en.wikipedia.org/wiki/Chart_parser). This type of parser generates edges for productions from the grammar. Each edge is marked with the part of the tree that was consumed. Each edge gets a score according to how close it was to full coverage, for example:
```
S -> NP . VP
```
Has a score of one half (We succeeded in covering the NP but not the VP).
The highest-scored edges suggest a new rule (such as X->NP).
In general, a chart parser is less efficient than a common LALR or LL parser (the types usually used for programming languages) - O(n^3) instead of O(n) complexity, but then again you are trying something more complicated than just parsing an existing language.
If you can do something with the idea, I can send you further details.
I believe looking at natural language parsers may give you some other ideas. | Partial evaluation for parsing | [
"",
"python",
"parsing",
"macros",
"language-design",
""
] |
When referencing class variables, why do people prepend it with `this`? I'm not talking about the case when `this` is used to disambiguate from method parameters, but rather when it seems unnecessary.
Example:
```
public class Person {
private String name;
public String toString() {
return this.name;
}
}
```
In `toString`, why not just reference `name` as `name`?
```
return name;
```
What does `this.name` buy?
[Here's](https://stackoverflow.com/questions/404278/java-calendar-time-minute-is-wrong) a stackoverflow question whose code has `this` pre-pending. | Same reason why some people like to prepend private data members with "m\_" or name interfaces "IFoo". They believe it increases readability and clarity. Whether or not you agree with conventions like these is a matter of taste. | 1. Defensive programming (in case someone editing the code later adds a parameter or local with a conflicting name
2. Make the code "self documenting," more obvious | In Java, why do people prepend fields with `this`? | [
"",
"java",
"coding-style",
""
] |
I'm working on a resource management class and want to have the user provide a functor to a "ReleaseResource" method as part of the resource manager's constructor. From there when a resource is requested that functor will be provided as the deleter for the shared\_ptr that I will be returning so that the appropriate method will be called when the resource is no longer used.
The problem I'm running into that this requires me to store the functor in my class, and I'm not entirely sure how to do that. Typically when using a functor you template the function like so:
```
template<class MyFunctor> MyMethod(MyFunctor f) {
f();
}
```
Which is great if you intend to use the functor in the scope of that function, but since the template goes out of scope with the function I'm not sure how you would specify a variable of the appropriate type to store the functor for later use.
Can anyone point me in the right direction here? | ```
template<class MyFunctor> MyMethod(MyFunctor f) {
boost::function<void()> g = f;
g();
}
```
The type you pass to [`boost::function`](http://www.boost.org/doc/libs/1_37_0/doc/html/function.html) is the function type. For example, `int(bool, char)` is the type of a function returning int and taking a bool and a char. That said, if you want to construct the shared\_ptr right away, you don't need to store the functor somewhere (`boost::function` requires the `new` operator for that, even though for very small functors, it will use special tricks to only use stack allocation (small buffer optimization)):
```
template<class MyFunctor> MyMethod(MyFunctor f) {
boost::shared_ptr<T> ptr(new T, f);
}
```
boost::function is part of [`tr1`](http://en.wikipedia.org/wiki/Technical_Report_1) and will be part of the next official C++ Standard. Example:
```
struct Manager {
template<typename Deleter>
Manager(Deleter d)
:deleter(d) {
}
boost::shared_ptr<Resource> allocate() {
...
return boost::shared_ptr<Resource>(resource, deleter);
}
private:
boost::function<void(Resource *)> deleter;
};
``` | There are two ways, both of which biol down to templating the class.
```
template <MyFunctor>
class MyClass
{
MyFunctor func;
public:
MyClass(MyFunctor f) :func(f)
{ }
MyMethod()
{
func();
}
}
```
This would require you to know the type of the functor. To avoid that, we can use a factory:
```
template<MyFunctor>
MyClass<MyFunctor> MakeFunctorClass(MyFunctor f)
{
return MyClass<MyFunctor>(f);
}
```
Alternately, since in all likelihood, most of the functor signature will be the same, with only a small part changing, we could use that:
```
template <MyType>
class MyClass
{
typedef std::binary_function<MyType, MyType, bool> MyFunctor;
MyFunctor func;
public:
MyMethod(MyFunctor f)
{
func = f;
func();
}
}
```
This makes usage a bit simpler:
```
bool AreEqual(int, int);
MyClass<int> myc;
myc.MyMethod(AreEqual);
```
at the expensive of a trickier definition (i.e., I don't guarantee that the binary\_function typedef I gave will work) | Retaining functors as variables | [
"",
"c++",
"functor",
""
] |
there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function.
```
>>> def gs(a,b):
... def ry():
... if a==b:
... return a
...
... ry()
...
... a += 1
... ry()
...
... b*=2
... ry()
...
>>> gs(1,2) # should return 2
>>> gs(1,1) # should return 1
>>> gs(5,3) # should return 6
>>> gs(2,3) # should return 3
```
so how do I get gs to return 'a' from within ry? I thought of using super but think that's only for classes.
Thanks
There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.
**edit**: I now think [decorators](http://muharem.wordpress.com/2006/10/19/python-decorator-mini-study-part-2-of-3/) might be the best solution. | This should allow you to keep checking the state and return from the outer function if a and b ever end up the same:
```
def gs(a,b):
class SameEvent(Exception):
pass
def ry():
if a==b:
raise SameEvent(a)
try:
# Do stuff here, and call ry whenever you want to return if they are the same.
ry()
# It will now return 3.
a = b = 3
ry()
except SameEvent as e:
return e.args[0]
``` | Do you mean?
```
def gs(a,b):
def ry():
if a==b:
return a
return ry()
``` | make a parent function return - super return? | [
"",
"python",
"class",
"function",
"return",
"parent",
""
] |
## Background:
I have an application written in native C++ which uses the wxWidgets toolkit's wxODBC database access library which is being [removed](http://wiki.wxwidgets.org/ODBC) from all future versions of wxWidgets . I need to replace this with another database access method that supports the assumptions and contraints outlined below. I don't require that the replacement use native DBMS APIs or ODBC under the hood, but it must meet the contraints outlined below.
## Assumptions/Constraints
*The library must:*
* Support Native (i.e. unmanaged) C++
* 32-bit Windows 2000/XP/2003
* Visual Studio 2005
* Microsoft SQL Server 2000 and 2005
* Oracle 9 and 10
* Run-time Performance greater than or equal to wxODBC
* Single programmer API supporting multiple DBMS (e.g. don't want to write different code for using different DBMS)
*Nice but Optional:*
* 64-bit Windows operating systems
* 32-bit and/or 64-bit Linux operating systems
* Microsoft SQL Server 2008
* Oracle 11
* MySQL
* Any additional DBMS
* Visual Studio 2008
* Open Source
* Runtime Performance near or equal to native DBMS API
## Question:
**What good libraries are available - either free, open source or pay - that support multiple DBMS from a single API including Oracle and Microsoft SQL Server and can be used from native C++?**
Please describe any past experiences you have had - good OR bad - with a given library and why you are making your recommendation for or against a given library, especially in regards to the assumptions and contraints above.
## See Also:
<https://stackoverflow.com/questions/74141/good-orm-for-c-solutions> | I use SQLAPI++. Well worth a look.
<http://www.sqlapi.com/> | A library is <http://otl.sourceforge.net/>
An employer of mine used it.
I can't tell you how its performance compares with wxODBC, but it might fit your requirements. | Database Access Libraries for C++ | [
"",
"c++",
"windows",
"database",
"linux",
"unmanaged",
""
] |
I know:
* Firebird: `FIRST` and `SKIP`;
* MySQL: `LIMIT`;
* SQL Server: `ROW_NUMBER()`;
Does someone knows a SQL ANSI way to perform result paging? | See **Limit—with offset** section on this page: [<http://troels.arvin.dk/db/rdbms/>](http://troels.arvin.dk/db/rdbms/)
BTW, Firebird also supports ROWS clause since version 2.0 | No official way, no.\*
Generally you'll want to have an abstracted-out function in your database access layer that will cope with it for you; give it a hint that you're on MySQL or PostgreSQL and it can add a 'LIMIT' clause to your query, or rownum over a subquery for Oracle and so on. If it doesn't know it can do any of those, fall back to fetching the lot and returning only a slice of the full list.
\*: eta: there is now, in ANSI SQL:2003. But it's not globally supported, it often performs badly, and it's a bit of a pain because you have to move/copy your ORDER into a new place in the statement, which makes it harder to wrap automatically:
```
SELECT * FROM (
SELECT thiscol, thatcol, ROW_NUMBER() OVER (ORDER BY mtime DESC, id) AS rownumber
)
WHERE rownumber BETWEEN 10 AND 20 -- care, 1-based index
ORDER BY rownumber;
```
There is also the "FETCH FIRST n ROWS ONLY" suffix in SQL:2008 (and DB2, where it originated). But like the TOP prefix in SQL Server, and the similar syntax in Informix, you can't specify a start point, so you still have to fetch and throw away some rows. | There are a method to paging using ANSI SQL only? | [
"",
"sql",
"ansi-sql",
""
] |
This is a generalization of the "string contains substring" problem to (more) arbitrary types.
Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:
Example usage (Sequence in Sequence):
```
>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
```
So far, I just rely on brute force and it seems slow, ugly, and clumsy. | I second the Knuth-Morris-Pratt algorithm. By the way, your problem (and the KMP solution) is exactly recipe 5.13 in [Python Cookbook](https://rads.stackoverflow.com/amzn/click/com/0596007973) 2nd edition. You can find the related code at <http://code.activestate.com/recipes/117214/>
It finds *all* the correct subsequences in a given sequence, and should be used as an iterator:
```
>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s
3
>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s
(nothing)
``` | Here's a brute-force approach `O(n*m)` (similar to [@mcella's answer](https://stackoverflow.com/questions/425604/best-way-to-determine-if-a-sequence-is-in-another-sequence-in-python#425764)). It might be faster than the Knuth-Morris-Pratt algorithm implementation in pure Python `O(n+m)` (see [@Gregg Lind answer](https://stackoverflow.com/questions/425604/best-way-to-determine-if-a-sequence-is-in-another-sequence-in-python#425838)) for *small* input sequences.
```
#!/usr/bin/env python
def index(subseq, seq):
"""Return an index of `subseq`uence in the `seq`uence.
Or `-1` if `subseq` is not a subsequence of the `seq`.
The time complexity of the algorithm is O(n*m), where
n, m = len(seq), len(subseq)
>>> index([1,2], range(5))
1
>>> index(range(1, 6), range(5))
-1
>>> index(range(5), range(5))
0
>>> index([1,2], [0, 1, 0, 1, 2])
3
"""
i, n, m = -1, len(seq), len(subseq)
try:
while True:
i = seq.index(subseq[0], i + 1, n - m + 1)
if subseq == seq[i:i + m]:
return i
except ValueError:
return -1
if __name__ == '__main__':
import doctest; doctest.testmod()
```
I wonder how large is the *small* in this case? | Best way to determine if a sequence is in another sequence? | [
"",
"python",
"algorithm",
"sequence",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.