Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
struct TimerEvent
{
event Event;
timeval TimeOut;
static void HandleTimer(int Fd, short Event, void *Arg);
};
```
HandleTimer needs to be static since I'm passing it to C library (libevent).
I want to inherit from this class. How can this be done?
Thanks. | You can easily inherit from that class:
```
class Derived: public TimerEvent {
...
};
```
However, you can't override HandleTimer in your subclass and expect this to work:
```
TimerEvent *e = new Derived();
e->HandleTimer();
```
This is because static methods don't have an entry in the vtable, and can't thus be virtual. You can however use the "void\* Arg" to pass a pointer to your instance... something like:
```
struct TimerEvent {
virtual void handle(int fd, short event) = 0;
static void HandleTimer(int fd, short event, void *arg) {
((TimerEvent *) arg)->handle(fd, event);
}
};
class Derived: public TimerEvent {
virtual void handle(int fd, short event) {
// whatever
}
};
```
This way, HandleTimer can still be used from C functions, just make sure to always pass the "real" object as the "void\* Arg". | To some extent the traits pattern lets you inherit and redefine static methods.
First start with a base class:
```
struct base {
static void talk() { std::cout << "hello" << std::endl; }
static void shout() { std::cout << "HELLO !!" << std::endl; }
};
```
Then derive it and redefine some methods:
```
struct derived: public base {
static void talk() { std::cout << "goodbye" << std::endl; }
};
```
And now call the methods via a traits class:
```
template < class T >
struct talker_traits {
static void talk() { T::talk(); }
static void shout() { T::shout(); }
};
talker_traits<base>::talk() // prints "hello"
talker_traits<base>::shout() // prints "HELLO !!"
talker_traits<derived>::talk() // prints "goodbye"
talker_traits<derived>::shout() // prints "HELLO !!"
```
[ideone demo](http://ideone.com/hnGGmf)
The traits class lets you reuse the static method `base::shout` while "overriding" `base::talk` with `derived::talk`. Still, there are several difference with actual inheritance:
* The function to call is resolved at compile time
* The child method needs not have the same signature as the parent one
It works with static fields and typedefs too, the best example is [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits). | How can Derived class inherit a static function from Base class? | [
"",
"c++",
"inheritance",
"static",
""
] |
I use huge data files, sometimes I only need to know the number of lines in these files, usually I open them up and read them line by line until I reach the end of the file
I was wondering if there is a smarter way to do that | This is the fastest version I have found so far, about 6 times faster than readLines. On a 150MB log file this takes 0.35 seconds, versus 2.40 seconds when using readLines(). Just for fun, linux' wc -l command takes 0.15 seconds.
```
public static int countLinesOld(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
```
EDIT, 9 1/2 years later: I have practically no java experience, but anyways I have tried to benchmark this code against the `LineNumberReader` solution below since it bothered me that nobody did it. It seems that especially for large files my solution is faster. Although it seems to take a few runs until the optimizer does a decent job. I've played a bit with the code, and have produced a new version that is consistently fastest:
```
public static int countLinesNew(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int readChars = is.read(c);
if (readChars == -1) {
// bail out if nothing to read
return 0;
}
// make it easy for the optimizer to tune this loop
int count = 0;
while (readChars == 1024) {
for (int i=0; i<1024;) {
if (c[i++] == '\n') {
++count;
}
}
readChars = is.read(c);
}
// count remaining characters
while (readChars != -1) {
for (int i=0; i<readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
readChars = is.read(c);
}
return count == 0 ? 1 : count;
} finally {
is.close();
}
}
```
Benchmark resuls for a 1.3GB text file, y axis in seconds. I've performed 100 runs with the same file, and measured each run with `System.nanoTime()`. You can see that `countLinesOld` has a few outliers, and `countLinesNew` has none and while it's only a bit faster, the difference is statistically significant. `LineNumberReader` is clearly slower.
[](https://i.stack.imgur.com/fjQQB.png) | I have implemented another solution to the problem, I found it more efficient in counting rows:
```
try
(
FileReader input = new FileReader("input.txt");
LineNumberReader count = new LineNumberReader(input);
)
{
while (count.skip(Long.MAX_VALUE) > 0)
{
// Loop just in case the file is > Long.MAX_VALUE or skip() decides to not read the entire file
}
result = count.getLineNumber() + 1; // +1 because line index starts at 0
}
``` | Number of lines in a file in Java | [
"",
"java",
"large-files",
"line-numbers",
""
] |
Given an hypothetical utility class that is used only in program setup:
```
class MyUtils {
private static MyObject myObject = new MyObject();
/*package*/static boolean doStuff(Params... params) {
// do stuff with myObject and params...
}
}
```
will myObject be garbage collected when it is no longer being used, or will it stick around for the life of the program? | Static variables cannot be elected for garbage collection while the class is loaded. They can be collected when the respective class loader (that was responsible for loading this class) is itself collected for garbage.
Check out the [JLS Section 12.7 Unloading of Classes and Interfaces](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.7)
> A class or interface may be unloaded
> if and only if its defining class
> loader may be reclaimed by the garbage
> collector [...] Classes and interfaces
> loaded by the bootstrap loader may not
> be unloaded. | Static variables are referenced by Class objects which are referenced by ClassLoaders -so unless either the ClassLoader drops the Class somehow (if that's even possible) or the ClassLoader itself becomes eligible for collection (more likely - think of unloading webapps) the static variables (or rather, the objects they reference) won't be collected. | Are static fields open for garbage collection? | [
"",
"java",
"static",
"garbage-collection",
"static-members",
""
] |
Is there any way to get the source line number in Javascript, like `__LINE__` for C or PHP? | There is a way, although more expensive: throw an exception, catch it immediately, and dig out the first entry from its stack trace. See example [here](http://eriwen.com/javascript/js-stack-trace/) on how to parse the trace. The same trick can also be used in plain Java (if the code is compiled with debugging information turned on).
**Edit**: Apparently not all browsers support this. The good news is (thanks for the comment, Christoph!) that some browsers export source file name and line number [directly through the `fileName` and `lineNumber` properties of the error object](http://books.google.hu/books?id=8oxJo5NITJUC&pg=PA204&lpg=PA204&dq=javascript+lineNumber+property&source=bl&ots=qkNTkbNKZR&sig=0Rs0BRj8wj-yTvdLUE9UJybd4TA&hl=en&sa=X&oi=book_result&resnum=1&ct=result). | The short answer is **no**.
The long answer is that depending on your browser you might be able to throw & catch an exception and pull out a stack trace.
I suspect you're using this for debugging (I hope so, anyway!) so your best bet would be to use [**Firebug**](http://getfirebug.com/). This will give you a [`console`](http://getfirebug.com/console.html) object; you can call `console.trace()` at any point to see what your programme is doing without breaking execution. | __LINE__ equivalent in Javascript | [
"",
"javascript",
""
] |
How can I create a product key for my C# Application?
I need to create a product (or license) key that I update annually. Additionally I need to create one for trial versions.
> Related:
>
> * [How do I best obfuscate my C# product license verification code?](https://stackoverflow.com/questions/501988)
> * [How do you protect your software from illegal distribution?](https://stackoverflow.com/questions/109997) | You can do something like create a record which contains the data you want to authenticate to the application. This could include anything you want - e.g. program features to enable, expiry date, name of the user (if you want to bind it to a user). Then encrypt that using some crypto algorithm with a fixed key or hash it. Then you just verify it within your program. One way to distribute the license file (on windows) is to provide it as a file which updates the registry (saves the user having to type it).
Beware of false sense of security though - sooner or later someone will simply patch your program to skip that check, and distribute the patched version. Or, they will work out a key that passes all checks and distribute that, or backdate the clock, etc. It doesn't matter how convoluted you make your scheme, anything you do for this will ultimately be security through obscurity and they will always be able to this. Even if they can't someone will, and will distribute the hacked version. Same applies even if you supply a dongle - if someone wants to, they can patch out the check for that too. Digitally signing your code won't help, they can remove that signature, or resign it.
You can complicate matters a bit by using techniques to prevent the program running in a debugger etc, but even this is not bullet proof. So you should just make it difficult enough that an honest user will not forget to pay. Also be very careful that your scheme does not become obtrusive to paying users - it's better to have some ripped off copies than for your paying customers not to be able to use what they have paid for.
Another option is to have an online check - just provide the user with a unique ID, and check online as to what capabilities that ID should have, and cache it for some period. All the same caveats apply though - people can get round anything like this.
Consider also the support costs of having to deal with users who have forgotten their key, etc.
*edit: I just want to add, don't invest too much time in this or think that somehow your convoluted scheme will be different and uncrackable. It won't, and cannot be as long as people control the hardware and OS your program runs on. Developers have been trying to come up with ever more complex schemes for this, thinking that if they develop their own system for it then it will be known only to them and therefore 'more secure'. But it really is the programming equivalent of trying to build a perpetual motion machine. :-)* | Who do you trust?
I've always considered this area too critical to trust a third party to manage the runtime security of your application. Once that component is cracked for one application, it's cracked for all applications. It happened to [Discreet](https://en.wikipedia.org/wiki/Autodesk_Media_and_Entertainment) in five minutes once they went with a third-party license solution for [3ds Max](https://en.wikipedia.org/wiki/Autodesk_3ds_Max) years ago... Good times!
Seriously, consider rolling your own for having complete control over your algorithm. If you do, consider using components in your key along the lines of:
* License Name - the name of client (if any) you're licensing. Useful for managing company deployments - make them feel special to have a "personalised" name in the license information you supply them.
* Date of license expiry
* Number of users to run under the same license. This assumes you have a way of tracking running instances across a site, in a server-ish way
* Feature codes - to let you use the same licensing system across multiple features, and across multiple products. Of course if it's cracked for one product it's cracked for all.
Then checksum the hell out of them and add whatever (reversable) encryption you want to it to make it harder to crack.
To make a trial license key, simply have set values for the above values that translate as "trial mode".
And since this is now probably the most important code in your application/company, on top of/instead of obfuscation consider putting the decrypt routines in a native DLL file and simply [P/Invoke](http://en.wikipedia.org/wiki/Platform_Invocation_Services) to it.
Several companies I've worked for have adopted generalised approaches for this with great success. Or maybe the products weren't worth cracking ;) | How can I create a product key for my C# application? | [
"",
"c#",
".net",
"license-key",
""
] |
I want to give a minimal js code to random websites so that they can add a widget.
The code needs to run after the main page loads and include a parameter with the domain name. ( I don't want to hardcode it)
One option is to add this code just before the `</body>` (so It will run after the page loads):
```
<script type="text/javascript" id="widget_script">
document.getElementById('widget_script').src=location.protocol.toLowerCase()+"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
</script>
```
This works in IE but not in Firefox. I see with Firebug that the src property is created correctly but the script from my site is not loaded.
My question is : what is the best way to do that ? (preferably by putting minimal lines on the header part.)
To further clarify the question: If I put a script on the header part, how do I make it run after it is loaded and the main page is loaded? If I use onload event in my script I may miss it because it may load after the onload event was fired. | You probably want to be implementing the **non-blocking script technique**. Essentially instead of modifying the src of a script, you're going to create and append a whole new script element.
Good write up [here](http://www.artzstudio.com/2008/07/beating-blocking-javascript-asynchronous-js/) and there are standard ways to do this in YUI and jQuery. It's quite straightforward with only one gotcha which is well understood (and documented at that link).
Oh and this:
> One option is to add this code just
> before the `</body>` (so It will run
> after the page loads):
...is not technically true: you're just making your script the last thing in the loading order. | You can try to statically include the script with document.write (is an older technique and not recommended to use as it can cause problems with more modern libraries):
```
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
document.write('<script src="', url, '" type="text/javascript"><\/script>');
```
Or with dynamically created DOM element:
```
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
```
Later edit:
To ensure the script is run after onload this can be used:
```
var oldWindowOnload = window.onload;
window.onload = function() {
oldWindowOnload();
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
}
```
I do not believe it can be shorter than this, apart from shorter variable names :) | How do I add an external js file with a parameter | [
"",
"javascript",
"load",
""
] |
It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).
Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)? | The biggest differences are that Python is duck typed, meaning that you won't need to plan out class hierarchies in as much detail as in Java, and has first class functions. The strategy pattern, for example, becomes much simpler and more obvious when you can just pass a function in, rather than having to make interfaces, etc. just to simulate higher order functions. More generally, Python has syntactic sugar for a lot of common design patterns, such as the iterator and the aforementioned strategy. It might be useful to understand these patterns (I've read Head First and found it pretty useful), but think about Pythonic ways to implement them rather than just doing things the same way you would in Java. | Python has it's own design idioms. Some of the standard patterns apply, others don't. Something like strategy or factories have in-language support that make them transparent.
For instance, with first-class types anything can be a factory. There's no need for a factory type, you can use the class directly to construct any object you want.
Basically, Python has its own design idioms that are somewhat different largely because it's so dynamic and has incredible introspection capabilities.
Example:
```
x = list
my_list = x(range(0,5)) #creates a new list by invoking list's constructor
```
By assigning the class-type to a callable object you can essentially remove any 'factory' types in your code. You are only left with callables that produce objects that should conform to some given conventions.
Furthermore, there are design patterns in Python that just can't be represented in other statically-typed languages efficiently. Metaclasses and function decorators are good examples of this. | Do OO design principles apply to Python? | [
"",
"python",
"oop",
""
] |
I am extreamly interested in math and programming and planning to start **symbolic math** project **from scratch**.
1. Is this good project idea?
2. Where to start?
3. How should one approach this
project?
4. Any good resources?
Thanks in advance. | 1. It's a good project to practice programming skills. But if you want to create a real library that other people will want to use this is a project you do not want to start allone and from scratch ...
2. *Where to start:* Have a look at the solutions that are already out there and think about what it is that you want to do different. How will your project differ from others?
3. Resource: [SymPy is a Python library for symbolic mathematics](http://code.google.com/p/sympy) | 1.Is this good project idea?
Yes; I would expect it to provide an endless source of interesting work which will, quite quickly, test and extend your programming powers.
2.Where to start?
I second the other suggestions that you should look at existing work. SAGE is very impressive and if you had asked for my advice I would suggest that you firstly write a basic system for doing arithmetic with numbers and symbols; then have a look at SAGE and write a module to extend the system, in other words become a contributor to something larger rather than trying to do it all on your own. Look also at Mathematica and Maple, Macsyma and Axiom. The latter 2 are free (I think) but they are all well documented on-line and a great source of ideas and challenges.
3.How should one approach this project?
As one would approach eating an elephant. One bite at a time. More seriously, I think there are some core issues, such as representation of expressions, and some basic functionality (arithmetic on polynomials) which you could cut your teeth on.
4.Any good resources?
Lots and lots. google for 'computer algebra', 'term rewriting'. Have a look at what's available on Amazon. And, if you have access, check out the ACM digital library
Good luck. | Symbolic Mathematics Python? | [
"",
"python",
"algorithm",
"math",
"symbolic-math",
""
] |
Is it possible to download a file from a website in Windows Application form and put it into a certain directory? | With the [WebClient class](http://msdn.microsoft.com/en-us/library/ez801hhe.aspx):
```
using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");
``` | Use [`WebClient.DownloadFile`](http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfile.aspx):
```
using (WebClient client = new WebClient())
{
client.DownloadFile("http://csharpindepth.com/Reviews.aspx",
@"c:\Users\Jon\Test\foo.txt");
}
``` | How to download a file from a website in C# | [
"",
"c#",
"download",
"windows",
""
] |
Does the `std::stack` in the C++ STL expose any iterators of the underlying container or should I use that container directly? | Stack does not have iterators, by definition of stack. If you need stack with iterators, you'll need to implement it yourself on top of other container (std::list, std::vector, etc).
[Stack doc is here](http://en.cppreference.com/w/cpp/container/stack).
P.S. According to a comment i got from Iraimbilanja, std::stack by default uses std::deque for implementation. | If you need a stack with iterators, you have two choices:
* `std::vector` using `push_back()`, `pop_back()`.
* `std::deque` with either `push_back()`/`pop_back()` or `push_front()`/`pop_front()`. | Does std::stack expose iterators? | [
"",
"c++",
"stl",
"stack",
""
] |
I've got some Java code which builds a data structure (approx 500 small interlinked objects) from data in some files and I'd really like to visualise the resulting structure. I hope that seeing it will allow me to optimise, not the code, but the data itself.
I'm wondering if there is a debugger that will do this or perhaps a way I can dump the data and have a tool build me a pretty graph of the data structure.
I hope that makes sense. | I've solved this before by dumping all my objects to Dot format, for [GraphViz](http://www.graphviz.org/), and then used GraphViz to visualize the data, but not in real time. I had a command that would start a dump visitor that would walk the structure. Anyways it was about a second to dump and a few more to balance the graph when working with about 3000 nodes. | In C++, the tool I've used for doing something similar is the GNU Data Display Debugger [DDD](http://www.gnu.org/software/ddd/). According to the manual, you can use JDB as the debugging backend. I've never tried it, but it might be worth a shot -- I had great success using DDD to create graphs of the complex data structures. | Debugging Datastructures Visually | [
"",
"java",
"data-structures",
"visualization",
""
] |
I have a database table with a list of products (clothing). The products belong to categories and are from different stores.
Sample categories: tops, bottoms, shoes
Sample stores: gap.com, macys.com, target.com
My customers can request to filter products in the following ways:
* all products (no filter)
* by category
* by store
* by category and store
Right now I have ONE method in my "Products" class that returns the products depending on the type of filter requested by the user. I use a FilterBy enum to determine which products need to be returned.
For example, if the user wants to view all products in the "tops" category I call this function:
```
Products.GetProducts(FilterBy.Category, "tops", "");
```
I have the last parameter empty because it's the string that contains the "store" to filter by but in this case there is no store. However, if the user wants to filter by category AND store I'd call the method this way:
```
Product.GetProducts(FilterBy.CategoryAndStore, "tops", "macys.com");
```
My question is, what's a better way to do this? I just learned about the strategy design pattern. Could I use that to do this in a better (easier to extend and easier to maintain) way?
The reason I'm asking this question is because I figure this must be a pretty common problem that people are repeatedly solving (filtering products in various ways) | According to Eric Evan's "Domain Drive Design" you need the specification pattern. Something like this
```
public interface ISpecification<T>
{
bool Matches(T instance);
string GetSql();
}
public class ProductCategoryNameSpecification : ISpecification<Product>
{
readonly string CategoryName;
public ProductCategoryNameSpecification(string categoryName)
{
CategoryName = categoryName;
}
public bool Matches(Product instance)
{
return instance.Category.Name == CategoryName;
}
public string GetSql()
{
return "CategoryName like '" + { escaped CategoryName } + "'";
}
}
```
Your repository can now be called with specifications
```
var specifications = new List<ISpecification<Product>>();
specifications.Add(
new ProductCategoryNameSpecification("Tops"));
specifications.Add(
new ProductColorSpecification("Blue"));
var products = ProductRepository.GetBySpecifications(specifications);
```
You could also create a generic CompositeSpecification class which would contain sub specifications and an indicator as to which logical operator to apply to them AND/OR
I'd be more inclined to combine LINQ expressions though.
**Update - Example of LINQ at runtime**
```
var product = Expression.Parameter(typeof(Product), "product");
var categoryNameExpression = Expression.Equal(
Expression.Property(product, "CategoryName"),
Expression.Constant("Tops"));
```
You can add an "and" like so
```
var colorExpression = Expression.Equal(
Expression.Property(product, "Color"),
Expression.Constant("Red"));
var andExpression = Expression.And(categoryNameExpression, colorExpression);
```
Finally you can convert this expression into a predicate and then execute it...
```
var predicate =
(Func<Product, bool>)Expression.Lambda(andExpression, product).Compile();
var query = Enumerable.Where(YourDataContext.Products, predicate);
foreach(Product currentProduct in query)
meh(currentProduct);
```
Probably wont compile because I have typed it directly into the browser, but I believe it is generally correct.
**Another update** :-)
```
List<Product> products = new List<Product>();
products.Add(new Product { CategoryName = "Tops", Color = "Red" });
products.Add(new Product { CategoryName = "Tops", Color = "Gree" });
products.Add(new Product { CategoryName = "Trousers", Color = "Red" });
var query = (IEnumerable<Product>)products;
query = query.Where(p => p.CategoryName == "Tops");
query = query.Where(p => p.Color == "Red");
foreach (Product p in query)
Console.WriteLine(p.CategoryName + " / " + p.Color);
Console.ReadLine();
```
In this case you would be evaluating in memory because the source is a List, but if your source was a data context that supported Linq2SQL for example I **think** this would evaluate using SQL.
You could still use the Specification pattern in order to make your concepts explicit.
```
public class Specification<T>
{
IEnumerable<T> AppendToQuery(IEnumerable<T> query);
}
```
The main difference between the two approaches is that the latter builds a known query based on explicit properties, whereas the first one could be used to build a query of any structure (such as building a query entirely from XML for example.)
This should be enough to get you started :-) | The strategy pattern doesn't necessarily knit well with the common interface-based repository approach. Personally, I'd probably go one of two ways here:
* One search method that supports combinations of options:
`IList<Product> GetProducts(string category, string store, ...);`
(then selectively apply the **combinations** of filters (i.e. `null` means "any") - either when building a command, or pass down to a SPROC that does something similar.
* With LINQ, maybe a predicate expression?
`IList<Product> GetProducts(Expression<Func<Product,bool>> predicate);`
Of course, with LINQ you could also use composition by the caller, but that is harder to write a closed / fully-tested repository for:
```
`IQueryable<Product> Products {get;}`
```
(and have the caller use .Where(x=>x.Category == "foo")) - I'm not so sure about this last one long-term... | which design pattern to use for filtering query? c# | [
"",
"c#",
"asp.net",
"design-patterns",
""
] |
This is a (hopefully) really simple question - I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment.
So this code:
```
std::SomeSTLContainer::const_iterator it = container.begin();
std::SomeSTLContainer::const_iterator itEnd = container.end();
```
would be 'slower' or less efficient than:
```
std::SomeSTLContainer::const_iterator it ( container.begin() );
std::SomeSTLContainer::const_iterator itEnd ( container.end() );
```
I understand the reason for this - the first example causes default construction and initialisation then subsequent assignment rather than specific construction and direct assignment in the second example. However, on modern processors / compilers, does it really make a difference? | > I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment.
This is simply wrong.
> I understand the reason for this - the first example causes default construction and initialisation then subsequent assignment rather than specific construction and direct assignment in the second example. However, on modern processors / compilers, does it really make a difference?
No, it doesn't make a difference. The C++ standard explicitly allows the assignment in that case to be omitted so that the same code will be produced. In practice, *all* modern C++ compilers do this.
Additionally, Charles is right: this would never call the assignment operator but rather the copy constructor. But as I've said, even this doesn't happen. | Your reasoning is not quite correct. Using an '=' in the definition does not cause default construction and assignment. In the 'worst' case, it uses the copy constructor from a temporary generated from the right hand side of the '='.
If the type of the right hand side is (const/volatile aside) of the same type or a derived type of the object being initialized then the two forms of construction are equivalent. | Optimising Iterator Definitions | [
"",
"c++",
"optimization",
"stl",
"iterator",
""
] |
i know there is a variable, function, or stored procedure that you can use to find the path that SQL Server is installed to:
e.g.:
```
c:\Program Files\Microsoft SQL Server\MSSQL.7\MSSQL
```
or
```
m:\CustomInstance\MSSQL
```
---
In reality, i'm hoping to SELECT for the default backup path. But since i doubt that exists, i'll just tack \BACKUP onto the install path and call it close enough.
---
## Update One
```
select filename from sysaltfiles
where name = db_name()
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'sysaltfiles'.
```
---
```
select filename from master.dbo.sysaltfiles
where name = db_name()
filename
----------------
(0 row(s) affected)
``` | ## How to select the installation path
**Note**: ***xp\_instance\_regread*** doesn't read the registry key you specify, but instead converts that key path into the appropriate path for the specific SQL Server instance you're running on. In other words: **xp\_regread** fails where **xp\_instance\_regread** succeeds.
## SQL Server Installation Directory
```
declare @rc int, @dir nvarchar(4000)
exec @rc = master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\Setup',
N'SQLPath',
@dir output, 'no_output'
select @dir AS InstallationDirectory
```
## SQL Server Backup Directory
```
declare @rc int, @dir nvarchar(4000)
exec @rc = master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'BackupDirectory',
@dir output, 'no_output'
select @dir AS BackupDirectory
```
[SQL Server 2000 Location Functions](http://www.sqldev.net/misc/SQLLocationFunctions.htm) | Execute the following to inspect the registry in order to find the appropriate key.
```
Declare @Path as varchar(100);
Set @Path = NULL
Exec master..xp_regread 'HKEY_LOCAL_MACHINE', 'SOFTWARE\Microsoft\Microsoft SQL Server\70\Tools\ClientSetup', 'SQLPath', @Path OUTPUT
Select @Path as [Sql Server 7.0 path]
Set @Path = NULL
Exec master..xp_regread 'HKEY_LOCAL_MACHINE', 'SOFTWARE\Microsoft\Microsoft SQL Server\80\Tools\ClientSetup', 'SQLPath', @Path OUTPUT
Select @Path as [Sql Server 2000 path]
Set @Path = NULL
Exec master..xp_regread 'HKEY_LOCAL_MACHINE', 'SOFTWARE\Microsoft\Microsoft SQL Server\90\Tools\ClientSetup', 'SQLPath', @Path OUTPUT
Select @Path as [Sql Server 2005 path]
Set @Path = NULL
Exec master..xp_regread 'HKEY_LOCAL_MACHINE', 'SOFTWARE\Microsoft\Microsoft SQL Server\100\Tools\ClientSetup', 'SQLPath', @Path OUTPUT
Select @Path as [Sql Server KATMAI path]
``` | SQL Server: How to SELECT the installation path? | [
"",
"sql",
"sql-server",
""
] |
I have the attached trigger that runs if the `tbl_repair_visit.TENANTSATISFACTION = 'Poor'` on an update.
The issue i have if we change the engineers name the Engineer column gets updated and the trigger runs again if `TENANTSATISFACTION = 'Poor'`
How can i set this up to only run if the `TENANTSATISFACTION = 'Poor'` column is updated and ignor updates on all other columns
```
ALTER TRIGGER [dbo].[tr_CustomerSatisfactionAlertRepair]
ON [dbo].[tbl_repair_visit]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT alertmessagedata (TypeID, Contract, Address, ORDERID,
ENGINEERS, Sent, DateAdded)
SELECT '5', tbl_property.contract, tbl_property.fulladdress,
tbl_repair_visit.orderid, tbl_repair_visit.engineer,
0, GETDATE()
FROM TBL_REPAIR_VISIT
INNER JOIN
INSERTED X ON TBL_REPAIR_VISIT.VISITID = X.VISITID
INNER JOIN
TBL_PROPERTY ON TBL_REPAIR_VISIT.PROPREF = TBL_PROPERTY.PROPREF
WHERE tbl_repair_visit.TENANTSATISFACTION = 'Poor'
END
``` | In the update trigger, you can check if a column is being updated:
IF UPDATE(TENANTSATISFACTION)
BEGIN
....
END | I don't think you can specify that. The triggers UPDATE, DELETE and INSERT are fired whenever an UPDATE, DELETE or INSERT (respectably) is performed on the table.
You can do as Mike K. suggested and check if the column that interests you changed or not. | SQL Trigger | [
"",
"sql",
"triggers",
""
] |
I'm trying to capture key presses so that when a given combination is pressed I trigger an event.
I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from [here](http://www.daniweb.com/forums/thread112975.html). However, when I run this from a terminal and hit some keys, after the "Press a key..." statement nothing happens.
Am I being stupid? Can anyone explain why nothing happens, or suggest a better way of achieving this on Linux (any language considered!)?
```
import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()
``` | Well, turns out there is a much simpler answer when using GNOME which doesn't involve any programming at all...
<http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php>
[Archived on Wayback](https://web.archive.org/web/20070802112319/http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php)
Just create the script/executable to be triggered by the key combination and point the 'keybinding\_commands' entry you create in gconf-editor at it.
Why didn't I think of that earlier? | Tk does not seem to get it if you do not display the window. Try:
```
import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
# root.withdraw()
root.mainloop()
```
works for me... | Detect key press combination in Linux with Python? | [
"",
"python",
"linux",
"keylogger",
""
] |
I am trying to find an optimal solution for the following problem: there is a need to design a database (postgres-based), the system of triggers and counters in it, which will form a system of efficiently querying, updating and storing information on 'how much unread comments exist in each article (or blog entry, or smth. similar), that is displayed on the page'.
Every solution that comes to the head, has some serious disadvantages, either in querying, or the storing, or the updating part. I.e. it needs too much storage, or too much updates, or too costy queries.
What about your expirience? Maybe there is an already formed nice solution for this kind of problems? | I would keep the schema as simple as possible, so querying will be as simple as possible. This usually also has the lowest storage requirements. Of course, set indices to support this query.
Next step: measure the performance! "To measure is to know." What is the response time? What is the load on the server? As long as the performance is acceptable, keep the schema and query simple. Do not sacrifice maintainability if it is not absolutely necessary: your successors will thank you for it later.
If performance really is a problem, look at the caching functionality of the framework you are using for your application. NOT performing a query is always faster than performing an optimized one. | If you really don't succeed within your resource envelope, maybe you have to tweak the user experience. Perhaps storing the date of last access to a thread is enough. | Implementing an efficient system of "unread comments" counters | [
"",
"sql",
"database",
"database-design",
"database-schema",
""
] |
Whenever I create a new Java file in Eclipse and check off the option to add `public static void main(String args[])`, this code is generated:
```
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
```
How do i:
* Remove the `@param args` comment
* Change the indentation so each { is on a line of its own
* Remove the TODO auto generated comment | The indention is a formatting issue while the comments is a template issue.
The templates are in **Window -> Preferences -> Java -> Code Style -> Code Templates**. Browse all of them and look for the things you would like to change.
The Formatter is a little bit more complicated. You find it under **Window -> Preferences -> Java -> Code Style -> Formatter**. There are tons of options there but I'll just answer your question.
* Templates -> Comments -> Methods -> Edit and delete everything
* Formatter -> Edit -> Braces Tab -> Change which situations you want
* Templates -> Code -> Method Body -> Edit and delete everything | 1. In Eclipse Go to Window->Preferences
2. In Left Panel, Select Java->Code Style->Code Template
3. Under "Configure generated code and comments", Expand Comments-> select Methods,Click Edit
Remove or replace the pattern ( \* @param args),Click OK
4. Under "Configure generated code and comments", Expand Code-> select Method Body,Click Edit
Remove or replace the pattern ( // TODO Auto-generated...),Click OK
5. Click OK ! | How to change auto-generated code when creating new class in Eclipse | [
"",
"java",
"eclipse",
""
] |
[This question](https://stackoverflow.com/questions/501412/why-does-autoboxing-make-some-calls-ambiguous-in-java) is about "Why does autoboxing make some calls ambiguous in Java?"
But reading through the answers, there are a number of references to casting and I'm not sure I completely understand the difference.
Can someone provide a simple explanation? | Boxing is when you convert a primitive type to a reference type, un-boxing is the reverse. Casting is when you want one type to be treated as another type, between primitive types and reference types this means an implicit or explicit boxing operation. Whether it needs to be explicit is a language feature. | Both casting and boxing/unboxing have to do with types and apparent (or real) conversion, but boxing/unboxing is specific to the relationship between primitive types and their corresponding wrapper types, while casting is the term for explicit or implicit change of type in the more general sense.
**Casting** is a general term with two related-but-different meanings:
1. Treating a value of one type **as if** it were a value of another type. Two examples of this first usages are:
1.1. Given that class `B` extends class `A`, you can ask for `myB` an instance of `B` to be treated as an instance of `A` by writing `((A) myB)` wherever a reference to an instance of `A` could appear. This doesn't actually produce a new instance of `A`.
1.2. Pre-Java5 collections stored all content as `Object`; this usually required you to use a cast after retrieving an object from a collection. For example, if you had stored a `String` in a `Map` and needed to get its length, you'd write something like `((String) myMap.get(someKey)).length()` where the cast would be required in order to call the `length` method of `String`. Again, this doesn't cause a new `String` to be created.
2. Explicitly **converting** one type to another (i.e. explicitly changing the representation). An example of this second usage is in the expression `((int) (float_var + 0.5F))` which rounds a floating-point variable by adding 0.5 (which produces a floating-point value) and then explicitly converting that value to an integer. The resulting integer value (after the `(int)` cast) is *produced* from the other value by internal computation.
Casting can be done when there's a superclass/subclass or interface/implementor relationship (meaning 1 above) or when the two types are primitive numeric types (meaning 2). You might look up "widening" and "narrowing" for more detail.
**Boxing** refers to wrapping primitive types in container objects, usually only done when you must have an object (e.g. storing a value in a collection). The primitive and wrapper types come in pairs:
```
int Integer
long Long
boolean Boolean
... ...
```
**Unboxing** simply means retrieving the primitive value from within its object wrapper.
As of Java5, when you write an expression that uses a primitive value where the corresponding wrapper type would be required (such as putting an integer into a collection), the compiler automagically slips in the code that actually wraps that primitive value. Likewise it will provide the unwrapping code for you.
So instead of writing (in pre-Java5) something like:
```
Map myMap = new HashMap();
...
myMap.put(someKey,Integer.valueOf(3));
...
int nextValue = (myMap.get(someKey)).intValue() + 1;
```
you can write:
```
Map<KeyType,Integer> myMap = new HashMap<KeyType,Integer>();
...
myMap.put(someKey,3);
...
int nextValue = myMap.get(someKey) + 1;
```
and the boxing/unboxing code is inserted by the compiler. | Java: What's the difference between autoboxing and casting? | [
"",
"java",
"casting",
"autoboxing",
""
] |
My enum consists of the following values:
```
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
```
I want to be able to output these values in a user friendly way though.
I don't need to be able to go from string to value again. | I use the [`Description`](http://msdn.microsoft.com/en-us/library/system.componentmodel.descriptionattribute.aspx) attribute from the System.ComponentModel namespace. Simply decorate the enum:
```
private enum PublishStatusValue
{
[Description("Not Completed")]
NotCompleted,
Completed,
Error
};
```
Then use this code to retrieve it:
```
public static string GetDescription<T>(this T enumerationValue)
where T : struct
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
``` | I do this with extension methods:
```
public enum ErrorLevel
{
None,
Low,
High,
SoylentGreen
}
public static class ErrorLevelExtensions
{
public static string ToFriendlyString(this ErrorLevel me)
{
switch(me)
{
case ErrorLevel.None:
return "Everything is OK";
case ErrorLevel.Low:
return "SNAFU, if you know what I mean.";
case ErrorLevel.High:
return "Reaching TARFU levels";
case ErrorLevel.SoylentGreen:
return "ITS PEOPLE!!!!";
default:
return "Get your damn dirty hands off me you FILTHY APE!";
}
}
}
``` | Enum ToString with user friendly strings | [
"",
"c#",
"enums",
"tostring",
""
] |
I am not sure when I should use *anonymous types* instead of *local variables* in C#.
I have:
```
string fullMessage // This is the full message including sender and recipient names
string sender = GetMessagePart(fullMessage, "from");
string recipient = GetMessagePart(fullMessage, "to");
//do some stuff and deliver the message
```
Should I use:
```
var msg = new {
sender = GetMessagePart(fullMessage, "from")
recipient = GetMessagePart(fullMessage, "to")
};
```
Instead? | ~~Do you mean statically typed variables? Note that anonymous types *are* statically typed...~~ (removed due to question edit)
There are 2 problems with C# anonymous types:
* you can't expose them through a method API
* you can't mutate them (the members are read-only)
If you only need to know about the data within a single method, and it is read-only, then an anonymous type is handy (and this covers a lot of cases, in reality).
If you need to mutate the data or pass it out to a caller, then use either a bespoke class, or simple variables (etc).
In the case given, I can't see a reason to use an anonymous type; if you just want the values, use the separate variable approach. If a "message" has a defined meaning, declare a `Message` class and populate that. | Does grouping a sender and recipient together make sense outside this method? If so, consider creating a class for them. If not, I would *usually* use separate local variables, but I suspect that's mostly through habit.
I suspect what we've here got is a pair of local variables which are conceptually related. The relationship may not be strong enough to deserve a full type, but it's meaningful within the method. In some ways, using an anonymous type is a very neat way of making that pairing obvious. On the other hand, if your method is long enough that it really needs that extra level of clarity, perhaps you should break it up anyway.
Note that using an anonymous type makes some refactoring techniques harder because the type is only available with the method (without a bit of hackery).
I realise that this is a wishy-washy answer, but it does strike me that there's some merit in the overall idea - it's a bit like using a tuple in a functional language. | Anonymous types VS Local variables, When should one be used? | [
"",
"c#",
".net",
""
] |
This pertains to C# & the .NET Framework specifically.
It's best practice not to initialize the following types in the .NET framework because the CLR initializes them for you:
int,
bool, etc.
and same for setting an object to null (I believe).
For example you do not need to do this and in fact it's a performance hit (drops in the bucket or not):
```
int Myvar = 0;
```
Just need `int Myvar;` and that's it. the CLR will initialize it to int.
I obviously just "know" from programming that int is set to 0 by default and bool to false.
And also setting an object to null because the CLR does it for you.
But how can you tell what those primitive types are set to. I tried opening up Reflector to take a look at int32 and bool but could not figure out how they are initialized by default.
I looked on msdn and I don't see it there either. Maybe I'm just missing it. | If you want a table, MSDN is your friend: [Default Values Table (C# Reference)](http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx) | You want a list like [this one](http://msdn.microsoft.com/en-us/library/83fhsxwc(VS.80).aspx)? | How to tell what value types are initialized to by the CLR | [
"",
"c#",
""
] |
Is there a better way to call MSBuild from C#/.NET than shelling out to the msbuild.exe? If yes, how? | Yes, add a reference to `Microsoft.Build.Engine` and use the [Engine](http://msdn.microsoft.com/en-us/library/microsoft.build.buildengine.engine.aspx) class.
PS: Take care to reference the right version. There are 2.0 and 3.5 assemblies and you'll have to [make sure that everyone gets the right one](http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/2772a075-4e2f-42af-9e7a-2228b794368e/). | For a .NET 2.0-specific version, you can use the following:
```
Engine engine = new Engine();
engine.BinPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.System)
+ @"\..\Microsoft.NET\Framework\v2.0.50727";
FileLogger logger = new FileLogger();
logger.Parameters = @"logfile=C:\temp\test.msbuild.log";
engine.RegisterLogger(logger);
string[] tasks = new string[] { "MyTask" };
BuildPropertyGroup props = new BuildPropertyGroup();
props.SetProperty("parm1","hello Build!");
try
{
// Call task MyTask with the parm1 property set
bool success = engine.BuildProjectFile(@"C:\temp\test.msbuild",tasks,props);
}
catch (Exception ex)
{
// your error handler
}
finally
{
engine.UnregisterAllLoggers();
engine.UnloadAllProjects();
}
``` | How to call MSBuild from C# | [
"",
"c#",
".net",
"msbuild",
""
] |
I'm working in a C++ unmanaged project.
I need to know how can I take a string like this "some data to encrypt" and get a byte[] array which I'm gonna use as the source for Encrypt.
In C# I do
```
for (int i = 0; i < text.Length; i++)
buffer[i] = (byte)text[i];
```
What I need to know is how to do the same but using unmanaged C++.
Thanks! | If you just need read-only access, then [`c_str()`](http://en.cppreference.com/w/cpp/string/basic_string/c_str) will do it:
```
char const *c = myString.c_str();
```
If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:
```
std::vector<char> bytes(myString.begin(), myString.end());
bytes.push_back('\0');
char *c = &bytes[0];
``` | [`std::string::data`](http://en.cppreference.com/w/cpp/string/basic_string/data) would seem to be sufficient and most efficient. If you want to have non-const memory to manipulate (strange for encryption) you can copy the data to a buffer using [memcpy](http://opengroup.org/onlinepubs/007908799/xsh/memcpy.html):
```
unsigned char buffer[mystring.length()];
memcpy(buffer, mystring.data(), mystring.length());
```
STL fanboys would encourage you to use [std::copy](http://www.sgi.com/tech/stl/copy.html) instead:
```
std::copy(mystring.begin(), mystring.end(), buffer);
```
but there really isn't much of an upside to this. If you need null termination use `std::string::c_str()` and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the `length`. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using `std::string::data()` discourages you from lazily making assumptions about the underlying bits in the string. | Get bytes from std::string in C++ | [
"",
"c++",
"string",
""
] |
This seems like a reasonable (and maybe simple?) scenario, but how would you do the following:
Lets say I have 2 interfaces:
```
Interface ISimpleInterface
string ErrorMsg { get; }
End Interface
Interface IExtendedInterface
string ErrorMsg { get; set; }
string SomeOtherProperty { get; set; }
End Interface
```
I want a class to implement both interfaces:
```
Public Class Foo Implements ISimpleInterface, IExtendedInterface
```
How do I define the ErrorMsg property in the class given that each interface has a different access level?
Here is my scenario in case you are wondering: I am writing a UserControl using a psuedo MVC arhitecture, where the UserControl exposes the extended interface to it's Controller, and exposes the Simple interface to the Consumers of the control.
By the way, implementing this in VB.NET (any suggested synatx in vb would be appreciated). | You can implement one of them or both interfaces with an 'explicit interface' implementation, so the compiler knows which ErrorMsg property belongs to which interface.
To do this simply write :ISimpleInterface (for C#) after your class name and then click on ISimpleInterface and select implement explicit interface.
More information here: <http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx> | Sorry but I don't master VB.Net syntax.
In C# you can implement interfaces implicitly or explicitly.
If your class Foo implements ErrorMsg as a public method, this implementation will be used for both interface.
If you want distinct implementation you can implement it explicitly :
```
string ISimpleInterface.ErrorMsg {get { ... } }
string IExtendedInterface.ErrorMsg {get { ... } set { ... }}
``` | Implementing 2 Interfaces with 'Same Name' Properties | [
"",
"c#",
"vb.net",
"multiple-inheritance",
""
] |
I came across this [link](http://www.codeproject.com/KB/menus/Office2007Renderer.aspx) today that offers a ToolStripProfessionalRenderer implementation for the Office 2007 look-and-feel.
From what I can tell, it would be fairly straightforward (albeit tedious) to customize this to support various other themes, such as the silver and black themes of Office 2007.
More specifically, I'd like to find a color table that matches Visual Studio 2008. Does anyone know where I might find this? | I found this a while back, and even have a bookmark for it: <http://blogs.msdn.com/jfoscoding/articles/489637.aspx>
I think this is what you're looking for. | Yes, tedious. You can find color settings in the MFC Feature Pack files, included with VS2008 SP1. There are 4 Office themes, they each have a style.xml file in a subdirectory of vc/atlmfc/include. Black, Blue, Silver and Aqua. | ToolStripProfessionalRenderer for Visual Studio 2008 Look-and-Feel | [
"",
"c#",
".net",
"winforms",
"user-interface",
"themes",
""
] |
I would like to have some long-running server applications periodically output general GC performance numbers in Java, something like the GC equivalent of Runtime.freeMemory(), etc. Something like number of cycles done, average time, etc.
We have systems running on customer machines where there is a suspicion that misconfigured memory pools are causing excessive GC frequency and length - it occurs to me that it would be good in general to periodically report the basic GC activity.
Is there any platform independent way to do this?
**EDIT: I specifically want to output this data to the system log (the console), while running; this is not something I want to connect to the JVM for, as would be with JConsole or JVisualVM.**
Edit2: The MX bean looks like what I want - does anyone have a working code example which obtains one of these? | Here's an example using `GarbageCollectorMXBean` to print out GC stats. Presumably you would call this method periodically, e.g. scheduling using a `ScheduledExecutorService`.
```
public void printGCStats() {
long totalGarbageCollections = 0;
long garbageCollectionTime = 0;
for(GarbageCollectorMXBean gc :
ManagementFactory.getGarbageCollectorMXBeans()) {
long count = gc.getCollectionCount();
if(count >= 0) {
totalGarbageCollections += count;
}
long time = gc.getCollectionTime();
if(time >= 0) {
garbageCollectionTime += time;
}
}
System.out.println("Total Garbage Collections: "
+ totalGarbageCollections);
System.out.println("Total Garbage Collection Time (ms): "
+ garbageCollectionTime);
}
``` | See [GarbageCollectorMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/GarbageCollectorMXBean.html). | Can you get basic GC stats in Java? | [
"",
"java",
"garbage-collection",
""
] |
I've got most of the code for writing a value to the windows registry, however when I change the path to a dummy key and value that I've set up for testing it fails. My code is below:
```
HKEY hKey;
LPCTSTR sk = TEXT("SOFTWARE\TestSoftware");
LONG openRes = RegOpenKeyEx(HKEY_LOCAL_MACHINE, sk, 0, KEY_ALL_ACCESS , &hKey);
if (openRes==ERROR_SUCCESS) {
printf("Success opening key.");
} else {
printf("Error opening key.");
}
LPCTSTR value = TEXT("TestSoftwareKey");
LPCTSTR data = "TestData\0";
LONG setRes = RegSetValueEx (hKey, value, 0, REG_SZ, (LPBYTE)data, strlen(data)+1);
if (setRes == ERROR_SUCCESS) {
printf("Success writing to Registry.");
} else {
printf("Error writing to Registry.");
}
LONG closeOut = RegCloseKey(hKey);
if (closeOut == ERROR_SUCCESS) {
printf("Success closing key.");
} else {
printf("Error closing key.");
}
```
All three tests yield error statuses.
The part that confuses me is that I was able to run this code when pointing it at other portions of the registry. Any ideas?
thanks,
brian | I feel silly. The solution is that need to properly escape the slash in the string as follows:
```
LPCTSTR sk = TEXT("SOFTWARE\\TestSoftware");
```
Hopefully someone finds this useful... | ```
HKEY OpenKey(HKEY hRootKey, char* strKey)
{
HKEY hKey;
LONG nError = RegOpenKeyEx(hRootKey, strKey, NULL, KEY_ALL_ACCESS, &hKey);
if (nError==ERROR_FILE_NOT_FOUND)
{
cout << "Creating registry key: " << strKey << endl;
nError = RegCreateKeyEx(hRootKey, strKey, NULL, NULL, REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL, &hKey, NULL);
}
if (nError)
cout << "Error: " << nError << " Could not find or create " << strKey << endl;
return hKey;
}
void SetintVal(HKEY hKey, LPCTSTR lpValue, DWORD data)
{
LONG nError = RegSetValueEx(hKey, lpValue, NULL, REG_DWORD, (LPBYTE)&data, sizeof(DWORD));
if (nError)
cout << "Error: " << nError << " Could not set registry value: " << (char*)lpValue << endl;
}
DWORD GetintVal(HKEY hKey, LPCTSTR lpValue)
{
DWORD data;
DWORD size = sizeof(data);
DWORD type = REG_DWORD;
LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)&data, &size);
if (nError==ERROR_FILE_NOT_FOUND)
data = 0;
SetVal() is called.
else if (nError)
cout << "Error: " << nError << " Could not get registry value " << (char*)lpValue << endl;
return data;
}
BOOL SetcharVal(HKEY Key,char* subkey,char* StringName,char* Stringdata)
{
HKEY hKey = OpenKey(Key,subkey);
LONG openRes = RegOpenKeyEx(Key, subkey, 0, KEY_ALL_ACCESS , &hKey);
if (openRes==ERROR_SUCCESS) {
} else {
printf("Error opening key.");
}
LONG setRes = RegSetValueEx (hKey, StringName, 0, REG_SZ, (LPBYTE)Stringdata, strlen(Stringdata)+1);
if (setRes == ERROR_SUCCESS) {
} else {
printf("Error writing to Registry.");
}
LONG closeOut = RegCloseKey(hKey);
if (closeOut == ERROR_SUCCESS) {
} else {
printf("Error closing key.");
}
}
char* GetCharVal(HKEY Key,char* subkey,char* StringName)
{
DWORD dwType = REG_SZ;
HKEY hKey = 0;
char value[1024];
DWORD value_length = 1024;
RegOpenKey(HKEY_LOCAL_MACHINE,subkey,&hKey);
RegQueryValueEx(hKey, StringName, NULL, &dwType, (LPBYTE)&value, &value_length);
RegCloseKey(hKey);
return value;
}
```
I am using this code. | Writing string (REG_SZ) values to the registry in C++ | [
"",
"c++",
"registry",
""
] |
My Ant build includes a junit task that runs some tests. In order for the tests to work, the value of the property that specifies the current working directory (`user.dir`) must be changed, but I am unsure how to achieve this.
The task in question currently looks like this:
```
<junit printsummary="withOutAndErr" fork="true"
haltonfailure="yes" showoutput="true"
filtertrace="false" dir="C:/workspace/obp-web">
<jvmarg value="-Duser.dir=C:/workspace/obp-web"/>
<classpath>
<fileset dir="${web.lib.dir}" includes="**/*.jar"/>
<fileset dir="${lib.dir}" includes="**/*.jar"/>
</classpath>
<batchtest fork="no" todir="${web.build.dir}/testresults">
<formatter type="xml"/>
<zipfileset src="${web.build.dir}/test-obp-web.jar">
<include name="**/*Test.class"/>
</zipfileset>
</batchtest>
</junit>
```
Notice that I've tried to use both the "dir" attribute and the "jvmarg" task to change the working directory to C:/workspace/obp-web. However when I run Ant with verbose output turned on, I see the following output, which indicates that the working dir has not been set correctly:
> **[junit] dir attribute ignored if running in the same VM**
>
> **[junit] Using System properties**
> {java.runtime.name=Java(TM) SE Runtime
> Environment,
> sun.boot.library.path=c:\jdk6\jre\bin,
> java.vm.version=10.0-b23, ant.lib
> rary.dir=C:\java\apache-ant-1.7.0\lib,
> java.vm.vendor=Sun Microsystems Inc.,
> java.vendor.url=<http://java.sun.com/>,
> path.separator=;, java.vm.name=Java
> HotSpot(T M) Client VM,
> file.encoding.pkg=sun.io,
> user.country=CA,
> sun.java.launcher=SUN\_STANDARD,
> sun.os.patch.level=Service Pack 1,
> java.vm.specification.name=Java Virtual Machine Specification,
> **user.dir=c:\workspace\obp-ear**, java.runtime.version=1.6.0\_07-b06,
> java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment,
> java.endorse
> d.dirs=c:\jdk6\jre\lib\endorsed,
> os.arch=x86,
> java.io.tmpdir=C:\Users\donal\AppData\Local\Temp\,
> line.separator= | Try using a jvmarg:
```
<junit fork="yes">
<jvmarg value="-Duser.dir=somedir"/>
...
</junit>
```
Note that fork **must** be true on both the *junit* tag and the *batchtest* tag as the *batchtest* tag overrides the value from *junit*. Jvmargs only work if junit forks a new JVM. | Use the attribute "dir" (must also fork the vm):
<http://ant.apache.org/manual/Tasks/junit.html> | How do I set the working directory for the Ant 'junit' task? | [
"",
"java",
"ant",
"junit",
""
] |
I've been tasked with debugging a Java (J2SE) application which after some period of activity begins to throw OutOfMemory exceptions. I am new to Java, but have programming experience. I'm interested in getting your opinions on what a good approach to diagnosing a problem like this might be?
This far I've employed JConsole to get a picture of what's going on. I have a hunch that there are object which are not being released properly and therefor not being cleaned up during garbage collection.
Are there any tools I might use to get a picture of the object ecosystem? Where would you start? | I'd start with a proper Java profiler. JConsole is free, but it's nowhere near as full featured as the ones that cost money. I used JProfiler, and it was well worth the money. See <https://stackoverflow.com/questions/14762/please-recommend-a-java-profiler> for more options and opinions. | Try the [Eclipse Memory Analyzer](http://www.eclipse.org/mat/), or any other tool that can process a java heap dump, and then run your app with the flap that generates a heap dump when you run out of memory.
Then analyze the heap dump and look for suspiciously high object counts.
See this article for more information on the [heap dump](http://blogs.oracle.com/alanb/entry/heap_dumps_are_back_with).
EDIT: Also, please note that your app may just legitimately require more memory than you initially thought. You might try increasing the java minimum and maximum memory allocation to something significantly larger first and see if your application runs indefinitely or simply gets slightly further. | Strategies for the diagnosis of Java memory issues | [
"",
"java",
"memory",
"garbage-collection",
"jconsole",
""
] |
I'm curious about how .NET will affect Python and Ruby applications.
Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific?
If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts? | I can't say anything about IronRuby, but most python implementations (like IronPython, Jython and PyPy) try to be as true to the CPython implementation as possible. IronPython is quickly becoming one of the best in this respect though, and there is a lot of traffic on Planet Python about it.
The main thing that will encourage developers to write code that's different from what they would write in CPython is the lack of C extension modules like NumPy (This is a problem in Jython and PyPy as well).
An interesting project to keep your eye on is IronClad, which will let you call C extension modules from within IronPython. This should eventually mean that you can develop code under CPython, using whatever modules you like, and it will run unmodified on IronPython.
<http://www.resolversystems.com/documentation/index.php/Ironclad>
So to answer your questions:
It should be easy enough to write IronPython applications that work on CPython as well, but I would probably aim to go the other way around: CPython programs that work on IronPython as well. That way, if it doesn't work then it's more likely to be a known bug with a known work-around.
The advantage of IronPython et al *existing* is that they provide alternative implementations of the language, which are sometimes useful for spotting bugs in CPython. They also provide alternative methods for deploying your Python applications, if for some reason you find yourself in a situation (like silverlight) where distributing the CPython implementation with your application is not appropriate. | > *Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific?*
IronRuby currently ships with most of the core ruby standard library, and support for ruby gems.
This means that it will support pretty much any native ruby app that doesn't rely on C extensions.
The flipside is that it will be possible to write native ruby apps in IronRuby that don't rely on the CLR, and those will be portable to MRI.
Whether or not people choose to create or use extensions for their apps using the CLR is the same question as to whether people create or use C extensions for MRI - one is no more portable than the other.
There is a side-question of **"because it is so much easier to create IronRuby extensions in C# than it is to create CRuby extensions in C, will people create extensions where they should be sticking to native ruby code?"**, but that's entirely subjective.
On the whole though, I think anything that makes creating extensions easier is a big win.
---
> *If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?*
1. Performance: IronRuby is already faster for the most part than MRI 1.8, and isn't far off MRI 1.9, and things will only improve in future. I think python is similar in this respect.
2. Deployment: As people have mentioned, running a native ruby cross-platform rails app inside IIS is an attractive proposition to some windows-based developers, as it lets them better integrate with existing servers/management infrastructure/etc
3. Stability: While MRI 1.9 is much better than 1.8 was, I don't think anyone could disagree that CLR has a much better garbage collector and base runtime than C ruby does. | How will Python and Ruby applications be affected by .NET? | [
"",
".net",
"python",
"ruby",
"ironpython",
"ironruby",
""
] |
What is the best way to add a hyperlink in a JLabel? I can get the view using html tags, but how to open the browser when the user clicks on it? | You can do this using a `JLabel`, but an alternative would be to style a [`JButton`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html). That way, you don't have to worry about [accessibility](http://en.wikipedia.org/wiki/Computer_accessibility) and can just fire events using an [`ActionListener`](http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html).
```
public static void main(String[] args) throws URISyntaxException {
final URI uri = new URI("http://java.sun.com");
class OpenUrlAction implements ActionListener {
@Override public void actionPerformed(ActionEvent e) {
open(uri);
}
}
JFrame frame = new JFrame("Links");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 400);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JButton button = new JButton();
button.setText("<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
+ " to go to the Java website.</HTML>");
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setBorderPainted(false);
button.setOpaque(false);
button.setBackground(Color.WHITE);
button.setToolTipText(uri.toString());
button.addActionListener(new OpenUrlAction());
container.add(button);
frame.setVisible(true);
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) { /* TODO: error handling */ }
} else { /* TODO: error handling */ }
}
``` | I'd like to offer yet another solution. It's similar to the already proposed ones as it uses HTML-code in a JLabel, and registers a MouseListener on it, but it also displays a HandCursor when you move the mouse over the link, so the look&feel is just like what most users would expect. If browsing is not supported by the platform, no blue, underlined HTML-link is created that could mislead the user. Instead, the link is just presented as plain text.
This could be combined with the SwingLink class proposed by @dimo414.
```
public class JLabelLink extends JFrame {
private static final String LABEL_TEXT = "For further information visit:";
private static final String A_VALID_LINK = "http://stackoverflow.com";
private static final String A_HREF = "<a href=\"";
private static final String HREF_CLOSED = "\">";
private static final String HREF_END = "</a>";
private static final String HTML = "<html>";
private static final String HTML_END = "</html>";
public JLabelLink() {
setTitle("HTML link via a JLabel");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel(LABEL_TEXT);
contentPane.add(label);
label = new JLabel(A_VALID_LINK);
contentPane.add(label);
if (isBrowsingSupported()) {
makeLinkable(label, new LinkMouseListener());
}
pack();
}
private static void makeLinkable(JLabel c, MouseListener ml) {
assert ml != null;
c.setText(htmlIfy(linkIfy(c.getText())));
c.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
c.addMouseListener(ml);
}
private static boolean isBrowsingSupported() {
if (!Desktop.isDesktopSupported()) {
return false;
}
boolean result = false;
Desktop desktop = java.awt.Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
result = true;
}
return result;
}
private static class LinkMouseListener extends MouseAdapter {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
JLabel l = (JLabel) evt.getSource();
try {
URI uri = new java.net.URI(JLabelLink.getPlainLink(l.getText()));
(new LinkRunner(uri)).execute();
} catch (URISyntaxException use) {
throw new AssertionError(use + ": " + l.getText()); //NOI18N
}
}
}
private static class LinkRunner extends SwingWorker<Void, Void> {
private final URI uri;
private LinkRunner(URI u) {
if (u == null) {
throw new NullPointerException();
}
uri = u;
}
@Override
protected Void doInBackground() throws Exception {
Desktop desktop = java.awt.Desktop.getDesktop();
desktop.browse(uri);
return null;
}
@Override
protected void done() {
try {
get();
} catch (ExecutionException ee) {
handleException(uri, ee);
} catch (InterruptedException ie) {
handleException(uri, ie);
}
}
private static void handleException(URI u, Exception e) {
JOptionPane.showMessageDialog(null, "Sorry, a problem occurred while trying to open this link in your system's standard browser.", "A problem occured", JOptionPane.ERROR_MESSAGE);
}
}
private static String getPlainLink(String s) {
return s.substring(s.indexOf(A_HREF) + A_HREF.length(), s.indexOf(HREF_CLOSED));
}
//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String linkIfy(String s) {
return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
}
//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String htmlIfy(String s) {
return HTML.concat(s).concat(HTML_END);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JLabelLink().setVisible(true);
}
});
}
}
``` | How to add hyperlink in JLabel? | [
"",
"java",
"swing",
"hyperlink",
"jlabel",
""
] |
I have a object built through a factory containing my parameters read from the url.
From this object, I can get the language parameter
> $language =
> $my\_parameters->getLanguage();
$language is NULL if it isn't been set.
$language may also be invalid ( $language->isValid() returns false ).
So, to build my page, I need some parameters.
The page is also built trough a factory. Then I know which parameters I need to build it. If it miss parameters, I build them with a valid default value according to the page asked.
At this point, into the page factory, if a have an invalid parameter, I throw an exception.
My page object contains a body object that needs a language parameter. I know that my parameters are valid when I build my body object.
Into my body object, I retrieve the language
> $language =
> $my\_parameters->getLanguage();
At this point, $language \*\* MUST \*\* be valid.
So I verify again
```
$language = $my_parameters->getLanguage();
if( is_null( $language ) or !$language->isValid() ) {
throw new Exception( 'Language must be valid.' );
}
```
If I need 4 parameters, I have 4 *ifs* that verify if the object is not NULL and not invalid.
I do it because the **method is public** where $language is used in the body object .
**And the body object may be built outside the factory.** Who knows...
Is it correct to verify in that case ?
What are the best-practices about that ? | [Here is the case for *not* checking for null](http://googletesting.blogspot.com/2009/02/to-assert-or-not-to-assert.html) in a recent blog post from the Google Testing blog.
The argument is that it gets in the way of writing clear, easy unit tests, because you can't actually fake the pieces that don't matter, because your exceptions/assertions will be thrown.
The author (Miško Hevery) does qualify the commentary by saying that if it's an external API, it might still be worth checking for an error condition. | i know very little about your domain, but in the general case, i like to assert(not null) all over the place, because typically if i end up with a null object somewhere, its a bug.
it's also good practice to prefer reference types which typically can't even be null. | Should I always verify if an object is NULL? | [
"",
"php",
"oop",
""
] |
I am writing unit tests for some of my code and have run into a case where I have an object with a small exposed interface but complex internal structures as each exposed method runs through a large number of internal functions including dependancies on the object's state. This makes the methods on the external interface quite difficult to unit test.
My initial question is should I be aiming to unit test these internal functions as well, as they are simpler and hence easier to write tests for? My gut feeling says yes, which leads to the follow-up question of if so, how would I go about doing this in C++?
The options I've come up with are to change these internal functions from private to protected and use either a friend class or inheritence to access these internal functions. Is this the best/only method of doing this will preserving some of the semantics of keeping the internal methods hidden? | Short answer: yes.
As to how, I caught a passing reference on SO a few days ago:
```
#define private public
```
in the unit testing code evaluated before the relevant headers are read...
Likewise for protected.
Very cool idea.
---
Slightly longer answer: Test if the code is not *obviously correct*. Which means essentially any code that does something non-trivial.
---
On consideration, I am wondering about this. You won't be able to link against the same object file that you use in the production build. Now, unit testing is a bit of an artificial environment, so perhaps this is not a deal-breaker. Can anyone shed some light on the pros and cons of this trick? | If your object is performing highly complex operations that are extremely hard to test through the limited public interface, an option is to factor out some of that complex logic into utility classes that encapsulate specific tasks. You can then unit test those classes individually. It's always a good idea to organize your code into easily digestible chunks. | Should non-public functions be unit tested and how? | [
"",
"c++",
"unit-testing",
""
] |
I have Python 2.6 and I want to install easy \_ install module. The problem is that the only available installation package of easy \_ install for Python 2.6 is an .egg file! What should I do? | You could try [this script](http://peak.telecommunity.com/dist/ez_setup.py).
```
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import sys
DEFAULT_VERSION = "0.6c11"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090',
'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4',
'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7',
'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5',
'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de',
'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b',
'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2',
'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
except pkg_resources.DistributionNotFound:
pass
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])
``` | sh setuptools-0.6c9-py2.5.egg | How do I install an .egg file without easy_install in Windows? | [
"",
"python",
"easy-install",
"egg",
""
] |
Is there anyway to get tuple operations in Python to work like this:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
```
instead of:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
```
I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only way would be to redefine them? | ```
import operator
tuple(map(operator.add, a, b))
``` | Using all built-ins..
```
tuple(map(sum, zip(a, b)))
``` | Python element-wise tuple operations like sum | [
"",
"python",
"tuples",
""
] |
Ok, so I'm psyched about another list. I got myself a copy of the beta Clojure programming book...
And the one thing I'm noticing most is that it's assumed I know... like all the major java classes.
Except, generally, I don't really care about Java. I just want enough knowledge of it for Clojure to be an option for me.
Any suggestion as to how to learn just what I need of it all? | My main recommendation for you, you've already accomplished by buying Programming Clojure. I've avoided and loathed Java for years and years, and (Programming) Clojure rehabilitated it enough that the language now excites me. Who'd've thought that a famously onerous system would let you interactively `(map #(.getName %) (.getMethods (class "")))` ? Look through "Working with Java, 3.5 Adding Ant Projects and Tasks to Lancet" for an exploration in a style that I'm familiar with from *Ruby*.
If you're in [Freenode](http://freenode.net/) #clojure , also join ##java. Get Java's [API documentation](http://java.sun.com/javase/reference/api.jsp) and keep it handy. Search the web for a [Java answer](http://www.spiration.co.uk/post/1199/Java%20md5%20example%20with%20MessageDigest) to something you want to do and translate it more or less directly [to Clojure](http://paste.lisp.org/display/74629).
EDIT: At clj:
```
user=> (use 'clojure.contrib.javadoc)
nil
user=> (keys (ns-publics 'clojure.contrib.javadoc))
(*remote-javadocs* javadoc find-javadoc-url add-remote-javadoc
*core-java-api* add-local-javadoc *local-javadocs*)
user=> (javadoc "this is a java.lang.String")
true (browses to http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html)
user=> (javadoc java.net.ServerSocket)
true (...)
user=>
``` | Umm, actually, though Clojure was developed with Java developers considered, it was not written *for* Java programmers.
> Clojure is designed to interoperate well in the Java environment.
Although it does, this is not *what* it was designed for (at least not in language part of the "Java environment"). And "Java environment" implies that the language and JVM are interconnected in some way that makes them one. They are not. Conjure is a native JVM language (unlike Jython or JRuby), and it uses a very well-built virtual machine to live within.
> Like Greg said though, Clojure is built to be with Java, and unless you want to really get into Clojure's software transactional memory system, I'd say to check out a different Lisp.
Nope, sorry. Clojure was not "build to be with Java". It was built for the JVM. You can use Java libraries if you like, but it isn't required (though it is useful). And as far as the advice to use a different Lisp if you don't want to learn Java. That's ridiculous. Clojure isn't meant to be Java; it is meant to be a 1st-class Lisp. And one, by the way, that means to enhance Lisp in certain ways, to make it more modern and functional. It's ability to work well with Java should be considered a bonus, not a liability.
> As Greg above points out, languages like Clojure and Groovy target the JVM for one main reason, so that Java developers can have the best of both worlds.
Also wrong. For reasons stated above. They were not written for Java developers. Sorry to be so blunt here, but I haven't seen one educated post on Clojure in these replies,and I just learned about Clojure today! It is just frustrating to see this kind of harmful advice so easily given.
I will just end with a quote by Rick Hickey (the guy who wrote Clojure):
"You can hate Java and like the JVM."
He goes on to say that that is where he stands. | Learning Clojure without Java Knowledge | [
"",
"java",
"lisp",
"clojure",
""
] |
I have my own php data object class that wraps the mysqli library. It works fine handling most datatypes, including text. As soon as I change a table column from text to mediumtext, I get the error described in the title of this question. I've tested my php scripts on several shared hosting environments, and I only get this error on one of them.
Does the MediumText and LongText really use up that much memory?
I will start optimizing my php classes, but I want to make sure I'm on the right track.. | mediumtext can hold up to 16777215 as specified in <http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html>
This would appear to be > than you memory limit as defined by php. So it makes sense. | The mediumtext and longtext fields could, potentially, hold that much information. Are you just changing the column type, or are you changing the column type then jamming it full of text? If it's the former, my guess would be that there's some run away loop/recursion that's building up a bunch of objects/arrays/somethings and you're hitting PHP's default memory ceiling.
You can control the amount of memory allocated to PHP via php.ini, or you can use the ini\_set function to set the values at run-time.
```
ini_set("memory_limit","12M");
``` | Mysql MediumText causes PHP Fatal error: Allowed memory size of 8388608 bytes exhausted | [
"",
"php",
"memory-management",
""
] |
I'm trying to use the code below to send messages via `System.Net.Mail` and am **sometimes** getting subjects like `'=?utf-8?B?W3AxM25dIEZpbGV...'` (trimmed). This is the code that's called:
```
MailMessage message = new MailMessage()
{
From = new MailAddress("someone@somewhere.com", "Service"),
BodyEncoding = Encoding.UTF8,
Body = body,
IsBodyHtml = true,
ReplyTo = new MailAddress("do.not.reply@somewhere.com"),
SubjectEncoding = Encoding.UTF8
};
foreach (string emailAddress in addresses)
{
message.To.Add(new MailAddress(emailAddress.Trim(), "Person"));
}
message.Subject = subject;
```
I'd like to emphasize that this does not happen all of the time.
What am I doing wrong? | When your subject contains characters outside the ASCII range, then the mailing software must encode them (RFC2822 mail does not permit non-ASCII characters in headers). There are two ways to do this:
* **Quoted Printable** (subject starts with `"=?utf-8?Q"`)
* **Base64** (subject starts with `"=?utf-8?B"`)
It appears that the framework has figured that the Base64 encoding is more efficient (=shorter) than the quoted-printable encoding. This makes sense when your subject contains relatively many characters outside the ASCII range.
To answer your question: You're doing nothing wrong. That's how internet mail with non-ASCII characters is supposed to look like. Of course, the software that reads such mail should detect and decode such subject fields. | I came across this post when I was debugging an identical problem, and based on my further investigations I can provide an alternate explanation to Andreas's:
The problem may be that your e-mail client software (Outlook 2003, in my case) is incorrectly decoding the subject line. In other words, it's a bug in Outlook, not in .NET or your program.
If you use a subject value like this (the letter "c" repeated 256 times), it displays fine in Outlook:
```
subject = New String("c"c, 256)
```
Likewise, if you use a subject like this (the letter "c" repeated 178 times, with a Unicode non-breaking space character appended), it also displays as expected in Outlook:
```
subject = New String("c"c, 178) + System.Text.Encoding.UTF8.GetChars(New Byte() {194, 160})
```
However, the following subject displays as "=?utf-8?B"-prepended garbage in Outlook:
```
subject = New String("c"c, 179) + System.Text.Encoding.UTF8.GetChars(New Byte() {194, 160})
```
The difference is that this third subject line is 256 bytes when UTF-8-encoded. I assume that Outlook must be truncating the subject line to 255 characters before displaying it... which would be fine except that it is doing this by truncating the encoded string to 255 bytes, which cuts off the encoding terminator ("?="), making it undecodable.
This is a bug in Outlook and not your mail provider or .NET; you can see the full, untruncated UTF-8 encoded subject line in Outlook by right-clicking on the message in your message list and selecting "Options..." from the context menu, then scrolling down in the "Internet Headers" box until you see the line starting with "Subject:".
Contrary to the situation that Andreas suggests, the problem manifests itself not only when there are many non-ASCII characters, but when there is one or more non-ASCII characters and the subject line is long. A workaround might be to use a shorter subject line or to strip out all the non-ASCII characters in your subject.
(This bug was particularly tricky for me to track down because, as above, the problem data included no obvious non-ASCII characters -- just a few non-breaking spaces. These display the same as regular ASCII spaces when you print them out to the console. Moreover, if you change the value of the string variable in the Visual Studio debugger, it silently replaces them with regular spaces.) | System.Net.Mail and =?utf-8?B?XXXXX.... Headers | [
"",
"c#",
".net",
"encoding",
"utf-8",
"system.net.mail",
""
] |
A WCF service exposing multiple elements in DataContract as DataMember
```
[DataMember(IsRequired = true, EmitDefaultValue = false)]
public string Source;
[DataMember(IsRequired = true, EmitDefaultValue = false)]
public string Target;
```
In generated proxy (through add service reference in VS 2008) at client, the client can pass null or empty string in Source or Target. how can I enforce Source and Target as Required at client side. i.e. client should get an exception if Source or Target is set to null, before invoking the service call. | Well, both null (xsi:nil) and an empty string *are* values - they just aren't values you want.
During deserialization (at client or server):
You could try putting some code in the setter to throw an exception for invalid values?
Alternatively (for more complex cases), I believe that data-contracts support deserialization callbacks, which should allow you to validate...
For example, you can add (in a partial class, if necessary, at the client):
```
[OnDeserialized]
internal void OnDeserialized(StreamingContext context)
{
if (string.IsNullOrEmpty(Bar))
{
throw new InvalidOperationException("No Bar!");
}
}
```
For pre-send checks (at the client), you would have to add an extra validation method, or perhaps (again, in a partial class):
```
[OnSerializing]
internal void OnSerializing(StreamingContext context)
{
if (string.IsNullOrEmpty(Bar))
{
throw new InvalidOperationException("No Bar!");
}
}
```
However, the server **must** also validate this - you can't assume that it is *your* client code that has sent the message. | You can't enforce anything on the client side. Think about it, a client can be custom developed by you, maybe not even in .Net like Java etc. IsRequired = true means that the type must have that member serialized over the wire, the value maybe be a null.
The only way is to throw a exception from you server if the value is null and use a proper fault contract. | How to specify if a Field in required in generated Proxy | [
"",
"c#",
"wcf",
"web-services",
""
] |
Hey. Is it possible to overload operator<< for primitive types? Fx lets say that I want to write a std::endl each time want to write a int. Can I overload operator<< for int, so that it automatic puts a std::endl to the output? I have tried with this,
```
std::ostream& operator<<(std::ostream& strm, int & i)
{
strm << i << std::endl;
return strm;
}
```
but it doesn't work. I cant recall the compiler error message, but I think that I'm getting operator overloading all wrong any ways.
I try to call the above overloaded operator<< in this way,
```
int main()
{
int i = 2;
std::out<<"Here is an int " << i;
return 0;
}
```
But it doesn't work at all. Maybe I can't overload POD types? | As zabzonk said, the standard library provides an (ostream&, int) overload so you can't define another.
To simulate what you were doing (though it is completely pointless in its present form :) :
```
class EndlinedInteger {
public:
EndlinedInteger(int i) : i(i) { }
friend ostream& operator<<(ostream&, EndlinedInteger const&);
private:
int i;
};
ostream& operator<<(ostream& out, EndlinedInteger const& ei) {
out << ei.i << endl;
return out;
}
int main()
{
EndlinedInteger i = 2;
std::cout<<"Here is an int " << i;
}
``` | Remember that here you use << operator not only on int but also on ostream. You could derive from ostream and implement it in your own derived class, but I would suggest to make a simple macro like
```
#define EL(i) (i)<<std::endl
```
Alternatively you could make boxed int class and override the << for standard ostream and boxed int (like in answer by Iraimbilanja) class. Sounds like huge overkill but could work. | Overloading operator<< for primitive types. Is that possible? | [
"",
"c++",
"stl",
"operator-overloading",
""
] |
I declare a static char array, then I pass it to a function. How to get the no. of bytes in the array inside the function? | You would have to pass it to the function. You can use sizeof() to get the size of an array.
```
const char foo[] = "foobar";
void doSomething( char *ptr, int length)
{
}
doSomething(foo, sizeof(foo));
```
This [MSDN page](http://msdn.microsoft.com/en-us/library/4s7x1k91(VS.71).aspx) has explains more about sizeof and has a bigger example.
Edit: \* [see j\_random\_hacker's answer](https://stackoverflow.com/questions/453099/size-of-static-array#453131) for an intriguing technique using templates... \* | Use a function template instead that has a non-type template parameter:
```
template <size_t N>
void func(char (&a)[N]) {
for (int i = 0; i < N; ++i) {
cout << "a[" << i << "] = " << a[i] << endl; // Or whatever you want to do
}
}
```
To call:
```
char myArray[500]; // Or "static char myArray[500]", if you want
func(myArray);
```
A new copy of this function will be instantiated for each distinct size of array that it is called with, so if you call it with many different-sized arrays, you'll get some code bloat. But that's not likely to be the case. | Size of static array | [
"",
"c++",
"arrays",
"size",
""
] |
What is the best way to do this in Access?
```
Create table tmp
(
plant int,
material vchar(20),
workcenter int,
setuptime vchar(20)
)
insert into tmp values( 1, mat1, 2, 30)
insert into tmp values( 1, mat1, 3, 30)
insert into tmp values( 1, mat2, 3, 30)
insert into tmp values( 1, mat2, 4, 30)
insert into tmp values( 2, mat1, 4, 30)
insert into tmp values( 2, mat1, 5, 30)
```
Result needs to look like.
```
Plant Material Workcenter1 Setuptime1 Workcenter2 Setuptime2
1 Mat1 2 30 3 30
1 Mat2 3 30 4 30
2 Mat1 4 30 5 30
```
I was thinking that this might work, but there has to be a better way.
```
SELECT t.Plant,
t.Material,
t.Workcenter as Workcenter1,
t.setuptime as SetupTime1
t2.Workcenter as Workcenter2,
t2.setuptime as SetupTime2
FROM tmp t
LEFT JOIN tmp t2
on t.plant = t2.plant
and t.material = t2.material
```
Thanks a bunch. | From what I understand of the problem you want to solve I don't think it's feasible using a standard SQL query (at least not in Access).
I tried to hack some code that does what you want (I think).
**How to use it**
Just copy/paste the code below in a VBA module.
From code, or, from the VBA IDE Immediate window if you want to test it, just call:
```
ExpandTable
```
**Assumptions**
* the table `temp` exists with the data you want to expand containing the plant/material/worksatation/etc
* the `temp` table is not empty (I have omitted some code checks to avoid bloating the sample).
* the expanded table will be created in a new table called `result`.
**Code**
```
Public Sub ExpandTable()
Dim db As DAO.Database
Dim rs As DAO.Recordset, rs2 As DAO.Recordset
Dim td As DAO.TableDef
Dim fd As DAO.Field
Dim maxWorkCenters As Integer
Dim i As Integer
Dim sql As String
Set db = CurrentDb
' Delete the old result table if there was one '
On Error Resume Next
db.TableDefs.Delete "result"
On Error GoTo 0
' Create the result table '
Set td = db.CreateTableDef("result")
td.Fields.Append td.CreateField("Plant", dbInteger)
td.Fields.Append td.CreateField("Material", dbText)
' Get the maximum number of workcenters we will need '
' for a given Plan/Material combination '
sql = "SELECT Count(*) FROM Temp GROUP BY Plant, Material"
Set rs = db.OpenRecordset(sql, dbOpenSnapshot)
maxWorkCenters = Nz(rs.Fields(0).Value, 0)
rs.Close
Set rs = Nothing
' Create as many columns as we need to fit all these combinations '
For i = 1 To maxWorkCenters
td.Fields.Append td.CreateField("WorkCenter" & i, dbText)
td.Fields.Append td.CreateField("SetupTime" & i, dbInteger)
Next i
db.TableDefs.Append td
' Now get the data into the new table '
Dim lastPlant As Variant, lastMaterial As Variant
Dim curcol As Integer
sql = "SELECT Plant, Material, Workcenter, Setuptime FROM Temp ORDER BY Plant, Material, WorkCenter"
Set rs = db.OpenRecordset(sql, dbOpenSnapshot)
Set rs2 = db.OpenRecordset("result", dbOpenDynaset)
With rs
lastPlant = 0
lastMaterial = ""
Do While Not .EOF
If (Nz(!Plant) <> lastPlant) Or (Nz(!Material) <> lastMaterial) Then
If rs2.EditMode = dbEditAdd Then
' Save the previously edited record if any '
rs2.Update
End If
' Different plant/material, so we add a new result '
rs2.AddNew
rs2!Plant = !Plant
rs2!Material = !Material
rs2!WorkCenter1 = !WorkCenter
rs2!SetupTime1 = !Setuptime
lastPlant = Nz(!Plant)
lastMaterial = Nz(!Material)
curcol = 1
Else
' Same plant/material combi, so we fill the next column set '
curcol = curcol + 1
rs2.Fields("Workcenter" & curcol).Value = !WorkCenter
rs2.Fields("SetupTime" & curcol).Value = !Setuptime
End If
.MoveNext
Loop
If rs2.EditMode = dbEditAdd Then
' Save the last result '
rs2.Update
End If
End With
Set rs2 = Nothing
Set rs = Nothing
Set db = Nothing
End Sub
```
**About the code**
* The `result` table is entirely re-created every time you run `ExpandTable`.
* The number of additional `WorkCenterX` and `SetupTimeX` columns adapts to the actual number of unique Plant/Material pairs.
* You'll have to modify code to suit your exact needs.
* You'll also have to clean it up a bit as some things could probably be expressed a bit better but you get the jest.
**Test database**
You can download a test Access 2000 database from <http://blog.nkadesign.com/wp-content/uploads/SO/SO547777.zip>.
Anyway, hope it does what you want or at least gets your closer. | Have you tried a Crosstab Query?
**EDIT**
(I grok better after reformatting your question)
You solution will almost work. But what you will get will have double entries (like this):
```
Plant Material Workcenter1 Setuptime1 Workcenter2 Setuptime2
1 Mat1 2 30 2 30
1 Mat1 2 30 3 30
1 Mat1 3 30 2 30
1 Mat1 3 30 3 30
1 Mat2 3 30 4 30
1 Mat2 3 30 3 30
1 Mat2 4 30 3 30
1 Mat2 4 30 4 30
2 Mat1 4 30 5 30
2 Mat1 4 30 4 30
2 Mat1 5 30 5 30
2 Mat1 5 30 4 30
```
And if you have more than two Work Centers then it gets even worse.
So what you want is a column indicator
```
Create table tmp
(
plant int,
material vchar(20),
workcenter int,
setuptime vchar(20),
myCol int
);
```
(btw., vchars won't work in ms-access/Jet... chars will though)
```
insert into tmp values( 1, mat1, 2, 30, 1);
insert into tmp values( 1, mat1, 3, 30, 2);
insert into tmp values( 1, mat2, 2, 30, 1);
insert into tmp values( 1, mat2, 3, 30, 2);
insert into tmp values( 2, mat1, 4, 30, 1);
insert into tmp values( 2, mat1, 5, 30, 2);
SELECT tmp.plant, tmp.material, tmp.workcenter, tmp.setuptime,
tmp_1.workcenter, tmp_1.setuptime
FROM tmp INNER JOIN tmp AS tmp_1 ON (tmp.material = tmp_1.material)
AND (tmp.plant = tmp_1.plant)
WHERE (((tmp.myCol)=1)
AND ((tmp_1.myCol)=2));
```
Of course if you can edit the original table, maybe you want to just add a second Workcenter and Setuptime column, | Convert rows to columns | [
"",
"sql",
"ms-access",
""
] |
I have the following example code:
```
class A(object):
def __init__(self, id):
self.myid = id
def foo(self, x):
print 'foo', self.myid*x
class B(A):
def __init__(self, id):
self.myid = id
self.mybid = id*2
def bar(self, x):
print 'bar', self.myid, self.mybid, x
```
When used, the following could be generated:
```
>>> a = A(2)
>>> a.foo(10)
foo 20
>>>
>>> b = B(3)
>>> b.foo(10)
foo 30
>>> b.bar(12)
bar 3 6 12
```
Now lets say I have some more subclasses `class C(A):` and `class D(A):`. I also know that the id will always fit in either B, C or D, but never in 2 of them at the same time.
Now I would like to call A(23) and get an object of the correct subclass. Something like this:
> ```
> >>> type(A(2))
> <class '__main__.B'>
> >>> type(A(22))
> <class '__main__.D'>
> >>> type(A(31))
> <class '__main__.C'>
> >>> type(A(12))
> <class '__main__.B'>
> ```
Is this impossible or is it possible but just bad design? How should problems like this be solved? | You should rather implement [Abstract Factory pattern](http://en.wikipedia.org/wiki/Abstract_factory_pattern), and your factory would then build any object you like, depending on provided parameters. That way your code will remain clean and extensible.
Any hack you could use to make it directly can be removed when you upgrade your interpreter version, since no one expects backwards compatibility to preserve such things.
EDIT: After a while I'm not sure if you should use Abstract Factory, or [Factory Method pattern](http://en.wikipedia.org/wiki/Factory_method_pattern). It depends on the details of your code, so suit your needs. | Generally it's not such a good idea when a superclass has any knowledge of the subclasses.
Think about what you want to do from an OO point of view.
The superclass is providing common behaviour for all objects of that type, e.g. Animal. Then the subclass provides the specialisation of the behaviour, e.g. Dog.
Think of it in terms of an "isa" relationship, i.e. a Dog is an Animal.
An Animal is a Dog doesn't really make sense.
HTH
cheers,
Rob | Can I instantiate a subclass object from the superclass | [
"",
"python",
"oop",
""
] |
My user is able to select multiple items in a `ListView` collection that is configured to show details (that is, a list of rows).
What I want to do is add a `Delete` button that will delete all of the selected items from the `ListViewItem` collection associated with the `ListView`.
The collection of selected items is available in `ListView.SelectedItems`, but `ListView.Items` doesn't appear to have a single method that lets me delete the entire range. I have to iterate through the range and delete them one by one, which will potentially modify a collection I'm iterating over.
So, what I'm basically after is the opposite of `AddRange()`. | If you have a collecion of your selectedItems, you can simply call remove on each of them instead of iterating over the ListView.
There is a method on ListViewItem called [Remove()](http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.remove.aspx).
```
ListView listview = <reference to ListView>;
foreach (ListViewItem item in listView.SelectedItems)
{
item.Remove();
}
```
This removes the iteration through all the items and only removes your selected items. | As far as I know, there is no way other than to delete them individually.
Wrap your deletion algorithm in `ListView.BeginUpdate()` and `ListView.EndUpdate()` calls. This way you won't get the slowdown of repainting on each delete.
Additionally, if you delete them in reverse order, I believe the underlying structure will have less to do.
Also, if the number of items you are deleting is a significant percentage of the total number of items, you might get more performance by clearing the list and `AddRange()`ing them back again. | What is the most efficient way to delete all selected items in a ListViewItem collection? | [
"",
"c#",
"winforms",
"listview",
""
] |
Anyone knows how to get sum of number?
For example i have mysql column name package.
```
Package
3
4
1
3
4
```
If package 3, the value should be usd 5, if package 4, value should be usd 10, if package 1, value should be usd 1 and so on.
So the total value above should be => 5 + 10 + 1 + 5 + 10 = 31
So how do i get sum of it in php?
i tried array\_sum .. but it gives me error, im not very expert in php.. Please help me
Thanking in advance. | Get the database to do the work:
```
select sum(CASE WHEN package = 3 THEN 5 ELSE 0 END)
+ sum(CASE WHEN package = 4 THEN 10 ELSE 0 END)
+ sum(CASE WHEN package = 1 THEN 1 ELSE 0 END) AS total
from table_name
```
The right way of doing it, if you've got more than a few values be to modify the table to contain the amount field so you can do:
```
select sum(amount) from table_name
```
Alternatively have another table that you contained the relationship between the values (package, amount), and then do
```
select sum(package_amount)
from table_name, lookup_values
where table_name.package = lookup_values.package
```
Or, if you really want to do it in PHP:
```
$amount = array(3=>5, 4=>10, 1=>1); // define the amount of each value
$result = mysql_query("SELECT id FROM table_name");
$sum = 0;
while ($row = mysql_fetch_assoc($result))
{
$sum += $amount[ $row['id'] ];
}
``` | You can do it in purely SQL like Richard did, the PHP version would be something like:
```
$result = mysql_query("SELECT `number` FROM `packages`");
while ($row = mysql_fetch_assoc($result))
{
$curr = $row['number'];
if ($curr == 3) $sum += 3;
if ($curr == 4) $sum += 10;
if ($curr == 1) $sum++;
}
```
This is assuming your database table is named 'packages' and the column that has the different package numbers is called 'number'. At the end of the loop you will be left with the sum in the $sum variable. Not sure if this is necessarily the most efficient way to do this in PHP. | sum value from mysql in php | [
"",
"php",
"mysql",
"sum",
""
] |
Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed? | The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.
Now, I'm *guessing* your question is why you should do this:
```
try
{
doSomething();
}
catch
{
catchSomething();
}
finally
{
alwaysDoThis();
}
```
When you can do this:
```
try
{
doSomething();
}
catch
{
catchSomething();
}
alwaysDoThis();
```
The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception. | Most advantages of using try-finally have already been pointed out, but I thought I'd add this one:
```
try
{
// Code here that might throw an exception...
if (arbitraryCondition)
{
return true;
}
// Code here that might throw an exception...
}
finally
{
// Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}
```
This behaviour makes it very useful in various situations, particularly when you need to perform cleanup (dispose resources), though a *using* block is often better in this case. | Why use finally in C#? | [
"",
"c#",
"exception",
""
] |
I'm developing an application where I the need to invoke a method of a generic class and I don't care about the instances actual type. Something like the following Java code:
```
public class Item<T>{
private T item;
public doSomething(){...}
}
...
public void processItems(Item<?>[] items){
for(Item<?> item : items)
item.doSomething();
}
```
At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it.
```
public interface IItem
{
void doSomething();
}
public class Item<T> : IItem {
private T item;
public void doSomething(){...}
}
...
public void processItems(IItem[] items)
{
foreach(IItem item in items)
item.doSomething();
}
```
This workaround works fine, but I'd like to know what is the correct way to achieve the same behavior.
**EDIT:**
I forgot to refer that the caller of `processItems` doesn't know the actual types. Actually the idea was that the array passed as argument to `processItems` could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way. | The normal way to do this would be to make the method generic:
```
public void ProcessItems<T>(Item<T>[] items) {
foreach(Item<T> item in items)
item.DoSomething();
}
```
Assuming the *caller* knows the type, type inference should mean that they don't have to explicitly specify it. For example:
```
Item<int> items = new Item<int>(); // And then populate...
processor.ProcessItems(items);
```
Having said that, creating a non-generic interface specifying the type-agnostic operations can be useful as well. It will very much depend on your exact use case. | I see that you only want to invoke some method with no parameters... there's already a contract for that: `Action`.
```
public void processItems(IEnumerable<Action> actions)
{
foreach(Action t in actions)
t();
}
```
Client:
```
List<Animal> zoo = GetZoo();
List<Action> thingsToDo = new List<Action>();
//
thingsToDo.AddRange(zoo
.OfType<Elephant>()
.Select<Elephant, Action>(e => e.Trumpet));
thingsToDo.AddRange(zoo
.OfType<Lion>()
.Select<Lion, Action>(l => l.Roar));
thingsToDo.AddRange(zoo
.OfType<Monkey>()
.Select<Monkey, Action>(m => m.ThrowPoo));
//
processItems(thingsToDo);
``` | What is the equivalent of Java wildcards in C# generics | [
"",
"c#",
"generics",
"wildcard",
""
] |
I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using Google AppEngine with Django Templates for presentation. | Thanks everyone for your help. I took many of your ideas and put them together, let me know what you think.
I added two methods to the class like this:
```
def hours(self):
retval = ""
if self.totalTime:
hoursfloat = self.totalTime.seconds / 3600
retval = round(hoursfloat)
return retval
def minutes(self):
retval = ""
if self.totalTime:
minutesfloat = self.totalTime.seconds / 60
hoursAsMinutes = self.hours() * 60
retval = round(minutesfloat - hoursAsMinutes)
return retval
```
In my django I used this (sum is the object and it is in a dictionary):
```
<td>{{ sum.0 }}</td>
<td>{{ sum.1.hours|stringformat:"d" }}:{{ sum.1.minutes|stringformat:"#02.0d" }}</td>
``` | You can just convert the timedelta to a string with `str()`. Here's an example:
```
import datetime
start = datetime.datetime(2009,2,10,14,00)
end = datetime.datetime(2009,2,10,16,00)
delta = end - start
print(str(delta))
# prints 2:00:00
``` | Format timedelta to string | [
"",
"python",
"string",
"datetime",
"format",
"timedelta",
""
] |
Do anyone know how to put Google adsense ads inside a GWT web application? | You can put the javascript-code from Adsense in the single HTML page that GWT starts with. This way the advertising will not be displayed in the same area as GTW but above/below the GWT code. For advertising that could be ok.
This example places a baner above the application:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>www.javaoracleblog.com</title>
<script type="text/javascript" language="javascript" src="com.javaoracleblog.aggregator.nocache.js"></script>
</head>
<body>
<script type="text/javascript"..
ADsense code here
</script>
<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
</body>
</html>
```
In order to indicate to Google WT that the site of Google adsense can be trusted you need to add a regex matching URL to the -whitelist command line argument.
Note that this will probably not solve the problems desribed in the above "Why I dumped GWT" article. | According to [this thread on AdSense](http://groups.google.com/group/adsense-help-troubleshooting/browse_thread/thread/632a7d4cf3d2e06/da4e75482cc5c027):
> Short version, you can't use Adsense
> via Ajax without breaking the
> programme policies/t&c's
>
> Long version...
>
> Ad code passed through an xmlhttp call
> is not rendered, it's just treated as
> text (hence, responseText). The only
> way to execute js code is to use
> "responseXML" coupled with the
> "exec()" command.
>
> For instance...
>
> If your xml contains something along
> the lines of:
>
> This is the
> content from the external
> file javascript code
> goes here
>
> You would assign a variable (called
> page\_data for instance) using
> ajax\_obj.responseXML, run the XML
> through a parser and run
>
> exec(js variable or line from XML
> here);
>
> Not really helpful from an Adsense
> standpoint, but that's how it's done.
It's also worth mentioning [Why I dumped GWT](http://www.onthoo.com/blog/programming/2008/02/why-i-dumped-gwt.html):
> Another problem were my adsense
> banners. Since I didn’t have a lot of
> content on the page, the banners were
> sometimes off topic. An even bigger
> problem was that the banners stayed
> the same when people searched for
> different keywords (since the ajax
> refresh didn’t trigger an adsense
> refresh). I solved this by doing the
> search with a page refresh instead of
> an ajax call. The ajax part of the
> site was limited to sorting, faceting,
> i18n and displaying tips. | How to put Google Adsense in GWT | [
"",
"java",
"gwt",
"adsense",
""
] |
I have a SQL query that takes a date parameter (if I were to throw it into a function) and I need to run it on every day of the last year.
How to generate a list of the last 365 days, so I can use straight-up SQL to do this?
Obviously generating a list 0..364 would work, too, since I could always:
```
SELECT SYSDATE - val FROM (...);
``` | There's no need to use extra large tables or ALL\_OBJECTS table:
```
SELECT TRUNC (SYSDATE - ROWNUM) dt
FROM DUAL CONNECT BY ROWNUM < 366
```
will do the trick. | Recently I had a similar problem and solved it with this easy query:
```
SELECT
(to_date(:p_to_date,'DD-MM-YYYY') - level + 1) AS day
FROM
dual
CONNECT BY LEVEL <= (to_date(:p_to_date,'DD-MM-YYYY') - to_date(:p_from_date,'DD-MM-YYYY') + 1);
```
Example
```
SELECT
(to_date('01-05-2015','DD-MM-YYYY') - level + 1) AS day
FROM
dual
CONNECT BY LEVEL <= (to_date('01-05-2015','DD-MM-YYYY') - to_date('01-04-2015','DD-MM-YYYY') + 1);
```
Result
```
01-05-2015 00:00:00
30-04-2015 00:00:00
29-04-2015 00:00:00
28-04-2015 00:00:00
27-04-2015 00:00:00
26-04-2015 00:00:00
25-04-2015 00:00:00
24-04-2015 00:00:00
23-04-2015 00:00:00
22-04-2015 00:00:00
21-04-2015 00:00:00
20-04-2015 00:00:00
19-04-2015 00:00:00
18-04-2015 00:00:00
17-04-2015 00:00:00
16-04-2015 00:00:00
15-04-2015 00:00:00
14-04-2015 00:00:00
13-04-2015 00:00:00
12-04-2015 00:00:00
11-04-2015 00:00:00
10-04-2015 00:00:00
09-04-2015 00:00:00
08-04-2015 00:00:00
07-04-2015 00:00:00
06-04-2015 00:00:00
05-04-2015 00:00:00
04-04-2015 00:00:00
03-04-2015 00:00:00
02-04-2015 00:00:00
01-04-2015 00:00:00
``` | Generate a range of dates using SQL | [
"",
"sql",
"oracle",
""
] |
I guess this could also be asked as to how long the created type name is attached to an anonymous type. Here's the issue:
A blog had something like this:
```
var anonymousMagic = new {test.UserName};
lblShowText.Text = lblShowText
.Text
.Format("{UserName}", test);
```
As sort of a wish list and a couple ways to go at it. Being bored and adventurous I took to creating an string extension method that could handle this:
```
var anonymousMagic = new {test.UserName, test.UserID};
lblShowText.Text = "{UserName} is user number {UserID}"
.FormatAdvanced(anonymousMagic);
```
With the idea that I would get the property info from the anonymous type and match that to the bracketted strings. Now with property info comes reflection, so I would want to save the property info the first time the type came through so that I wouldn't have to get it again. So I did something like this:
```
public static String FormatAdvanced(this String stringToFormat, Object source)
{
Dictionary<String, PropertyInfo> info;
Type test;
String typeName;
//
currentType = source.GetType();
typeName = currentType.Name;
//
//info list is a static list for the class holding this method
if (infoList == null)
{
infoList = new Dictionary<String, Dictionary<String, PropertyInfo>>();
}
//
if (infoList.ContainsKey(typeName))
{
info = infoList[typeName];
}
else
{
info = test.GetProperties()
.ToDictionary(item => item.Name);
infoList.Add(typeName, info);
}
//
foreach (var propertyInfoPair in info)
{
String currentKey;
String replacement;
replacement = propertyInfoPair.Value.GetValue(source, null).ToString();
currentKey = propertyInfoPair.Key;
if (stringToFormat.Contains("{" + currentKey + "}"))
{
stringToFormat = stringToFormat
.Replace("{" + currentKey + "}", replacement);
}
}
//
return stringToFormat;
}
```
Now in testing, it seems to keep the name it created for the anonymous type so that the second time through it doesn't get the property info off the type but off the dictionary.
If multiple people are hitting this method at the same time, is it pretty much going to work in a Session like fassion; IE the names of the types will be specific to each instance of the program? Or would it be even worse than that? At what point does that name get chucked and overwritten? | It never does. The type is generated at compile-time and you can consider it constant and unique throughout the life of the app-domain.
I question the value of this function though. The obvious first reason is because you don't have much of the functionality of the Format method on the String class (no escape for brackets, no formatting of values in the brackets, etc, etc).
The second is that it basically links the format string to the type being passed in, so they are not swapped out easily. If I had two classes which had the same conceptual value, but different properties naming it, I have to change my format string to display it with your method to compensate for the fact that the property name is embedded in the format string. | Anonymous types are generated at compile time, and so the reflection names should be static as long as you don't re-compile the assembly.
There is a detailed post [here](http://community.bartdesmet.net/blogs/bart/archive/2006/12/03/C_2300_-3.0-Feature-Focus-_2D00_-Part-1-_2D00_-Local-Type-Inference.aspx) that describes the names, but I believe what you are doing is safe. | How "safe" are Anonymous Types and Reflection together? | [
"",
"c#",
"reflection",
"anonymous-types",
""
] |
I am trying to serialize an Exception object in C#. However, it appears that it is impossible since the Exception class is not marked as [`[Serializable]`](https://msdn.microsoft.com/en-us/library/system.serializableattribute). Is there a way to work around that?
If something goes wrong during the execution of the application, I want to be informed with the exception that occurred.
My first reflex is to serialize it. | What I've done before is create a custom Error class. This encapsulates all the relevant information about an Exception and is XML serializable.
```
[Serializable]
public class Error
{
public DateTime TimeStamp { get; set; }
public string Message { get; set; }
public string StackTrace { get; set; }
public Error()
{
this.TimeStamp = DateTime.Now;
}
public Error(string Message) : this()
{
this.Message = Message;
}
public Error(System.Exception ex) : this(ex.Message)
{
this.StackTrace = ex.StackTrace;
}
public override string ToString()
{
return this.Message + this.StackTrace;
}
}
``` | Create a custom Exception class with the **[Serializable()]** attribute. Here's an example taken from the [MSDN](http://msdn.microsoft.com/en-us/library/ms173163.aspx):
```
[Serializable()]
public class InvalidDepartmentException : System.Exception
{
public InvalidDepartmentException() { }
public InvalidDepartmentException(string message) : base(message) { }
public InvalidDepartmentException(string message, System.Exception inner) : base(message, inner) { }
// Constructor needed for serialization
// when exception propagates from a remoting server to the client.
protected InvalidDepartmentException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
``` | How to serialize an Exception object in C#? | [
"",
"c#",
".net",
"exception",
"serialization",
""
] |
I'm setting up Fact and Dim tables and trying to figure out the best way to setup my time values. AdventureworksDW uses a timekey (UID) for each time entry in the DimTime table. I'm wondering there's any reason I shouldn't just use a time value instead i.e. 0106090800 (My granularity is hourly)? | "Intelligent keys" (in this case, a coded date and hour number) can lead to problems when you want to change definitions in your dimension. For example, your users might insist on a change from local time to UTC. Now your key is no longer actually a useful number, it's the old value in the dimension.
Further, with a midnight roll-over issue, the date part of your intelligent key might not match the actual date of the UTC vs. local time change.
To prevent the key from becoming a problem, you can't use it for any calculation of any kind. In which case, it's little better than a simple GUID or auto-increment number.
Auto-increment keys (or GUIDS) are fast and simple. Most important, they are trivially consistent across all dimensions.
Time happens to have a numeric mapping, but it helps to look at this is a weird coincidence, not a basis for a good design. | Here's Ralph Kimball's [latest](http://www.rkimball.com/html/designtipsPDF/KimballDT51LatestThinking.pdf) on time dimension. It's dated 2004, but it's still good.
[This one](http://www.ralphkimball.com/html/designtipsPDF/DesignTips2000%20/KimballDT5SurrogateKeys.pdf) will help, too. | Fact/Dim Table Time Value | [
"",
"sql",
"data-warehouse",
"multidimensional-array",
""
] |
Commonly when I look around the Internet, I find that people are generally using CSS hacks to make their website look the same in all browsers. Personally, I have found this to be quite time consuming to find all of these hacks and test them; each change you make you have to test in 4+ browsers to make sure it didn't break anything else.
About a year ago, I looked around the Internet for what other major sites are using (Yahoo, Google, BBC, etc) and found that most of them are doing some form of browser detection (JS, HTML if statements, server based). I have started doing this as well. On almost all of the sites I have worked on recently, I use jQuery, so I use the built in browser detection.
Is there a reason you use or don't use either of these? | The problem is that you only really get one shot at the css (since it is pretty much static content at the client)... you can't (easily) adapt it to suit on the fly at the client - so for those tricky incompatible cases (and there's too many of them), detection is sadly the best route. I can't see this changing very soon.
With javascript, you can often avoid much of this pain through libraries like (as you state) jQuery - and checking for *functionality* support rather than identifying the specific browser (most of the time). There are some cases you need to know exactly (the box model, for example). | There is a third option:
**Minimize or eliminate the need for browser detection and CSS hacks.**
I try to use things like jQuery plug-ins that take care of any browser differences for you (for widgets and the like). This doesn't take care of everything but it does a lot and has delegated the effort of supporting multiple browsers to someone who has spent and will spend far more effort on it than you can afford to or want to.
After that I follow these princples:
* Use what I call **minimal CSS**, meaning only use features that are widely supported;
* Use tables for complex layout if necessary. You may not like this but frankly to do things like side-by-side layout, tables will work on browsers going back a decade and will be a lot less effort than getting divs to work with combinations of absolute positioning, floating and the like;
* [**Force IE6 into strict rather than quirks mode by adding a DOCTYPE**](http://www.quirksmode.org/css/quirksmode.html). I can't stress how much easier this will make your life but oddly many people don't seem to do it still;
* Minimize [box model](http://css.maxdesign.com.au/listamatic/about-boxmodel.htm) issues by either using the correct DOCTYPE or using nested block elements rather than the other [box model hacks](http://css-discuss.incutio.com/?page=BoxModelHack); and
* If necessary include extra CSS files for relevant browsers. I tend to do this on the server rather than the client with generated pages (which, let's face it, is most of them). Many projects I've worked on have had IEfix.css files.
After that, I divide browsers into tiers:
Tier 1:
* Firefox 3;
* IE7.
My website **must** work on these.
Tier 2:
* Firefox 2;
* Safari;
* Opera;
* Chrome.
My website **should** work on these. This may offend some people but frankly the market share of these browsers is so low that they're simply not as important as Firefox 3 or IE7.
Tier 3:
* IE6;
* Others.
Minimal effort will be made to work on these unless it is, for example, a company requirement. IE6 is the nightmare one but it's [market share](http://www.w3schools.com/browsers/browsers_stats.asp) as of December was 20% and rapidly falling. Plus there are valid security concerns (on financial websites for example) for dissuading or even disallowing the use of IE6 such that sites like [Paypal have blocked IE6](http://www.hyperborea.org/journal/archives/2008/04/21/blocking-ie6/) and [Google tells users to drop IE6](http://tech.slashdot.org/article.pl?sid=09%2F01%2F01%2F145231&from=rss). | What is better: CSS hacks or browser detection? | [
"",
"javascript",
"css",
"browser-detection",
""
] |
I have been developing **ASP.Net** applications for quite a few years, and I have always avoided learning **JavaScript**. Now I have been diving in and trying to learn as much as possible.
As a **.Net** developer I rely on **Visual Studio** heavily. What I am wondering is what tools, as a **JavaScript** developer, do you guys rely on heavily to develop **JavaScript**? I have just discovered **FireBug** which is awesome. What other tools out there am I missing that are a **must have**?
Thanks! | Yes, Firebug is awesome. Be sure that you are aware of the [profiling](http://getfirebug.com/js.html) capabilities in there. Also, there is a new testing framework called [FireUnit](http://fireunit.org/) that works with Firebug as well.
I like [Textmate](http://macromates.com/) for Javascript editing on my Mac. [Aptana Studio](http://www.aptana.com/) (stand-alone or as an [Eclipse](http://www.eclipse.org) plug-in) is really good too.
I've been meaning to try test-driven-development in Javascript with the [YUI test library](http://developer.yahoo.com/yui/yuitest/). It promises to be like NUnit/JUnit for Javascript, which would be great.
Check out [JS lint](http://www.jslint.com/).
If you're interested in Aspect-oriented Programming, look at AOP in Javascript from [Dojo](http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/).
Lastly, for some good information about the current state of Javascript engines (cool stuff like [TraceMonkey](https://wiki.mozilla.org/JavaScript:TraceMonkey)) and future directions, check out this episode of [HanselMinutes](http://www.hanselminutes.com/default.aspx?showID=148).
Enjoy! | Firebug is pretty much the best. You'll need some solutions for IE too.
See this link: [Debugging JavaScript in IE7](https://stackoverflow.com/questions/361635/debugging-javascript-in-ie7) | What tools should I have as my core set for developing javascript? | [
"",
"javascript",
""
] |
... and thanks for reading...
I'm still learning the ropes so please be forgiving... ;-)
I am writing a function that meshes a solid in space. The mesh is done by using objects of a "Node" class and each node is represented by:
```
int id
double p
double r
```
Initially I thought that a map would be the way to go: with a map I can make the association between the "id" key and the second key (a pointer to the node object).
Something like this:
```
int nodeId;
Node *node;
std::map<int, Node *> NodeMap;
```
Then, when I create the nodes I just call the "new" operator. E.g in a for loop I do something like this:
```
node = new Node(i); // the node constructor sets the id to the value of i.
```
and I add the new node to the map:
```
NodeMap[i] = node;
```
But.... I realized that I will need to do a lookup in the map not by first key (the id) but by the p and r parameters (the coordinates of the node).
In other words I will need something that returns the node id given the values of p and r.
A map is a perfect container if the lookup is done using the integer first key (id).
Does anyone have a suggestion on how to solve this particular problem?
Thanks much!
AsvP. | A map<> won't work. C++ associative containers work on the basis of key equality, and comparing floating-point numbers for equality doesn't work at all well.
It sounds like you need to find a node, given x and y. The best way will depend on what you're trying to accomplish. Are you trying to find the nearest node, given the coordinates, or are you going to calculate coordinates that are very close to a node, and then you need to find the node?
For the second, you'll probably be well off sorting the nodes on either the x or y coordinate (I'll assume the x), and doing a binary search to find which nodes have x coordinates very close to your given x. That will generally select a small number of nodes, which can be searched for the approximately correct y.
(Of course, if the nodes are in some sort of predictable grid, you should be able to provide some means to calculate directly, like round x and y to nearest integer if you've got integral lattice points.)
If you need to find the closest node, well, that gets a bit complicated. I don't know enough about this to help much, but there are resources for geometric algorithms. | As with any "what should I use to represent this structure" question it does really depend on **how you want to interact with it**
Scene graphs are common in 3D libraries, they provide a tree based traversal over the nodes, often allowing the transforms, interactions and other attributes to cascade down the tree.
For something to hold objects to be rendered a common structure is a [Binary space Partitioning Tree](http://en.wikipedia.org/wiki/Binary_space_partitioning) which allows efficient culling of objects which are definitely not visible or occluded by others.
Edit;
I missed that you were indexing by floating point. This is normally a bad idea (since the exactness required in most standard maps will causes issues relating to the instability of floating point behaviour). Unless you **really** want this behaviour
In this case you need to have some way of handling it such as:
* chunking your domain so that you can accurately point at a small section of it and prevent more than one node occupying the same chunk of space.
* Have some way of bucketing your space (possibly requiring adaptive subdivision of areas with higher concentrations of nodes) so that when asking for the point p,r you are given a (possibly empty) set of nodes present in that region. | What is the best data structure for representing nodes in 3D space? | [
"",
"c++",
"data-structures",
"stl",
"dictionary",
""
] |
I'm writing a program as follows:
* Find all files with the correct extension in a given directory
* Foreach, find all occurrences of a given string in those files
* Print each line
I'd like to write this in a functional way, as a series of generator functions (things that call `yield return` and only return one item at a time lazily-loaded), so my code would read like this:
```
IEnumerable<string> allFiles = GetAllFiles();
IEnumerable<string> matchingFiles = GetMatches( "*.txt", allFiles );
IEnumerable<string> contents = GetFileContents( matchingFiles );
IEnumerable<string> matchingLines = GetMatchingLines( contents );
foreach( var lineText in matchingLines )
Console.WriteLine( "Found: " + lineText );
```
This is all fine, but what I'd also like to do is print some statistics at the end. Something like this:
```
Found 233 matches in 150 matching files. Scanned 3,297 total files in 5.72s
```
The problem is, writing the code in a 'pure functional' style like above, each item is lazily loaded.
You only know how many files match in total until the final foreach loop completes, and because only one item is ever `yield`ed at a time, the code doesn't have any place to keep track of how many things it's found previously. If you invoke LINQ's `matchingLines.Count()` method, it will re-enumerate the collection!
I can think of many ways to solve this problem, but all of them seem to be somewhat ugly. It strikes me as something that people are bound to have done before, and I'm sure there'll be a nice design pattern which shows a best practice way of doing this.
Any ideas? Cheers | In a similar vein to other answers, but taking a slightly more generic approach ...
... why not create a *Decorator* class that can wrap an existing IEnumerable implementation and calculate the statistic as it passes other items through.
Here's a `Counter` class I just threw together - but you could create variations for other kinds of aggregation too.
```
public class Counter<T> : IEnumerable<T>
{
public int Count { get; private set; }
public Counter(IEnumerable<T> source)
{
mSource = source;
Count = 0;
}
public IEnumerator<T> GetEnumerator()
{
foreach (var T in mSource)
{
Count++;
yield return T;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var T in mSource)
{
Count++;
yield return T;
}
}
private IEnumerable<T> mSource;
}
```
You could create three instances of `Counter`:
1. One to wrap `GetAllFiles()` counting the total number of files;
2. One to wrap `GetMatches()` counting the number of matching files; and
3. One to wrap `GetMatchingLines()` counting the number of matching lines.
The key with this approach is that you're not layering multiple responsibilities onto your existing classes/methods - the `GetMatchingLines()` method only handles the matching, you're not asking it to track stats as well.
**Clarification** in response to a comment by `Mitcham`:
The final code would look something like this:
```
var files = new Counter<string>( GetAllFiles());
var matchingFiles = new Counter<string>(GetMatches( "*.txt", files ));
var contents = GetFileContents( matchingFiles );
var linesFound = new Counter<string>(GetMatchingLines( contents ));
foreach( var lineText in linesFound )
Console.WriteLine( "Found: " + lineText );
string message
= String.Format(
"Found {0} matches in {1} matching files. Scanned {2} files",
linesFound.Count,
matchingFiles.Count,
files.Count);
Console.WriteLine(message);
```
Note that this is still a functional approach - the variables used are **immutable** (more like *bindings* than variables), and the overall function has no side-effects. | I would say that you need to encapsulate the process into a 'Matcher' class in which your methods capture statistics as they progress.
```
public class Matcher
{
private int totalFileCount;
private int matchedCount;
private DateTime start;
private int lineCount;
private DateTime stop;
public IEnumerable<string> Match()
{
return GetMatchedFiles();
System.Console.WriteLine(string.Format(
"Found {0} matches in {1} matching files." +
" {2} total files scanned in {3}.",
lineCount, matchedCount,
totalFileCount, (stop-start).ToString());
}
private IEnumerable<File> GetMatchedFiles(string pattern)
{
foreach(File file in SomeFileRetrievalMethod())
{
totalFileCount++;
if (MatchPattern(pattern,file.FileName))
{
matchedCount++;
yield return file;
}
}
}
}
```
I'll stop there since I'm supposed to be coding work stuff, but the general idea is there. The entire point of 'pure' functional program is to not have side effects, and this type of statics calculation is a side effect. | Design pattern for aggregating lazy lists | [
"",
"c#",
".net",
"ienumerable",
"lazy-loading",
"generator",
""
] |
I have a stored procedure that returns an object as XML. How do I handle the case where the object doesn't exist?
I can't return null or empty string as the XmlReader complains that it is not valid XML.
If I return an empty Tag, how do I tell if it is just an empty object or no object? | Well, a common approach is some marker attribute, such as `xsi:nil="true"` (although this is just an example). | The two ways that I've seen are:
1. Include an attribute to indicate whether the item is null or not (isnull="true|false"). Generally, false is assumed if the attribute is not included.
2. Don't include the element for that node. If it doesn't exist in the xml it's null. If it does exist and is empty, it's just an empty string. This, of course, relies on your parsing code being able to determine what elements should exist (via either a schema or information earlier in the xml file, generally).
The first option is generally easier to deal with, but results in more text. The second can result in a smaller xml file. | How to handle null objects in XML coming from SQL Server? | [
"",
"c#",
"sql-server",
"xml",
""
] |
I have been trying to access a .NET Assembly that I have created in classic ASP using
```
dim foo
set foo = Server.CreateObject("TestAssembly.MyClass")
```
The problem is I'm getting an error:
```
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
/test.asp, line 4
Invalid class string
```
I have registered the assembly (TestAssembly.dll) using gacutil and regasm as instructed in the article: [Replacing Old Classic ASP COM Components with .NET Assemblies](http://blog.danbartels.com/articles/322.aspx) which I referenced from [another question](https://stackoverflow.com/questions/95724/what-is-the-easiest-way-to-convert-from-asp-classic-to-asp-net/104187#104187). It supplies two methods in which to install the assembly and I have tried both, but to no avail.
Getting this working would be great because it would allow me to gradually migrate a classic ASP site to .NET | Another thing to check: make sure your .Net assembly is set to be COM Visible. | Check in the registry here: \*HKLM\SOFTWARE\Classes\* and see if the namespace.class is there (e.g. "TestAssembly.MyClass") and that it has a key called "CLSID" with a valid ID.
If the registry entry isn't there then make sure that **Project > Properties > Assembly Information** has "**Make assembly COM-Visible**", then recompile.
Once compiled, run regasm (if you're on a 64bit machine they you will have to explicitly reference the 64bit version of regasm - **c:\Windows\microsoft.net\framework64\v4.0.30319\regasm**) with:
```
regasm /codebase /tlb TestAssembly.dll
``` | Accessing a .NET Assembly from classic ASP | [
"",
"c#",
".net",
"asp-classic",
"assemblies",
""
] |
I'm not a Java developer so I might get some terms wrong... but.
An application I integrate with is moving from Spring to Wicket. While it should not affect my integration with it I got to wondering why they would do this?
From what I know Spring is the more popular framework. I know nothing about it except it's popular. I did read the Wicket page and Wicket seems really simple and straightforward.
What are some of the advantages of Wicket?
It seems to me that changing your entire framework would be some work so I wonder if Wicket offers something that Spring does not? | Advantages that often get touted in circles I frequent are:
1. Your html can be fully xhtml compliant - there is a VERY nice separation of presentation and logic in that the only thing your presentation/html layer needs to know about wicket are wicketid attributes in standard html tags. This is wonderful for the html/css/javascript client side guy on your team who does little to no actual java work. No other java based web framework can claim this, afaik.
2. No xml config for anything wicket specific - everything can be done in source and very little needs to be done to the standard web.xml for your .war
3. component based development is pretty easy to grok - especially if you have a non web background (e.g. a swing programmer). it encourages reuse quite a bit more than mvc does, imo. | Here are some features of apache wicket:
**POJO Component Model**
Pages and Components in Wicket are real Java objects that support encapsulation, inheritance and events.
**Ease of Development**
Because Wicket is Java and HTML, you can leverage what you know about Java or your favorite HTML editor to write Wicket applications.
**Separation of Concerns**
Wicket does not mix markup with Java code and adds no special syntax to your markup files. The worlds of HTML and Java are parallel and associated only by Wicket ids, which are attributes in HTML and Component properties in Java. Since Wicket HTML is just HTML and Wicket Java is just Java, coders and designers can work independently to a large degree and without relying on any special tools.
**Secure**
Wicket is secure by default. URLs do not expose sensitive information and all component paths are session-relative. Explicit steps must be taken to share information between sessions. Furthermore URL encryption allows highly secure web sites.
**Transparent, Scalable Clustering Support**
All Wicket applications will work on a cluster automatically and without additional work. Once bottlenecks are understood, Wicket enables tuning of page state replication. The next version of Wicket will support client-side models for zero-state scalability.
**Transparent Back Button Support**
Wicket supports configurable page version management. When users submit a form or follow a link from a page they accessed with the back button in their browser, Wicket is able to revert the page object to the state it was in when the page was originally rendered. This means you can write web applications that support the back button with very little work.
**Multi-tab and multi-window support**
Wicket provides an easy way to write application that supports multi-window and multi-tab usage allowing developer to react properly when users open new browser window or tab
**Reusable Components**
Reusable components in Wicket are particularly easy to create. Not only can you extend existing components with the Java extends keyword, but you can also create Panel components which associate a group of components as a reusable unit.
**Simple, Flexible, Localizable Form Validation**
It is trivial to write and use validators in Wicket. It is also quite easy to customize and localize the display and content of validation error messages.
**Typesafe Sessions**
Wicket eliminates the need to manage HttpSession attributes by hand. Page and component objects are transparently stored in the session and your application can create a custom session subclass with typesafe properties as well. All objects stored in the session can automatically participate in clustering replication.
**Factory Customizable**
Wicket is very extensible. Most operations are customizable through factories or factory methods.
**Detachable Models**
Model objects in Wicket can be very lightweight in terms of memory and network use in a cluster. When a model is used, it can “attach”, populating itself with information from persistent storage. When the model is no longer in use, transient information can be reset, reducing the size of the object.
**Border Components**
Wicket Border components enable the decoration of pages in a reusable fashion. This is especially useful for inheritance of common navigational structures or layout.
**Support for All Basic HTML Features**
Wicket supports image tags, links, forms and everything else that you’re used to using in your web application development.
**Programmatic Manipulation of Attributes**
Wicket Components can programmatically change any HTML tag attribute.
**Automatic Conversions**
Once a Form validates, the model can be updated using Wicket converters. Most ordinary conversions are built-in and it is easy to write new converters.
**Dynamic Images**
Wicket makes image use, sharing and generation very easy. Dynamic images can be created by simply implementing a paint method.
**Pageable ListView**
ListViews in Wicket are extremely powerful. You can nest any kind of component in a ListView row, even other ListViews. PageableListView supports navigation links for the large lists.
**Tree Component**
Out of the box tree component for navigating and selecting nodes.
**Localization**
HTML pages, images and resource strings can all be localized. | What are the advantages of Apache Wicket? | [
"",
"java",
"model-view-controller",
"spring",
"wicket",
""
] |
I have a table with a row that looks like this:
(**20091231**48498429, '...', '...')
The first part, id, is a timestamp followed by a random number. (needed to work with other parts in the system) The data already exists in the table.
I want to create a column, timestamp, and extract just the date (20091231) and update all the rows with the timestamp.
1. How can I do this for all the rows with SQL? (i.e. update them all with some sort of a function?)
2. What kind of default value should I assign the column to make sure that future inserts correctly extract the date?
**UPDATE** - Please read the comments by bobince in the first answered question by Jonathan Sampson on how we got to the answer. This is the final query that worked:
```
UPDATE table SET rdate=substring(convert(rid,char(20)),1,8);
```
The problem was that I was using `substring` as `substring( str, 0, 8 )` whereas it should be `substring( str, 1, 8 )`. I guess we're all used to 0 as the beginning position! More info here on [substring](http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substring "substring @ mysql")
Related to: [multiple updates in mysql](https://stackoverflow.com/questions/3432/multiple-updates-in-mysql "multiple updates in my mysql") | ```
SELECT SUBSTRING(colDate,0,8) as 'date'
FROM someTable
```
Or am I mistaken?
```
UPDATE someTable
SET newDateField = SUBSTRING(colDate,0,8)
```
Would likely work too. Untested. | Use a sub-select in your update (untested, and I've been using Firebird for too long, so someone check me here).
```
UPDATE MyTable AS TUpdate
SET MyNewField = (SELECT SUBSTRING(TSub.MyDateColumn,0,8)
FROM MyTable AS TSub
WHERE TSub.MyID = TUpdate.MyID);
```
As for future inserts correctly extracting the date, you're going to have to create a trigger on insert to extract the date for that record. | Updating multiple rows with a value calculated from another column | [
"",
"sql",
"mysql",
""
] |
I've been thinking about the web app I'm about to begin developing and wondering whether my usual approach could be improved.
In my last few apps I've created a table (see below) of roles (such as `CREATE POST`, `EDIT POST` etc.) which each have a bitfield applied to them so I can simply assign a user certain rights in registration and check them later on (e.g. `$user->hasRight(CREATE_POST)`).
I'm wondering if there's a better approach to this. It's certainly confusing when the rights aren't specifically linked to the user (I could have a table where each right is a boolean column but that only sounds like a small improvement) - and what happens if I change some around?
I'm not looking to use standard libraries (the app itself is a learning experience for me: using postgresql, git etc.) although I'm perfectly happy to take inspiration from them to construct my own - so if there's something special you think I should take a look at please say so :) | That's basically the same approach I take in my own web apps (and a bit of trial and error has gone into that for me). The only difference is, I'd probably use a table which has the different permissions as columns, so that if you want to add more permissions later on, you can. Using bits in an integer limits you to a fixed number of permissions, namely as many bits as there are in the integer. Typically that would be 32 which I suppose is probably enough, but I prefer not to limit myself that way.
For what it's worth, that's also the model that phpBB uses (permissions as table columns), and if it's good enough for arguably the most popular PHP web app, it's probably good enough for you ;-) | You could take a look at the documentation of Spring Security (formerly Acegi), which is a widely used Java ACL framework.
The documentation is exhaustive and also describes the various considerations made in the design of bot authentication and authorization. Even without using Java it is worthy reading.
You can view the [index page](http://static.springframework.org/spring-security/site/reference/html/springsecurity.html) to get an overview and an impression of what Acegi does (and does not) do. You can also skip right to the [authorization concepts](http://static.springframework.org/spring-security/site/reference/html/authorization-common.html "authorization concepts") or even to the [database schema](http://static.springframework.org/spring-security/site/reference/html/appendix-schema.html "database schema"). | How should I be implementing my ACL in a web application? | [
"",
"php",
"acl",
"access-control",
"rights-management",
""
] |
I got an anonymous type inside a List anBook:
```
var anBook=new []{
new {Code=10, Book ="Harry Potter"},
new {Code=11, Book="James Bond"}
};
```
Is to possible to convert it to a List with the following definition of clearBook:
```
public class ClearBook
{
int Code;
string Book;
}
```
by using direct conversion, i.e., without looping through anBook? | Well, you could use:
```
var list = anBook.Select(x => new ClearBook {
Code = x.Code, Book = x.Book}).ToList();
```
but no, there is no direct conversion support. Obviously you'll need to add accessors, etc. (don't make the fields public) - I'd guess:
```
public int Code { get; set; }
public string Book { get; set; }
```
Of course, the other option is to start with the data how you want it:
```
var list = new List<ClearBook> {
new ClearBook { Code=10, Book="Harry Potter" },
new ClearBook { Code=11, Book="James Bond" }
};
```
There are also things you could do to map the data with reflection (perhaps using an `Expression` to compile and cache the strategy), but it probably isn't worth it. | As Marc says, it can be done with reflection and expression trees... and as luck would have it, there's a class in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) which does exactly that. However, looking at your question more closely it sounds like you want to apply this conversion to a collection (array, list or whatever) *without looping*. That can't possibly work. You're converting from one type to another - it's not like you can use a reference to the anonymous type as if it's a reference to ClearBook.
To give an example of how the PropertyCopy class works though, you'd just need:
```
var books = anBook.Select(book => PropertyCopy<ClearBook>.CopyFrom(book))
.ToList();
``` | Convert anonymous type to class | [
"",
"c#",
"linq",
"anonymous-types",
""
] |
I have 2 related database tables which in simplified form look like this
```
Product(
product_id,
name
)
ProductSpecs(
spec_id,
product_id,
name,
value
)
```
Foreign key is set via product\_id field and ProductSpecs table has a unique constraint on (product\_id, name) pair.
Now in my ASP.NET MVC application when user edits product specs and saves the data I delete old specs and insert all as new ones.
I do this by first calling DataContext.DeleteAllOnSubmit() and providing current (old) ProductSpecs as a parameter, and then I add new specs to the Product.ProductSpecs collection.
Then I call DataContext.SubmitChanges() and get an error that my unique constraint was violated.
By looking at the SQL statements returned by DataContenxt.GetChangeText() I can see that INSERTs are executed before DELETEs (even though I called DeleteAllOnSubmit() before Add).
What is the reason of this behavior and how to fix or workaround it?
Thanks. | Yes, for some reason, Linq to SQL perform all deletes as the last thing. And there is no way to change that.
Or maybe there is. I haven't looked into the codegen DataContext to see if we can override something there.
You can call SubmitChanges() as many times you want. My workaround when I need to delete as the first thing, is mark my deletions, call SubmitChanges(), then perform inserts and updates, and call SubmitChanges once again.
You can wrap everything inside of a TransactionScope:
```
var deletables =
from toDelete in db.NamedValues
where toDelete.Name == knownValue.Name
select toDelete;
using (var scope = new TransactionScope())
{
db.NamedValues.DeleteAllOnSubmit(deletables);
db.SubmitChanges();
db.NamedValues.InsertOnSubmit(knownValue);
db.SubmitChanges();
scope.Complete();
}
``` | A better solution that does not require knowing in advance what entities have changed is to use the DataContext's partial methods to intercept the inserts and push the deletes through first.
```
public partial class YourDataContext
{
List<EntityX> _deletedEntities = new List<EntityX>();
partial void InsertEntityX(EntityX instance)
{
// Run deletes before inserts so that we don't run into any index violations
var deletes =
this.GetChangeSet().Deletes
.Where(d => d.GetType().Equals(instance.GetType()))
.Cast<EntityX>().ToList();
var replaced = deletes.SingleOrDefault(d => d.UniqueKeyId == instance.UniqueKeyId);
if (replaced != null)
{
DeleteEntityX(replaced);
_deletedEntities.Add(replaced);
}
this.ExecuteDynamicInsert(instance);
}
partial void DeleteEntityX(EntityX instance)
{
if (_deletedEntities.Contains(instance))
{
_deletedEntities.Remove(instance);
return;
}
this.ExecuteDynamicDelete(instance);
}
}
``` | Linq to SQL: execution order when calling SubmitChanges() | [
"",
".net",
"sql",
"linq",
"linq-to-sql",
""
] |
This questions is prompted by [strange HashMap.put() behaviour](https://stackoverflow.com/questions/444638/strange-hashmap-put-behaviour#444757)
I think I understand why `Map<K,V>.put` takes a `K` but `Map<K,V>.get` takes an `Object`, it seems not doing so will break too much existing code.
Now we get into a very error-prone scenario:
```
java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>();
m.put(5L,"Five"); // compiler barfs on m.put(5, "Five")
m.contains(5); // no complains from compiler, but returns false
```
Couldn't this have been solved by returning true if the `Long` value was withing `int` range and the values are equal? | Here is the source from Long.java
```
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
```
I.e. it needs to be a Long type to be equal. I think the key difference between:
```
long l = 42L
int i = 42;
l == i
```
and your example above is that with primitives an implicit widening of the int value can occur, however with object types there are no rules for implicitly converting from Integer to a Long.
Also check out [Java Puzzlers](http://www.javapuzzlers.com/), it has a lot of examples similar to this. | Generally speaking, although it is not strictly expressed in the contract for [equals()](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)), objects should not consider themselves equal to another object that is not of the exact same class (even if it is a subclass). Consider the symmetric property - if a.equals(b) is true, then b.equals(a) must also be true.
Let's have two objects, `foo` of class `Super`, and `bar` of class `Sub`, which extends `Super`. Now consider the implementation of `equals()` in Super, specifically when it's called as `foo.equals(bar)`. Foo only knows that bar is strongly typed as an `Object`, so to get an accurate comparison it needs to check it's an instance of Super and if not return false. It is, so this part is fine. It now compares all the instance fields, etc. (or whatever the actual comparison implementation is), and finds them equal. So far, so good.
However, by the contract it can only return true if it know that bar.equals(foo) is going to return true as well. Since bar can be any subclass of Super, it's not clear whether the equals() method is going to be overridden (and if probably will be). Thus to be sure that your implementation is correct, you need to write it symmetrically and ensure that the two objects are the same class.
More fundamentally, objects of different classes cannot really be considered equal - since in this case, only one of them can be inserted into a `HashSet<Sub>`, for example. | Why is Long.valueOf(0).equals(Integer.valueOf(0)) false? | [
"",
"java",
"equals",
""
] |
I have a form served in non-UTF-8 (it’s actually in Windows-1251). People, of course, post there any characters they like to. The browser helpfully converts the unpresentable-in-Windows-1251 characters to html entities so I can still recognise them. For example, if user types an →, I receive an `→`. That’s partially great, like, if I just echo it back, the browser will correctly display the → no matter what.
The problem is, I actually do a htmlspecialchars () on the text before displaying it (it’s a PHP function to convert special characters to HTML entities, e.g. & becomes `&`). My users sometimes type things like `—` or `©`, and I want to display them as actual `—` or `©`, not — and ©.
There’s no way for me to distinguish an → from `→`, because I get them both as `→`. And, since I htmlspecialchars () the text, *and* I also get a `→` for a → from browser, I echo back an `&#8594;` which gets displayed as `→` in a browser. So the user’s input gets corrupted.
Is there a way to say: “Okay, I serve this form in Windows-1251, but will *you* please just send me the input in UTF-8 and let me deal with it myself”?
Oh, I know that the good idea is to switch the whole software to UTF-8, but that is just too much work, and I would be happy to get a quick fix for this. If this matters, the form’s enctype is "multipart/form-data" (includes file uploader, so cannot use any other enctype). I use Apache and PHP.
Thanks! | > The browser helpfully converts the unpresentable-in-Windows-1251 characters to html entities
Well, nearly, except that it's not at all helpful. Now you can't tell the difference between a real “ƛ” that someone typed expecting it to come out as a string of text with a ‘&’ in it, and a ‘Б’ character.
> I actually do a htmlspecialchars () on the text before displaying it
Yes. You must do that, or else you've got a security problem.
> Okay, I serve this form in Windows-1251, but will you please just send me the input in UTF-8 and let me deal with it myself
Yeah, supposedly you send “accept-charset="UTF-8"” in the form tag. But the reality is that doesn't work in IE. To get a form in UTF-8, you must send a form (page) in UTF-8.
> I know that the good idea is to switch the whole software to UTF-8,
Yup. Well, at least the encoding of the page containing the form should be UTF-8. | ```
<form action="action.php" method="get" accept-charset="UTF-8">
<!-- some elements -->
</form>
```
All browsers should return the values in the encoding specified in `accept-charset`. | Get non-UTF-8-form fields as UTF-8 in PHP? | [
"",
"php",
"html",
"utf-8",
"webforms",
""
] |
When writing xml documentation you can use `<see cref="something">something</see>`, which works of course. But how do you reference a class or a method with generic types?
```
public class FancyClass<T>
{
public string FancyMethod<K>(T value) { return "something fancy"; }
}
```
If I was going to write xml documentation somewhere, how would I reference the fancy class? how can I reference a `FancyClass<string>`? What about the method?
For example in a different class I wanted to let the user know that I will return an instance of `FancyClass<int>`. How could I make a see cref thing for that? | To reference the method:
```
/// <see cref="FancyClass{T}.FancyMethod{K}(T)"/> for more information.
``` | # TL;DR:
> *"How would I reference `FancyClass<T>`?"*
```
/// <see cref="FancyClass{T}"/>
```
> *"What about `FancyClass<T>.FancyMethod<K>(T value)`?"*
```
/// <see cref="FancyClass{T}.FancyMethod{K}(T)"/>
```
> *"How can I reference a `FancyClass<string>`?"*
```
/// <see cref="SomeType.SomeMethod(FancyClass{string})"/>
/// <see cref="FancyClass{T}"/> whose generic type argument is <see cref="string"/>
```
While you *can* reference a method whose signature includes `FancyClass<string>` (e.g. as a parameter type), you *cannot* reference such a closed generic type directly. The second example works around that limitation. (This is seen e.g. on the [MSDN refence page for the static `System.String.Concat(IEnumerable<string>)` method](https://msdn.microsoft.com/en-us/library/dd784338(v=vs.110).aspx)). :
# XML documentation comment `cref` rules:
* **Surround the generic type parameter list with curly braces `{}`** instead of with `<>` angle brackets. This spares you from escaping the latter as `<` and `>` — remember, documentation comments are XML!
* **If you include a prefix (such as `T:`** for types, `M:` for methods, `P:` for properties, `F:` for fields), the compiler will not perform any validation of the reference, but simply copy the `cref` attribute value straight to the documentation XML output. For this reason, you'll have to use the special ["ID string" syntax](https://msdn.microsoft.com/en-us/library/fsbx0t7x.aspx "MSDN reference page on XML documentation comment ID strings") that applies in such files: always use fully-qualified identifiers, and use backticks to reference generic type parameters (`` `n `` on types, ``` ``n ``` on methods).
* **If you omit the prefix**, regular language naming rules apply: you can drop namespaces for which there's a `using` statement, and you can use the language's type keywords such as `int` instead of `System.Int32`. Also, the compiler will check the reference for correctness.
# XML documentation comment `cref` cheat sheet:
```
namespace X
{
using System;
/// <see cref="I1"/> (or <see cref="X.I1"/> from outside X)
/// <see cref="T:X.I1"/>
interface I1
{
/// <see cref="I1.M1(int)"/> (or <see cref="M1(int)"/> from inside I1)
/// <see cref="M:X.I1.M1(System.Int32)"/>
void M1(int p);
/// <see cref="I1.M2{U}(U)"/>
/// <see cref="M:X.I1.M2``1(``0)"/>
void M2<U>(U p);
/// <see cref="I1.M3(Action{string})"/>
/// <see cref="M:X.I1.M3(System.Action{System.String})"/>
void M3(Action<string> p);
}
/// <see cref="I2{T}"/>
/// <see cref="T:X.I2`1"/>
interface I2<T>
{
/// <see cref="I2{T}.M1(int)"/>
/// <see cref="M:X.I2`1.M1(System.Int32)"/>
void M1(int p);
/// <see cref="I2{T}.M2(T)"/>
/// <see cref="M:X.I2`1.M2(`0)"/>
void M2(T p);
/// <see cref="I2{T}.M3{U}(U)"/>
/// <see cref="M:X.I2`1.M3``1(``0)"/>
void M3<U>(U p);
}
}
``` | How to reference generic classes and methods in xml documentation | [
"",
"c#",
"generics",
"reference",
"xml-documentation",
""
] |
I have a c# DateTime object and I need to increment it by one month.
example:
```
input output
-------------------------------
Jan 12, 2005 Feb 12, 2005
Feb 28, 2009 Mar 28, 2009
Dec 31, 2009 Jan 31, 2010
Jan 29, 2000 Feb 29, 2000
Jan 29, 2100 Error: no Feb 29, 2100
```
What is the best way to do this.
My first thought (aside from some built in code) was to construct a new DateTime from pieces and handle the roll to the year myself | Here's a complete program showing the examples given in the question. You'd probably want to use an exception in OneMonthAfter if it really shouldn't be called that way.
```
using System;
using System.Net;
public class Test
{
static void Main(string[] args)
{
Check(new DateTime(2005, 1, 12));
Check(new DateTime(2009, 2, 28));
Check(new DateTime(2009, 12, 31));
Check(new DateTime(2000, 1, 29));
Check(new DateTime(2100, 1, 29));
}
static void Check(DateTime date)
{
DateTime? next = OneMonthAfter(date);
Console.WriteLine("{0} {1}", date,
next == null ? (object) "Error" : next);
}
static DateTime? OneMonthAfter(DateTime date)
{
DateTime ret = date.AddMonths(1);
if (ret.Day != date.Day)
{
// Or throw an exception
return null;
}
return ret;
}
}
``` | ```
using System;
public static class Test
{
public static void Main()
{
string[] dates = { "Jan 12, 2005", "Feb 28, 2009", "Dec 31, 2009", "Jan 29, 2000", "Jan 29, 2100" };
foreach (string date in dates)
{
DateTime t1 = DateTime.Parse(date);
DateTime t2 = t1.AddMonths(1);
if (t1.Day != t2.Day)
Console.WriteLine("Error: no " + t2.ToString("MMM") + " " + t1.Day + ", " + t2.Year);
else
Console.WriteLine(t2.ToString("MMM dd, yyyy"));
}
Console.ReadLine();
}
}
``` | How to get the same time and Day next month using DateTime in c# | [
"",
"c#",
"datetime",
""
] |
Edit: Matt, that does indeed solves some (most) of my problems, thank you. Now the only lingering issue of how do I do this in WPF? I have a custom part based off of a `UserControl` but there is no way in WPF to do :
```
[Import]<my:SomeCustomControl>
```
so the cascade doesn't work in this instance.
/Edit
---
I am having an issue [Import]ing various MEF components in my project. Do I have to use a CompositionContainer in every class I use? In the code below, a null reference exception is thrown in the method Helper.TimesTwo() but when I call logger.Log() in the Program class, everything works. Any help would be greatly appreciated.
(this will compile and run as a console app).
```
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.Run();
}
[Import]
private ILog logger { get; set; }
public void Run()
{
var catalog = new DirectoryCatalog(".");
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
logger.Log("hello");
var h = new Helper();
logger.Log(h.TimesTwo(15).ToString());
Console.ReadKey();
}
}
class Helper
{
[Import]
private IDouble doubler { get; set; }
private Helper()
{
// do I have to do all the work with CompositionContainer here again?
}
public double TimesTwo(double d)
{
return doubler.DoubleIt(d);
}
}
interface ILog
{
void Log(string message);
}
[Export(typeof(ILog))]
class MyLog : ILog
{
public void Log(string message)
{
Console.WriteLine("mylog: " + message);
}
}
interface IDouble
{
double DoubleIt(double d);
}
[Export(typeof(IDouble))]
class MyDoubler : IDouble
{
public double DoubleIt(double d)
{
return d * 2.0;
}
}
}
``` | No you can't do that. You could look into using attached properties though for this. With an attached property you can have the container compose the element that the attached property is added to. Another option would be markup extensions.
Glenn | I think the trick is to make use of the fact that MEF will cascade its imports. So if you import your Helper instance rather than declaring it as a local variable, any imports that the Helper requires will be satisfied.
```
[Import]
public Helper MyHelper { get; set; }
public void Run()
{
var catalog = new DirectoryCatalog(".");
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
logger.Log("hello");
logger.Log(MyHelper.TimesTwo(15).ToString());
Console.ReadKey();
}
```
I'm sure there's a way to have it satisfy any imports in a local variable, but I like using the "cascaded imports" feature like that. | MEF: Unable to import in other classes? | [
"",
"c#",
"wpf",
"null",
"mef",
""
] |
If you scan a folder containing other folders AND files, how do you get rid of . and .. and files? How do you put in array only folders WITHOUT . and ..?
I would like to use regular expression, but I'm newbie and I can't get it right.
My code is now this but doesn't work:
> if(fnmatch("\.{1,2}",$dir\_array[$i]) || is\_file($dir\_array[$i]){
> unset($dir\_array[$i]);
> }else{
> //other code
> } | You are confusing fnmatch and regular expressions in your code. To get all files and directories except the special ones, use this:
```
$dir_array = array_diff($dir_array, array(".", ".."));
```
Alternatively, if you iterate the array anyway, you can test each element like this:
```
foreach ($dir_array as $name) {
if (($name != "..") && ($name != ".")) {
// Do stuff on all files and directories except . ..
if (is_dir($name)) {
// Do stuff on directories only
}
}
}
```
In php<5.3, you can exclusively [use a callback function](http://php.net/manual/en/function.array-filter.php), too:
```
$dir_array = array_filter($dir_array,
create_function('$n', 'return $n != "." && $n != ".." && is_dir($n);'));
```
(See Allain Lalonde's answer for a more verbose version)
Since php 5.3, this can be written [nicer](http://wiki.php.net/rfc/closures):
```
$dir_array = array_filter($dir_array,
function($n) {return $n != "." && $n != ".." && is_dir($n);});
```
Finally, combining array\_filter and the first line of code of this answer yields an (insignificantly) slower, but probably more readable version:
```
$dir_array = array_filter(array_diff($dir_array, array(".", "..")), is_dir);
``` | You don’t need a regular expression to test this. Just use plain string comparison:
```
if ($dir_array[$i] == '.' || $dir_array[$i] == '..' || is_file($dir_array[$i])) {
unset($dir_array[$i]);
}
``` | How to get rid of . and .. while scaning the folder creating an array in php? | [
"",
"php",
"regex",
"arrays",
"file",
"directory",
""
] |
In an application I'm working on I've implemented a MVC pattern to use different views for displaying parts of a UI. In an overall UI there's an entry box, in which the user can give commands or queries. The idea is that this entry box generates a few basic events, like "ValidEntry", "InvalidEntry" and "EmptyEntry". Each one of the controller parts should respond to these events. I do not want every controller that is subscribed to the ValidEntry event to respond, only the one that is active.
I could add an "if" to every eventhandler that checks if "this.IsActive" is true and update that on every switch of views. Or add different events for all different controllers. Any better ideas on this problem? | Assuming only 1 controller is active at once, how about having some sort of controller manager class, with a SetActiveController method. The manager would subscribe to the UI events and call the approproate method on the currently active controller. | For events like the ValidEntry where you want only a single controller to respond to, the simplest way is to "downgrade" it into a delegate and assign it to the active controller's handler whenever it receives focus.
Of course a manager keeping track of visibility and subscription will definitely give better structure when this simple requirement gets complex. But for now it's an overkill :) | Handling events from shared control in MVC | [
"",
"c#",
"model-view-controller",
"events",
""
] |
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:
```
"(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)"
```
And then concatenate the `start` group with the new data for `replace` and then the `end` group.
Is there a better method for this? | Look in the Python [re documentation](http://docs.python.org/library/re.html) for lookaheads `(?=...)` and lookbehinds `(?<=...)` -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match. | ```
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
``` | Regex replace (in Python) - a simpler way? | [
"",
"python",
"regex",
""
] |
I have built a small web application in PHP where users must first log in. Once they have logged in, I intend on showing a small thumbnail as part of their "profile".
I will have to ensure the image is below a particular size to conserve space, or ensure it is a particular resolution, or both, or even perhaps use something like image magick to scale it down.
Not sure what the best approach for that is yet, any ideas welcome.
Also, I have been trying to work out if it is better to store the image in the `users` table of MySQL as a blob, or maybe a separate `images` table with a unique id, and just store the appropriate image id in the `users` table, or simply save the uploaded file on the server (via an upload page as well) and save the file as `theUsersUniqueUsername.jpg`.
Best option?
I found a tutorial on saving images to mysql here:
<http://www.phpriot.com/articles/images-in-mysql>
I am only a hobby programmer, and haven't ever done anything like this before, so examples, and/or a lot of detail is greatly appreciated. | Always depends of context, but usually, I store a user image on the filesystem in a folder called `/content/user/{user_id}.jpg` and try to bother the database as little as possible. | I would recommend storing the image as a file and then have the file URI in the database. If you store all the images in the database, you might have some problems with scaling at a later date.
Check out [this answer](https://stackoverflow.com/questions/522957/what-is-the-best-format-to-store-images-in-a-database/522983#522983) too:
> Microsoft's advice for SQL Server used to be, for speed and size, store images in the file system, with links in the database. I think they've softened their preference a bit, but I still consider it a better idea certainly for size, since it will take up no space in the database. | PHP to store images in MySQL or not? | [
"",
"php",
"mysql",
"image",
""
] |
I'm looking to retrieve a machine's windows experience rating in C#. If possible I would also like to retrieve the numbers for each component (Graphics, RAM etc.)
Is this possible? | Every time the user goes through control panel to calculate the Windows Experience Rating, the system creates a new file in `%Windows%\Performance\WinSAT\DataStore\`
You need to find the most recent file (they are named with the most significant date first, so finding the latest file is trivial).
These files are xml files and are easy to parse with XmlReader or other xml parser.
The section you are interested in is `WinSAT\WinSPR` and contains all the scores in a single section. E.g.
```
<WinSAT>
<WinSPR>
<SystemScore>3.7</SystemScore>
<MemoryScore>5.9</MemoryScore>
<CpuScore>5.2</CpuScore>
<CPUSubAggScore>5.1</CPUSubAggScore>
<VideoEncodeScore>5.3</VideoEncodeScore>
<GraphicsScore>3.9</GraphicsScore>
<GamingScore>3.7</GamingScore>
<DiskScore>5.2</DiskScore>
</WinSPR>
...
``` | Same with LINQ:
```
var dirName = Environment.ExpandEnvironmentVariables(@"%WinDir%\Performance\WinSAT\DataStore\");
var dirInfo = new DirectoryInfo(dirName);
var file = dirInfo.EnumerateFileSystemInfos("*Formal.Assessment*.xml")
.OrderByDescending(fi => fi.LastWriteTime)
.FirstOrDefault();
if (file == null)
throw new FileNotFoundException("WEI assessment xml not found");
var doc = XDocument.Load(file.FullName);
Console.WriteLine("Processor: " + doc.Descendants("CpuScore").First().Value);
Console.WriteLine("Memory (RAM): " + doc.Descendants("MemoryScore").First().Value);
Console.WriteLine("Graphics: " + doc.Descendants("GraphicsScore").First().Value);
Console.WriteLine("Gaming graphics: " + doc.Descendants("GamingScore").First().Value);
Console.WriteLine("Primary hard disk: " + doc.Descendants("DiskScore").First().Value);
Console.WriteLine("Base score: " + doc.Descendants("SystemScore").First().Value);
``` | Retrieve Windows Experience Rating | [
"",
"c#",
"rating",
""
] |
I have two tables: 'movies' and 'users'.
There's an n:m relationship between those, describing what movies a user has seen. This is described with a table 'seen'
Now i want to find out for a given user, all the movies he has not seen.
My current solution is like this:
```
SELECT *
FROM movies
WHERE movies.id NOT IN (
SELECT seen.movie_id
FROM seen
WHERE seen.user_id=123
)
```
This works fine but does not seem to scale very well. Is there a better approach to this? | Here's a typical way to do this query without using the subquery method you showed. This may satisfy @Godeke's request to see a join-based solution.
```
SELECT *
FROM movies m
LEFT OUTER JOIN seen s
ON (m.id = s.movie_id AND s.user_id = 123)
WHERE s.movie_id IS NULL;
```
However, in most brands of database this solution can perform worse than the subquery solution. It's best to use EXPLAIN to analyze both queries, to see which one will do better given your schema and data.
Here's another variation on the subquery solution:
```
SELECT *
FROM movies m
WHERE NOT EXISTS (SELECT * FROM seen s
WHERE s.movie_id = m.id
AND s.user_id=123);
```
This is a correlated subquery, which must be evaluated for every row of the outer query. Usually this is expensive, and your original example query is better. On the other hand, in MySQL "`NOT EXISTS`" is often better than "`column NOT IN (...)`"
Again, you must test each solution and compare the results to be sure. **It's a waste of time to choose any solution without measuring performance.** | Not only does your query work, it's the right approach to the problem as stated. Perhaps you can find a different way to approach the problem? A simple LIMIT on your outer select should be very fast even for large tables, for instance. | MySQL: Finding rows that don't take part in a relationship | [
"",
"sql",
"mysql",
"join",
"entity-relationship",
""
] |
Since the trigonometric functions in java.lang.Math are quite slow: is there a library that does a quick and good approximation? It seems possible to do a calculation several times faster without losing much precision. (On my machine a multiplication takes 1.5ns, and java.lang.Math.sin 46ns to 116ns). Unfortunately there is not yet a way to use the hardware functions.
UPDATE: The functions should be accurate enough, say, for GPS calculations. That means you would need at least 7 decimal digits accuracy, which rules out simple lookup tables. And it should be much faster than java.lang.Math.sin on your basic x86 system. Otherwise there would be no point in it.
For values over pi/4 Java does [some expensive computations](https://bugs.java.com/bugdatabase/view_bug?bug_id=4857011) in addition to the hardware functions. It does so for a good reason, but sometimes you care more about the speed than for last bit accuracy. | [Computer Approximations](https://rads.stackoverflow.com/amzn/click/com/0882756427) by Hart. Tabulates [Chebyshev-economized](http://en.wikipedia.org/wiki/Approximation_theory) approximate formulas for a bunch of functions at different precisions.
**Edit:** Getting my copy off the shelf, it turned out to be [a different book](https://rads.stackoverflow.com/amzn/click/com/B0000CJASU) that just sounds very similar. Here's a sin function using its tables. (Tested in C since that's handier for me.) I don't know if this will be faster than the Java built-in, but it's guaranteed to be less accurate, at least. :) You may need to range-reduce the argument first; see [John Cook's suggestions](https://stackoverflow.com/questions/523531/fast-transcendent-trigonometric-functions-for-java/523777#523777). The book also has arcsin and arctan.
```
#include <math.h>
#include <stdio.h>
// Return an approx to sin(pi/2 * x) where -1 <= x <= 1.
// In that range it has a max absolute error of 5e-9
// according to Hastings, Approximations For Digital Computers.
static double xsin (double x) {
double x2 = x * x;
return ((((.00015148419 * x2
- .00467376557) * x2
+ .07968967928) * x2
- .64596371106) * x2
+ 1.57079631847) * x;
}
int main () {
double pi = 4 * atan (1);
printf ("%.10f\n", xsin (0.77));
printf ("%.10f\n", sin (0.77 * (pi/2)));
return 0;
}
``` | [Here](http://www.shellandslate.com/computermath101.html) is a collection of low-level tricks for quickly approximating trig functions. There is example code in C which I find hard to follow, but the techniques are just as easily implemented in Java.
Here's my equivalent implementation of invsqrt and atan2 in Java.
I could have done something similar for the other trig functions, but I have not found it necessary as profiling showed that only sqrt and atan/atan2 were major bottlenecks.
```
public class FastTrig
{
/** Fast approximation of 1.0 / sqrt(x).
* See <a href="http://www.beyond3d.com/content/articles/8/">http://www.beyond3d.com/content/articles/8/</a>
* @param x Positive value to estimate inverse of square root of
* @return Approximately 1.0 / sqrt(x)
**/
public static double
invSqrt(double x)
{
double xhalf = 0.5 * x;
long i = Double.doubleToRawLongBits(x);
i = 0x5FE6EB50C7B537AAL - (i>>1);
x = Double.longBitsToDouble(i);
x = x * (1.5 - xhalf*x*x);
return x;
}
/** Approximation of arctangent.
* Slightly faster and substantially less accurate than
* {@link Math#atan2(double, double)}.
**/
public static double fast_atan2(double y, double x)
{
double d2 = x*x + y*y;
// Bail out if d2 is NaN, zero or subnormal
if (Double.isNaN(d2) ||
(Double.doubleToRawLongBits(d2) < 0x10000000000000L))
{
return Double.NaN;
}
// Normalise such that 0.0 <= y <= x
boolean negY = y < 0.0;
if (negY) {y = -y;}
boolean negX = x < 0.0;
if (negX) {x = -x;}
boolean steep = y > x;
if (steep)
{
double t = x;
x = y;
y = t;
}
// Scale to unit circle (0.0 <= y <= x <= 1.0)
double rinv = invSqrt(d2); // rinv ≅ 1.0 / hypot(x, y)
x *= rinv; // x ≅ cos θ
y *= rinv; // y ≅ sin θ, hence θ ≅ asin y
// Hack: we want: ind = floor(y * 256)
// We deliberately force truncation by adding floating-point numbers whose
// exponents differ greatly. The FPU will right-shift y to match exponents,
// dropping all but the first 9 significant bits, which become the 9 LSBs
// of the resulting mantissa.
// Inspired by a similar piece of C code at
// http://www.shellandslate.com/computermath101.html
double yp = FRAC_BIAS + y;
int ind = (int) Double.doubleToRawLongBits(yp);
// Find φ (a first approximation of θ) from the LUT
double φ = ASIN_TAB[ind];
double cφ = COS_TAB[ind]; // cos(φ)
// sin(φ) == ind / 256.0
// Note that sφ is truncated, hence not identical to y.
double sφ = yp - FRAC_BIAS;
double sd = y * cφ - x * sφ; // sin(θ-φ) ≡ sinθ cosφ - cosθ sinφ
// asin(sd) ≅ sd + ⅙sd³ (from first 2 terms of Maclaurin series)
double d = (6.0 + sd * sd) * sd * ONE_SIXTH;
double θ = φ + d;
// Translate back to correct octant
if (steep) { θ = Math.PI * 0.5 - θ; }
if (negX) { θ = Math.PI - θ; }
if (negY) { θ = -θ; }
return θ;
}
private static final double ONE_SIXTH = 1.0 / 6.0;
private static final int FRAC_EXP = 8; // LUT precision == 2 ** -8 == 1/256
private static final int LUT_SIZE = (1 << FRAC_EXP) + 1;
private static final double FRAC_BIAS =
Double.longBitsToDouble((0x433L - FRAC_EXP) << 52);
private static final double[] ASIN_TAB = new double[LUT_SIZE];
private static final double[] COS_TAB = new double[LUT_SIZE];
static
{
/* Populate trig tables */
for (int ind = 0; ind < LUT_SIZE; ++ ind)
{
double v = ind / (double) (1 << FRAC_EXP);
double asinv = Math.asin(v);
COS_TAB[ind] = Math.cos(asinv);
ASIN_TAB[ind] = asinv;
}
}
}
``` | Fast transcendent / trigonometric functions for Java | [
"",
"java",
"optimization",
"math",
"trigonometry",
""
] |
Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time? | The shelve module uses an underlying database package (such as dbm, [gdbm](http://docs.python.org/library/gdbm.html#module-gdbm) or bsddb) .
The [*restrictions* pragraph](http://docs.python.org/library/shelve.html#restrictions) says (my emphasis):
> The shelve module **does not support concurrent read/write access to shelved objects**. (Multiple simultaneous read accesses are safe.) When a program has a shelf open for writing, no other program should have it open for reading or writing. Unix file locking can be used to solve this, but this differs across Unix versions and requires knowledge about the database implementation used.
Conclusion: it depends on OS and the underlying DB. To keep things portable, do not build on concurrency. | I've implemented [Ivo's approach](https://stackoverflow.com/questions/486490/python-shelve-module-question/7915260#7915260) as a context manager, for anyone interested:
```
from contextlib import contextmanager
from fcntl import flock, LOCK_SH, LOCK_EX, LOCK_UN
import shelve
@contextmanager
def locking(lock_path, lock_mode):
with open(lock_path, 'w') as lock:
flock(lock.fileno(), lock_mode) # block until lock is acquired
try:
yield
finally:
flock(lock.fileno(), LOCK_UN) # release
class DBManager(object):
def __init__(self, db_path):
self.db_path = db_path
def read(self):
with locking("%s.lock" % self.db_path, LOCK_SH):
with shelve.open(self.db_path, "r", 2) as db:
return dict(db)
def cas(self, old_db, new_db):
with locking("%s.lock" % self.db_path, LOCK_EX):
with shelve.open(self.db_path, "c", 2) as db:
if old_db != dict(db):
return False
db.clear()
db.update(new_db)
return True
``` | Python shelve module question | [
"",
"python",
"shelve",
""
] |
I'm facing this strange problem.
I'm trying to read a file that is located in another machine as a shared resource:
```
\\remote-machine\dir\MyFileHere.txt
```
When I run a standalone application ( a 16 lines java file ) everything is just fine. But when I attempt to read the same file with using the same class and the same method from a server "engine" ( this is an application engine, pretty much like a Java EE Application Server where you can run java programs ) the "FileNotFoundException" is thrown.
I though I would be some sort of permissions, so I map the resource as a drive: K:\
Re-run my java file, reads, fine.
Re-run my java file inside the "engine" -> FileNotFoundException.
When I copy the file into the local machine ( C:\MyFileHere.txt ) no exception is thrown.
**Question**
What may be causing this FileNotFoundExcecption?
I'm using Java 1.5
As far as I know the engine pretty much uses java transparently.
Anyone has faced something similar?
Additional question? What would be a good approach for workaround this? I'm starting to think about a tomcat installation serving those files and read them through http, but I think that's too much, that's why the SMB protocol is for in first place isn't it? And probably I won't be able to open sockets anyway.
Does security manager may be the cause ( I have never used that before, but I know it exists )
Wound't a SecurityException be thrown instead if that would be the case?
Thanks a lot.
**EDIT**
Solved. Thank you Steve W.
It turns out that this engine is launched with "LaunchAnywhere" from ZeroG. So, a .exe is created that in turn will run a JVM with the specified app.
This application it self is Launcher. When it start the engine, somehow ( I cannot figure out why or how ) the user that owns the JVM process is SYSTEM. AS Steve pointed out, this user doesn't have NETWORK access, and thus cannot read from a shared resource or a mapped drive.
The workaround ( while I report this to the manufacturer ) is to create a .cmd file to lauch manually the engine. Since it would be manually launched the user does have access to the network.
I've used "Process Explorer" from SysInternals to know exactly the command line used to run the engine app.
WHAT A MESS!
Thanks to those who posted answers. | Is the shared resource protected by a username and password? And if so, is your application engine running as that user? If your application engine is running as a Windows Service, the Windows service cannot be running as the "Local System Account". This account cannot access the network. You must configure your service to run as a user that has the rights to access the shared drive. | Double check that the file is REALLY Called "MyFileHere.txt" and not "MyFileHere.txt.txt"
If you are hiding the extention of the file this is an easy mistake to miss | FileNotFoundException thrown when the file does exists | [
"",
"java",
"jvm",
"io",
"filenotfoundexception",
"smb",
""
] |
How do I write a sub-select in LINQ.
If I have a list of customers and a list of orders I want all the customers that have no orders.
This is my pseudo code attempt:
```
var res = from c in customers
where c.CustomerID ! in (from o in orders select o.CustomerID)
select c
``` | How about:
```
var res = from c in customers
where !orders.Select(o => o.CustomerID).Contains(c.CustomerID)
select c;
```
Another option is to use:
```
var res = from c in customers
join o in orders
on c.CustomerID equals o.customerID
into customerOrders
where customerOrders.Count() == 0
select c;
```
Are you using LINQ to SQL or something else, btw? Different flavours may have different "best" ways of doing it | If this is database-backed, try using navigation properties (if you have them defined):
```
var res = from c in customers
where !c.Orders.Any()
select c;
```
On Northwind, this generates the TSQL:
```
SELECT /* columns snipped */
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
))
```
Which does the job quite well. | Linq Sub-Select | [
"",
"c#",
"linq",
"outer-join",
""
] |
I've got a simple procedure to strip a string of all characters illegal in XML:
```
string SanitizeXml(string xml)
{
return string.Concat
(xml.ToCharArray().Where(c => IsLegalXmlChar(c)).ToArray());
}
```
It's nice and terse. But I'm concerned about its performance. The same thing could easily be accomplished using a simple for loop:
```
string SanitizeXml(string xml)
{
var buffer = new StringBuilder();
foreach(char c in xml)
{
if (IsLegalXmlChar(c))
{
buffer.Append(c);
}
}
return buffer.ToString();
}
```
What sticks out to me is that, in the second example, xml is converted to a char[], and Where()'s IEnumerable<char> back to a char[]. I seem to do this a lot with LINQ--change between arrays and enumerables.
Should I be concerned about this? What kind of performance hit am I going to get, in general, for relying on LINQ extension methods when there a clear alternative that may be a little more verbose.
Perhaps this is too broad of a question. | Well, you don't need the first call to `ToCharArray()` to start with - string implements `IEnumerable<char>`. However, I agree that a StringBuilder and a loop would probably be more appropriate in this case.
I'm not sure what string.Concat(char[]) does offhand, btw - why aren't you just using the string constructor which takes a char array? In other words, after these modifications:
```
static string SanitizeXml(string xml)
{
return new string (xml.Where(c => IsLegalXmlChar(c)).ToArray());
}
```
I still prefer a StringBuilder solution, but that could be improved for the common case (where there are few illegal characters) by giving an appropriate capacity to start with:
```
string SanitizeXml(string xml)
{
var buffer = new StringBuilder(xml.Length);
foreach(char c in xml)
{
if (IsLegalXmlChar(c))
{
buffer.Append(c);
}
}
return buffer.ToString();
}
```
One alternative I hadn't thought of before might be an extension method on StringBuilder:
```
// Can't just call it Append as otherwise StringBuilder.Append(object) would
// be used :(
public static StringBuilder AppendSequence(this StringBuilder builder,
IEnumerable<char> sequence)
{
foreach (char c in sequence)
{
builder.Append(c);
}
return builder;
}
```
Then you could use it like this:
```
xml = new StringBuilder(xml.Length)
.AppendSequence(xml.Where(IsLegalXmlChar)
.ToString();
```
(You could have other overloads for AppendSequence to take IEnumerable etc, if you wanted.)
EDIT: Another alternative might be to avoid calling Append so often, using instead [the overload which appends a substring](http://msdn.microsoft.com/en-us/library/kc12ydtf.aspx). You could then again build an extension method for StringBuilder, something like (completely untested, I'm afraid - I haven't even tried compiling it):
```
public static StringBuilder AppendWhere(this StringBuilder builder,
string text,
Func<char, bool> predicate)
{
int start = 0;
bool lastResult = false;
for (int i=0; i < text.Length; i++)
{
if (predicate(text[i]))
{
if (!lastResult)
{
start = i;
lastResult = true;
}
}
else
{
if (lastResult)
{
builder.Append(text, start, i-start);
lastResult = false;
}
}
}
if (lastResult)
{
builder.Append(text, start, text.Length-start);
}
return builder;
}
```
Usage for the example:
```
xml = new StringBuilder(xml.Length).AppendWhere(xml, IsLegalXmlChar)
.ToString();
```
Another alternative would be to change it to be an extension method on String, create the StringBuilder lazily, and if you get to the end with start=0, just return the original string. | **For a simple `foreach` loop, the two version is essentially the same.**
Just think about why we have `IEnumerable` type in the first place, it's for use with `foreach` loop! If you use a foreach loop then your string gets converted to an IEnumerable behind the scenes and so the logic would essentially be the same as in the LINQ version.
Unless you throw in some optimization, i.e. using StringBuilder, performance won't be too different.
Here's a profiling code: <http://pastebin.com/f125a9a46>
Credit @Chris, @Marc\_Garvell, @Jon\_Skeet
This is the result on my machine:
```
Simple LINQ version : 43270ms
For-each-loop version w/ StringBuilder : 35875ms
For-each-loop version w/ List : 37595ms
For-index loop w/ StringBuilder : 37589ms
Jon Skeet's AppendWhere version : 28980ms
```
Here's the result with code optimization enabled:
```
Simple LINQ version : 27814ms
For-each-loop version w/ StringBuilder : 23453ms
For-each-loop version w/ List : 21374ms
For-index loop w/ StringBuilder : 22308ms
Jon Skeet's AppendWhere version : 10884ms
```
4.3 seconds difference between LINQ and foreach loop doesn't really justify 400,000,000 characters when you also take in the fact that you have utilized the StringBuilder while LINQ have the overhead of rebuilding from a char array. | LINQ performance implications | [
"",
"c#",
"linq",
""
] |
I want to write a function like so,
```
public System.Windows.Input.Key ResolveKey(char charToResolve)
{
// Code goes here, that resolves the charToResolve
// in to the Key enumerated value
// (For example with '.' as the character for Key.OemPeriod)
}
```
I know I can write a huge Switch-case to match the character, but is there any other way?
The thing with this is the Key enum's string may not match with the character so Enum.IsDefined will not work
Any ideas?
Update: This is in Windows environment | ```
[DllImport("user32.dll")]
static extern short VkKeyScan(char ch);
static public Key ResolveKey(char charToResolve)
{
return KeyInterop.KeyFromVirtualKey(VkKeyScan(charToResolve));
}
``` | Try using the ConvertFrom method of the System.Windows.Input.KeyConverter class. | How to convert a character in to equivalent System.Windows.Input.Key Enum value? | [
"",
"c#",
".net",
"enums",
"input",
"key",
""
] |
I have a Java program that I'd like to daemonize on a linux system. In other words, I want to start running it in a shell and have it continue running after I've logged out. I also want to be able to stop the program cleanly.
I found [this article](http://barelyenough.org/blog/2005/03/java-daemon/ "this article") which uses a combination of shell scripting and Java code to do the trick. It looks good, but I'd like something simpler, if possible.
What's your preferred method to daemonize a Java program on a Linux system? | [Apache Commons Daemon](http://commons.apache.org/daemon/) will run your Java program as Linux daemon or WinNT Service. | If you can't rely on [Java Service Wrapper](http://wrapper.tanukisoftware.org/) cited [elsewhere](https://stackoverflow.com/a/534680/362) (for instance, if you are running on Ubuntu, which has no packaged version of SW) you probably want to do it the old fashioned way: have your program write its PID in /var/run/$progname.pid, and write a standard SysV init script (use for instance the one for ntpd as an example, it's simple) around it. Preferably, make it LSB-compliant, too.
Essentially, the start function tests if the program is already running (by testing if /var/run/$progname.pid exists, and the contents of that file is the PID of a running process), and if not run
```
logfile=/var/log/$progname.log
pidfile=/var/run/$progname.pid
nohup java -Dpidfile=$pidfile $jopts $mainClass </dev/null > $logfile 2>&1
```
The stop function checks on /var/run/$progname.pid, tests if that file is the PID of a running process, verifies that it is a Java VM (so as not to kill a process that simply reused the PID from a dead instance of my Java daemon) and then kills that process.
When called, my main() method will start by writing its PID in the file defined in System.getProperty("pidfile").
One major hurdle, though: in Java, there is no simple and standard way to get the PID of the process the JVM runs in.
Here is what I have come up with:
```
private static String getPid() {
File proc_self = new File("/proc/self");
if(proc_self.exists()) try {
return proc_self.getCanonicalFile().getName();
}
catch(Exception e) {
/// Continue on fall-back
}
File bash = new File("/bin/bash");
if(bash.exists()) {
ProcessBuilder pb = new ProcessBuilder("/bin/bash","-c","echo $PPID");
try {
Process p = pb.start();
BufferedReader rd = new BufferedReader(new InputStreamReader(p.getInputStream()));
return rd.readLine();
}
catch(IOException e) {
return String.valueOf(Thread.currentThread().getId());
}
}
// This is a cop-out to return something when we don't have BASH
return String.valueOf(Thread.currentThread().getId());
}
``` | How to Daemonize a Java Program? | [
"",
"java",
"process",
"daemon",
""
] |
Is there a way (using .net) to connect an application i write to the 360? What I want to do is write a custom media sharing application, and have the contents stream to an xbox.
I see that there is an application for the mac called [Connect360](http://www.nullriver.com/products/connect360) that does this, so there must be a way, right? | [XBMC](http://xbmc.org) which uses the [Platinum UPnP library](http://www.plutinosoft.com/blog/projects/platinum), had Xbox 360 support [at one point](http://www.plutinosoft.com/blog/category/blah-blah/213). Not sure if it still does. However, both are open source and under revision control, so the source code should give you a good idea of how to implement UPnP support in your application. | Write a [DLNA server](http://www.allegrosoft.com/downloads/UPnP_DLNA_White_Paper.pdf). There's a media sharing server for linux that you can look into for an idea on how the protocols work, but I don't remember what it's called. | Connect my 360 to an application | [
"",
"c#",
"xbox360",
""
] |
Why GetHashCode is not a property like HashCode in .NET? | I don't think there's any good reason. Any implemention of `GetHashCode` should be fast enought to put into a property. That said, there are [plenty of design flaws](https://stackoverflow.com/questions/411906/c-net-design-flaws) in the .Net framework, some small, some serious. This seems like a small one. | Probably because it requires computation, and exposing it as a propery might imply that the hashcode is already available for free.
*Edit:*
Guidelines on this: [Properties versus Methods](http://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx#cpconpropertyusageguidelinesanchor1)
"The operation is expensive enough that you want to communicate to the user that they should consider caching the result."
Perhaps GetHashCode is expensive enough in some cases. | Why GetHashCode is not a property like HashCode in .NET | [
"",
"c#",
".net",
"hashcode",
""
] |
When my program starts, the main window places itself where it was when it was last closed. I want to modify this behavior some so if the window is off-screen (or partially off-screen) it moves itself to fully on screen.
I've got this working perfectly. Here's the code:
```
int x = gameConfig.windowX;
int y = gameConfig.windowY;
int width = gameConfig.windowWidth;
int height = gameConfig.windowHeight;
if( x < 0 ) x = 0;
if( y < 0 ) y = 0;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if( x + width > screenSize.width ) x = screenSize.width - width;
if( y + height > screenSize.height ) y = screenSize.height - height;
if( width > screenSize.width ) width = screenSize.width;
if( height > screenSize.height ) height = screenSize.height;
this.setLocation(x, y);
this.setSize(width, height );
if( gameConfig.screenMaximized ) {
this.setExtendedState(getExtendedState() | MAXIMIZED_BOTH );
}
```
This works as expected, but with one big exception; it doesn't account for taskbars. On windows, if the window is past the bottom of the screen, this code will correct it, but it still leaves a piece of the window blocked by the taskbar.
I'm not sure how to do this. Is there someway to ask java about any taskbars in the system, and what their width/height is?
---
Thanks that worked perfectly.
Do you know how to get it so Java will reflect the total screen size of both of my monitors when I call getScreenSize() ? Right now it is returning 1600x1200, when it's really 3200x1200, spanned across two monitors.
The Java API suggests that GraphicsConfiguration.getBounds() would do the trick, but that still returns the rectangle {0, 0, 1600, 1200}. | Use getScreenInsets (Java 4+):
```
static public Insets getScreenInsets(Window wnd) {
Insets si;
try {
if(wnd==null) { si=Toolkit.getDefaultToolkit().getScreenInsets(new Frame().getGraphicsConfiguration()); }
else { si=wnd.getToolkit() .getScreenInsets(wnd.getGraphicsConfiguration()); }
} catch(NoSuchMethodError thr) { si=new Insets(0,0,0,0); }
return si;
}
```
(This method allows for multiple screens, and older JVM's that don't support the API).
And, always remember the task bar may be on any edge of the screen, not just the bottom. | The below code worked for me, even tested by moving the toolbar to the right. But did not try with multiple screens.
```
public class Scene extends JFrame {
private static final long serialVersionUID = 42L;
public Scene() {
Canvas canvas = new Canvas();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(canvas);
this.pack();
this.putFrameInRightCorner();
this.setVisible(true);
}
protected void putFrameInRightCorner(){
Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
int taskBarWidth = screenSize.width - winSize.width;
int taskBarHeight = screenSize.height - winSize.height;
this.setLocation((screenSize.width - frameSize.width - taskBarWidth),
(screenSize.height - frameSize.height - taskBarHeight));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Scene();
}
});
}
}
``` | Java: Accounting for taskbars/menubars/etc when placing a window on the desktop? | [
"",
"java",
"swing",
""
] |
I'm implementing a DFA as close as I can to the formal definition as a learning exercise (and blogging material)
I planned on using a java.util.Set where a set is involved in the definition.
The definition involves a set of tuples to define the legal state transitions: (state,symbol) -> nextState.
I have a Transition class with members state, symbol and nextState. I have implemented equals() and hashCode() to indicate that two Transitions are equal if they match on state and symbol. I then have a java.util.Set of Transition instances.
In my processing algorithm, I have the current state when I read the next symbol. I anticipated building a Transition object using these two to pull out the matching Transition from the Set, which would then tell me the next state, and I can iterate.
But - I don't see any way of extracting a member of a java.util.Set for further use. I can remove(Object o), but that just return boolean.
What am I doing wrong? | Set is probably not what you want to use for this. My recommendation would be to use a List< Transition>, or possibly a Map< State,List< Transition>>. I'm not sure which would be better without actually building it and doing some benchmarking. | It sounds as though your overriding of equals() and hashCode() is dubious, because the original transition matches the one in the set according to equals() and yet the two are not interchangeable (otherwise you would just use the new transition in place of the original.)
You probably want a class that is just a combination of state and symbol with no other attributes, and use that as a key in a Map. Alternatively you could use a `Map<State, Map<Symbol, State>>` | Can I implement State Transitions for a DFA in Java using java.util.Set | [
"",
"java",
"computer-science",
"set",
"finite-automata",
""
] |
```
for (i = 0; i < document.checks.user.length; i++) //for all check boxes
{
if (document.checks.user[i].checked == true )
{
document.checks.submit();
return 0;
}
}
<body>
<form action="" method=POST name="checks" ID="Form2">
I have a bike:
<input type="checkbox" name="user" value="Bike" ID="Checkbox1">
<br>
<br>
</form>
<input type="button" value="Delete"
class="btn" onclick="sub_delete()"
onmouseover="hov(this, 'btn btnhov')" onmouseout="hov(this, 'btn')"
id="Button1" name="Button1"
/>
</body>
```
as you probably already know when there is only one check box left document.checks.user.length = undefined. Whats the most efficient way to make sure that when there is only one check box, it will be deleted. I was thinking just thinking to add it as a seperate if statement before the if statement here.....any suggesstions.
Thanks. | Use a loop control variable, and set it to 1 if length is undefined...
```
var len = document.checks.user.length;
if(len == undefined) len = 1;
for (i = 0; i < len; i++) //for all check boxes
```
Best regards... | ```
if (document.getElementById('Checkbox1').checked) { /* do something */ }
```
if you want to loop a bunch of checkboxes, you could loop the input fields of your form, like:
```
var formNodes = document.checks.getElementsByTagName('input');
for (var i=0;i<formNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
}
``` | Javascript and only one Checkbox - undefined | [
"",
"javascript",
"html",
"forms",
"checkbox",
""
] |
Basically I'm looking for a control that allows for grouping in a DataGridView control that can also be edited (I.E. something like DataGridView and TreeView into a single control).
Thanks in advance. | [Infragistics](http://www.infragistics.com/dotnet/netadvantage.aspx#Overview) UltraWebGrid (ASP.NET) and UltraWinGrid (Windows Forms) support grouping and can be setup as edittable grids. These controls are part of their NetAdvantage Suite. | Herre Kuijpers made a [OutlookGrid](http://www.codeproject.com/KB/grid/OutlookGrid.aspx) in CodeProject, which derives from DataGridView, and allows grouping of rows. | Looking for a DataGridView that allows grouping | [
"",
"c#",
"vb.net",
"controls",
""
] |
I have a point class like:
```
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
```
and a list of points:
```
std::list <Point> pointList;
std::list <Point>::iterator iter;
```
I'm pushing points on to my pointList (although the list might contain no Points yet if none have been pushed yet).
I have two questions:
**How can I delete the closest point to some arbitrary (x, y) from the list?**
Lets say I have the x,y (5,12) and I want to find the Point in the list closest to that point and remove it from the STD::List.
I know I'll have to use the distance formula and I'll have to iterate through the list using an iterator but I'm having some trouble conceptualizing how I'll keep track of which point is the closest as I iterate through the list.
**How can I return an array or list of points within x radius of a given (x,y)?**
Similar to the last question except I need a list of pointers to the "Point" objects within say 5 radius of a given (x,y). Also, should I return an array or a List?
If anyone can help me out, I'm still struggling my way through C++ and I appreciate it. | Use a std::list::iterator variable to keep track of the closest point as you loop through the list. When you get to the end of the list it will contain the closest point and can be used to erase the item.
```
void erase_closest_point(const list<Point>& pointList, const Point& point)
{
if (!pointList.empty())
{
list<Point>::iterator closestPoint = pointList.begin();
float closestDistance = sqrt(pow(point.x - closestPoint->x, 2) +
pow(point.y - closestPoint->y, 2));
// for each point in the list
for (list<Point>::iterator it = closestPoint + 1;
it != pointList.end(); ++it)
{
const float distance = sqrt(pow(point.x - it->x, 2) +
pow(point.y - it->y, 2));
// is the point closer than the previous best?
if (distance < closestDistance)
{
// replace it as the new best
closestPoint = it;
closestDistance = distance
}
}
pointList.erase(closestPoint);
}
}
```
Building a list of points within a radius of a given point is similar. Note that an empty radius list is passed into the function by reference. Adding the points to the list by reference will eliminate the need for copying all of the points when returning the vector by value.
```
void find_points_within_radius(vector<Point>& radiusListOutput,
const list<Point>& pointList,
const Point& center, float radius)
{
// for each point in the list
for (list<Point>::iterator it = pointList.begin();
it != pointList.end(); ++it)
{
const float distance = sqrt(pow(center.x - it->x, 2) +
pow(center.y - it->y, 2));
// if the distance from the point is within the radius
if (distance > radius)
{
// add the point to the new list
radiusListOutput.push_back(*it);
}
}
}
```
Again using copy if:
```
struct RadiusChecker {
RadiusChecker(const Point& center, float radius)
: center_(center), radius_(radius) {}
bool operator()(const Point& p)
{
const float distance = sqrt(pow(center_.x - p.x, 2) +
pow(center_.y - p.y, 2));
return distance < radius_;
}
private:
const Point& center_;
float radius_;
};
void find_points_within_radius(vector<Point>& radiusListOutput,
const list<Point>& pointList,
const Point& center, float radius)
{
radiusListOutput.reserve(pointList.size());
remove_copy_if(pointList.begin(), pointList.end(),
radiusListOutput.begin(),
RadiusChecker(center, radius));
}
```
*Note that the **sqrt** can be removed if you need extra performance since the square of the magnitude works just as well for these comparisons. Also, if you really want to increase performance than consider a data structure that allows for scene partitioning like a [quadtree](http://en.wikipedia.org/wiki/Quadtree). The first problem is closely related to [collision detection](http://en.wikipedia.org/wiki/Collision_detection) and there is a ton of valuable information about that topic available.* | You are right on how it should be made. Just iterate through all items in the list and keep track of the smallest distance already found, and the nearest point you found in two variables, making sure you don't match the point with itself if the problem states so. Then just delete the point you found.
How this is exactly made is kept as an exercise.
If you want to get a list of points in a given radius from another point, iterate the list and build a second list containing only the points within the specified range.
Again, how it's made in code is left to you as an exercise. | How do I delete the closest "Point" object in a STD::List to some x,y? | [
"",
"c++",
"list",
"pointers",
"distance",
""
] |
IE7/Windows XP
I have a third party component in my page that does a lot of DOM manipulation to adjust itself each time the browser window is resized.
Unfortunately I have little control of what it does internally and I have optimized everything else (such as callbacks and event handlers) as much as I can. I can't take the component off the flow by setting display:none because it fails measuring itself if I do so.
In general, does setting visibility of the container to invisible during the resize help improve DOM rendering performance? | Caveat: I have not specifically tested this with IE7, but I am reasonably confident based on what I know about its DOM manipulation model.
Changing CSS properties (whether `display: none` or `visibility: hidden` or what-have-you) will not affect the performance of DOM manipulation in any version of any browser I've worked with. The primary way to improve the speed of DOM manipulation is to remove the node(s) you will be working with from the document tree, performing your manipulations, and adding them back in. This involves keeping track of their succeeding sibling nodes, if any (for use with `insertBefore`), which can become complex if you're working with nodes which are scattered around the document.
One technique I have seen when performing a large number of DOM manipulations all at once is to get a list of the `body` element's children, remove them, perform your manipulations (wherever they fall in the document tree), and then reappend the body's child nodes. Depending on how long your DOM manipulations take (which is itself partially dependent on the speed of your visitor's computer!), this can produce a noticeable flicker. This is why sites manipulating content via AJAX will usually replace any temporarily-removed content with a "spinner" or loading screen. | I'm not certain, but removing it from the active document's DOM then manipulating it *does* improve performance. After all manipulating is done, attach it back to the document's DOM. Think of it sort of like video buffer swapping. | Does visibility affect DOM manipulation performance? | [
"",
"javascript",
"performance",
"optimization",
"dom",
""
] |
I have a std::list of Points (that simply store an x, y). Each one of these points represents a polygon, which I later draw.
```
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
std::list <Point> currentPolygon;
```
I would like to have a list of these polygons (lists themselves).
Is this possible? How do I have a std::list of a list of Points (so I can store more than one polygon). | You could use this:
```
std::list< std::list<Point> > polygons;
```
To make things easier, use typedefs.
```
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
typedef std::list<Point> PolygonType;
typedef std::list<PolygonType> PolygonsType;
``` | It sure is. But what you probably want - for expandability purposes later - create a second class - "polygon", that holds a list of points. Then use a list of polygons.
EDIT: I'm no C++ programmer, so I'm sure an implementation like [j\_random\_hacker's](https://stackoverflow.com/questions/544206/is-it-possible-or-ok-to-have-a-stdlist-of-stdlists/544685#544685) response is better if you're needing this for a real project. I merely wanted to give a quickie code example of this design.
```
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
class Polygon {
public:
std::list <Point> currentPolygon;
Polygon(std::list <Point> p1)
{
currentPolygon = p1
}
};
``` | Is it possible (or ok) to have a std::list of std::list's? | [
"",
"c++",
""
] |
I've looped over the `Request.ServerVariables` collection in ASP.NET, but it's not as comprehensive as `phpinfo()`.
How can I print all that information, including server software, drivers, etc, for ASP.NET? | An empty page with this header should do the trick:
```
<%@ Page Trace="true" Language="C#"
ContentType="text/html" ResponseEncoding="utf-8" %>
``` | <http://code.google.com/p/aspnetsysinfo/>
> The project is a ASP.Net System Information Prober. It's a single page which trying to get as much as possible of useful hosting information. The concept is similar to PHP page which contains `phpinfo()`... | How to print similar information as phpinfo() but for ASP.NET? | [
"",
"asp.net",
"configuration",
"webserver",
"php",
""
] |
I want to build an entire web app using only Javascript and MYSQL . How can I go about this if it's possible. | Try something like [Jaxer](http://www.aptana.com/jaxer), which will allow you to execute JavaScript on the Web Server and query databases.
Here are some syntax examples and usages:
---
**Database, file, and socket access from JavaScript**
[alt text http://jaxer.org/images/Picture+4\_0.png](http://jaxer.org/images/Picture+4_0.png)
---
**Easily create RESTful JSON data services**
[alt text http://jaxer.org/images/Picture+6.png](http://jaxer.org/images/Picture+6.png)
---
**Directly call server-side functions from the browser**
[alt text http://jaxer.org/images/Picture+2\_0.png](http://jaxer.org/images/Picture+2_0.png)
--- | If you can run javascript on the server, you can build a web-application with it (without the need for any other language like PHP etc.). Search the web for 'connection string mysql' to find out how to connect to your mySQL database and use ADO/ODBC. You'll need the MySQL ODBC-connector on the MySQL server.
Here's an example database connection (where MySQL server resides on the same server as the web server):
```
function connectDB()
{
var connectStr = "DRIVER={MySQL ODBC 3.51 Driver}; " +
"SERVER=localhost; " +
"PORT=[MySQL server port];" +
"DATABASE=[your database]; " +
"UID=[username];PWD=[password];" +
"OPTION=3",
conection = Server.CreateObject("ADODB.Connection");
//ERRID=>lib::connectDB::open
try {connection.Open(connectStr) }
catch(e) {errAlert(e,'rs::connectDB','connection failed',1) }
return connection;
}
```
(Where `errAlert` is a custom function to return the error) | Javascript and MySQL | [
"",
"javascript",
"mysql",
""
] |
I'm using Spring for an HTML form. One of the fields is an `enum` and thus I'd like a HTML drop-down list (`<option>` tag). My enum's name is different than the `toString()` value. For example:
```
public enum Size {
SMALL("Small"), LARGE("Large"), VERY_LARGE("Very large");
private final String displayName;
private Size(String displayName) {
this.displayName = displayName;
}
public String toString() {
return displayName;
}
}
```
I want the user to see the `toString()` value. Normally this is accomplished using the `itemLabel` of the Spring options tag.
```
<form:options items="${enumValues}" itemLabel="beanProperty" />
```
But `toString()` isn't a bean property as it doesn't start with "get". Is there a way to set `itemLabel` to use toString's value without having to create a getter? | I know this is few years old and must be solved by now, but thought I'd add the solution for future comers.
Just remove the [itemLabel="beanProperty"] part. It will use the toString to print the values. | Why not add a public getDisplayName() method to your enum? | Use Spring options tag to display enum's toString value | [
"",
"java",
"spring",
"jsp",
"enums",
""
] |
If you do not have Java installed in your computer, is it possible to compile and execute Java programs by pointing to a PC which has? | If you have Java installed on your machine then zip that whole directory and give that to those guys. They can extract it to their machine, they don;t need admin rights for that. Thats it you are done and can use javac and java to compile and run. You can add the bin directory to your PATH then you can executes these command from anywhere.
Also you can login to a remote machine where JDK is installed and the logged in user have execute permission. | Dude, you have an organizational problem, not a java problem. If the higer-ups don't want programmers hacking on the regular boxes, then you really shouldn't be trying to bypass the protection. Way to get in serious trouble.
Do it the right way - speak to someone with the authority to get the jdk & eclipse (or netbeans, if you insist) installed.
As a last resort - anyone who wants to learn java will have a home PC or a laptop. Just remember, if you have to use your home PC to learn java, then you owe your employer *nothing* by way of loyalty or obligation to use your new skills working for them. | Compiling and Executing Java Remotely | [
"",
"java",
""
] |
Bit stuck about how to go about this one. Given the current month, I need to to return the date of the fourth saturday of each month.
e.g. This month would be Feb 20th, next would be March 27th.
Thanks | I'm not a PHP coder, however, it seems strtotime is what you're after.
You can use strtotime("fourth Saturday") and it will return the 4th saturday.
Check out the [`strtotime`](http://php.net/strtotime) docs.
EDIT:
Just to make the answer complete, thanks to Tom and Paul Dixon
```
date('dS F',strtotime('Fourth Saturday '.date('F o')));
``` | You can use [strtotime](http://php.net/strtotime) to find "next saturday" based on a starting date. If that starting date is the day before the earliest possible preceding day (21st) we get the answer...
```
//required year/month
$yyyymm="2009-01";
//find next saturday after earliest possible date
$t=strtotime("next saturday", strtotime("{$yyyymm}-21"));
//here you go!
echo "4th saturday of $yyyymm is ".strftime("%Y-%m-%d",$t)."\n";
```
Earliest possible 4th repeat of a day in any month is the 22nd (1,8,15,22), last possible 4th repeat is 28th (7,14,21,28).
**EDIT**: Although it's not clear in the documentation, you can request the "fourth saturday" too - use the zeroth day of the month as the basis:
```
$t=strtotime("fourth saturday", strtotime("{$yyyymm}-00"));
```
or omit the basis time and specify the month and year directly:
```
$t=strtotime("fourth saturday feb 2009");
```
*Tip of the hat to Robin "I'm not a PHP coder" Day for spotting that :)* | work out the date of the fourth saturday in the current month | [
"",
"php",
"datetime",
"date",
""
] |
I thought this would be simple, but searching Google didn't seem to help.
I'm basically trying to write a function which will return a ratio as a string (eg 4:3) when supplies with two integers (eg 800 and 600).
```
string GetRatio(Int A, Int B) {
// Code I'm looking for
return Ratio;
}
``` | You can simplify fractions by dividing numerator and denominator by their [GCD](http://en.wikipedia.org/wiki/Greatest_common_divisor):
```
var gcd = GCD(A, B);
return string.Format("{0}:{1}", A / gcd, B / gcd)
```
And a very basic function for calculating the GCD, using the [Euclidean algorithm](http://en.wikipedia.org/wiki/Euclidean_algorithm):
```
static int GCD(int a, int b) {
return b == 0 ? Math.Abs(a) : GCD(b, a % b);
}
``` | Are you basically trying to get the greatest common denominator - GCD for the two numbers and then dividing them by that and thus getting your string ?
I.e: 800 : 600 ; the greatest common denominator = 200 thus 4:3.
This would be able to deal with all integer numbers. Sorry for not sending the code, but I think that from this on it should be simple enough.
```
public int GCD(int a, int b)
{
while (a != 0 && b != 0)
{
if (a > b)
a %= b;
else
b %= a;
}
if (a == 0)
return b;
else
return a;
}
// Using Konrad's code:
var gcd = GCD(A, B);
return string.Format("{0}:{1}", A / gcd, B / gcd)
``` | Calculate a Ratio in C# | [
"",
"c#",
"string-formatting",
""
] |
I've got data in ten minutes intervals in my table:
```
2009-01-26 00:00:00 12
2009-01-26 00:10:00 1.1
2009-01-26 00:20:00 11
2009-01-26 00:30:00 0
2009-01-26 00:40:00 5
2009-01-26 00:50:00 3.4
2009-01-26 01:00:00 7
2009-01-26 01:10:00 7
2009-01-26 01:20:00 7.2
2009-01-26 01:30:00 3
2009-01-26 01:40:00 25
2009-01-26 01:50:00 4
2009-01-26 02:00:00 3
2009-01-26 02:10:00 4
etc.
```
Is it possible to formulate a single SQL-query for MySQL which will return a series of averages over each hour?
In this case it should return:
```
5.42
8.87
etc.
``` | It's unclear whether you want the average to be aggregated over days or not.
If you want a different average for midnight on the 26th vs midnight on the 27th, then modify Mabwi's query thus:
```
SELECT AVG( value ) , thetime
FROM hourly_averages
GROUP BY DATE( thetime ), HOUR( thetime )
```
Note the additional `DATE()` in the `GROUP BY` clause. Without this, the query would average together all of the data from `00:00` to `00:59` without regard to the date on which it happened. | This should work:
```
SELECT AVG( value ) , thetime
FROM hourly_averages
GROUP BY HOUR( thetime )
```
Here's the result
```
AVG(value) thetime
5.4166666865349 2009-01-26 00:00:00
8.8666666348775 2009-01-26 01:00:00
3.5 2009-01-26 02:00:00
``` | How do I generate a series of hourly averages in MySQL? | [
"",
"sql",
"mysql",
""
] |
What are the best ways to protect from MySQL injection? What are weaknesses I should look out for?
I know what it is, but I really have no idea how vulnerable I might be. Though I have taken (what I think to be) steps toward protecting myself and my database.
Is there any sure-fire way of stopping someone?
BTW...I write in PHP:) | Use prepared statements instead of mixing the statement and the actual payload data.
see
* <http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html>
* [PDO::prepare](http://uk.php.net/manual/en/pdo.prepare.php)
* [mysqli::prepare](http://uk.php.net/manual/en/mysqli.prepare.php)
You might also be interested in <http://shiflett.org/articles/sql-injection> and <http://shiflett.org/blog/2007/sep/the-unexpected-sql-injection> | Trust no one!
Sanitize all input -- `filter_var()` or regexes or `in_array()` of valid values or a mixed strategy depending on datatype.
"Input" means any source of input that you don't directly control -- not just forms!
Sanitize anything you get back from `$_GET`, `$_POST`, `$_SESSION`, `$_COOKIE` -- anything that could have any possibility of being tainted.
AND
Use prepared statements | MySQL injection protection and vulnerability signs using PHP | [
"",
"php",
"mysql",
"database",
"sql-injection",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.