Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have an file input tag in my web app. I'd like to check that the file isn't too big before sending it to the server. Of course, I still have validation server side. Is there any way to do this with JavaScript? It must work in IE7+ and FF3+. Thank you.
EDIT: somefileinputobject.files[0].filesize works in FF, but not IE. | It's a hard problem. You have to do it with AJAX, and use the filesize headers sent by the browser to the server on the POST request.
Yahoo's UI Library has a tool to help with this. [YUI Uploader](http://developer.yahoo.com/yui/uploader/ "YUI Uploader") | Javascript cannot do this. It would have serious security issues. Perhaps flash can though. | How to retrieve the size of a file before uploading it? | [
"",
"javascript",
"file",
"input",
"filesize",
""
] |
Profiling my program and the function print is taking a lot of time to perform. How can I send "raw" byte output directly to stdout instead of using fwrite, and making it faster (need to send all 9bytes in the print() at the same time to the stdout) ?
```
void print(){
unsigned char temp[9];
temp[0] = matrix[0][0];
temp[1] = matrix[0][1];
temp[2] = matrix[0][2];
temp[3] = matrix[1][0];
temp[4] = matrix[1][1];
temp[5] = matrix[1][2];
temp[6] = matrix[2][0];
temp[7] = matrix[2][1];
temp[8] = matrix[2][2];
fwrite(temp,1,9,stdout);
```
}
Matrix is defined globally to be a unsigned char matrix[3][3]; | IO is not an inexpensive operation. It is, in fact, a **blocking** operation, meaning that the OS can preempt your process when you call `write` to allow more CPU-bound processes to run, before the IO device you're writing to completes the operation.
The only lower level function you can use (if you're developing on a \*nix machine), is to use the raw `write` function, but even then your performance will not be that much faster than it is now. Simply put: IO is expensive. | The top rated answer claims that IO is slow.
Here's a quick benchmark with a sufficiently large buffer to take the OS out of the critical performance path, but **only if** you're willing to receive your output in giant blurps. If latency to first byte is your problem, you need to run in "dribs" mode.
## Write 10 million records from a nine byte array
### Mint 12 AMD64 on 3GHz CoreDuo under gcc 4.6.1
```
340ms to /dev/null
710ms to 90MB output file
15254ms to 90MB output file in "dribs" mode
```
### FreeBSD 9 AMD64 on 2.4GHz CoreDuo under clang 3.0
```
450ms to /dev/null
550ms to 90MB output file on ZFS triple mirror
1150ms to 90MB output file on FFS system drive
22154ms to 90MB output file in "dribs" mode
```
There's nothing slow about IO if you can afford to buffer properly.
```
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char* argv[])
{
int dribs = argc > 1 && 0==strcmp (argv[1], "dribs");
int err;
int i;
enum { BigBuf = 4*1024*1024 };
char* outbuf = malloc (BigBuf);
assert (outbuf != NULL);
err = setvbuf (stdout, outbuf, _IOFBF, BigBuf); // full line buffering
assert (err == 0);
enum { ArraySize = 9 };
char temp[ArraySize];
enum { Count = 10*1000*1000 };
for (i = 0; i < Count; ++i) {
fwrite (temp, 1, ArraySize, stdout);
if (dribs) fflush (stdout);
}
fflush (stdout); // seems to be needed after setting own buffer
fclose (stdout);
if (outbuf) { free (outbuf); outbuf = NULL; }
}
``` | C/C++ best way to send a number of bytes to stdout | [
"",
"c++",
"c",
"optimization",
"stdout",
"fwrite",
""
] |
As a CRUD developer one of the trade offs that needs to be made is the decision of how much of the work should be done in SQL on the server, and how much ought to be done on the client end in code.
**How do you decide where the fulcrum goes? What factors go into your decisions? What kind of mistakes have you made? What works well?**
[EDIT] I am kind of surprised in the low volume of responses to this question. I think this is a basic issue for all CRUD programming. Where the balance is set is a trade off between performance and maintainability.
The other issue I didn't really consider is the fact that the domains vary enough, that the answers probably need to be expressed in sections for each domain. That's kind of what I tried to do in my answer. | My priorities:
1. Minimize database trips.
The code should do most of the work, if possible, and only visit the database when it has to. When it does, it should get as much needed for the current operation as possible.
2. Minimize SQL complexity.
Even if we should visit the database less, this doesn't mean building an overly complex SQL query that is non-performant and does too much. The query will still need to be maintained, and if two simpler queries will save the headache of developing and maintaining one mega-query, then extra code should be used rather than more database work.
3. Minimize code list iteration.
Code is great. A nice place to put the business logic, and lots of neat library functions. Code is awesome. But if using code means having to iterate over and over again through lists returned from the database where some simple database where clauses or joins could have eliminated that work, then the SQL needs to be improved, and the code minimized.
It's generally a case by case basis. For long-lived applications, maintenance is a huge cost and simplicity will often dictate my design. | A database is a place to hold multi-million row tables, to read and write effectively against those tables.
A database is not a place to perform string manipulation or date logic. It is not a place to calculate balances or to generate mailings. These concerns are better addressed with other tools (such as code). | SQL vs CODE, Where is the balance? | [
"",
"sql",
""
] |
I'm solving problems in [Project Euler](http://projecteuler.net/). Most of the problems solved by
1. big numbers that exceeds ulong,
> ```
> Ex : ulong number = 81237146123746237846293567465365862854736263874623654728568263582;
> ```
2. very sensitive decimal numbers with significant digits over 30
> Ex : decimal dec =
> 0,3242342543573894756936576474978265726385428569234753964340653;
3. arrays that must have index values that exceeds biggest int value.
> Ex : bool[] items = new
> bool[213192471235494658346583465340673475263842864836];
I found a library called IntX to solve this big numbers. But I wonder how can I solve this problems with basic .NET types ?
Thanks for the replies ! | Well, for the third item there you really don't want to use an array, since it needs to be allocated that big as well.
Let me rephrase that.
By the time you can afford, and get access to, that much memory, the big-number problem will be solved!
To answer your last question there, there is no way you can solve this using only basic types, unless you do what the makers of IntX did, implement big-number support.
Might I suggest you try a different programming language for the euler-problems? I've had better luck with Python, since it has support for big numbers out of the box and integrated into everything else. Well, except for that array, you really can't do that in any language these days. | Maybe this could give you ideas to how to solve part of your problem:
[<http://www.codeproject.com/csharp/BigInteger.asp>](http://www.codeproject.com/csharp/BigInteger.asp)
Wikipedia also has a good article about [Arbitrary-precision math](http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) and in that article there is a link to Codeplex and [W3b.sine](http://www.codeplex.com/sine) wich is an arbitrary precision real number c# library. | Numbers that exceeds basic types in C# | [
"",
"c#",
".net",
"math",
"types",
""
] |
I can use this jQuery code to dynamically change the RSS link in the DOM in Firefox & Chrome. <http://path.com/feed> is normally replaced by a variable, but not for this example.
```
$('#rssfeed').remove();
$('head').append('<link id="rssfeed" rel="alternate" type="application/rss+xml" href="http://path.com/feed"/>');
```
The live bookmark feature immediately updates. However, this doesn't work in IE7.
In IE7 I have tried this method, also created an in the html and tried updating with .setAttribute(href,'path.com/feed'), and tried creating a new DOM element and attaching it to "<\_head>" (no \_ in the actual code, of course).
The only "success" I have had was doing a document.write. The big problem with this is that I can't change it after the page has loaded.
Can anyone recommend an alternate way to change the link element href and have it dynamically reloaded by IE7? Alternatively, is there a way to force the browser to re-interpret or reload the DOM without doing a full page refresh? | Unfortunately, the short answers to your questions are "No" and "Sort of" because of a lack of browser support for udpating the list of feeds that are modified/added/removed in IE and Firefox.
First, in order to add elements to the document `HEAD` in IE (remember this applies to CSS as well), you must be sure to specify the first item in the array that is returned by jQuery's element selector (note the use of the [eq(index)](http://docs.jquery.com/Selectors/eq) selector):
```
$('head:eq(0)').append('<link id="rssfeed" rel="alternate" type="application/rss+xml" href="http://path.com/feed" title="Path (RSS)">');
```
Note: I found including the `TITLE` attribute made it easier to see the changes.
While you can change the `HREF` attribute of the `LINK` in both IE and Firefox (through the DOM), *neither* will update the RSS icon menu. *However*, you can **add** `LINK` elements and they will be recognized by the RSS icon menu but the old entries will remain because Firefox only builds that menu when `LINK`s are *added*.
See the following links for more information:
* [Ask MetaFilter - Firefox and Javascript issue](http://ask.metafilter.com/54377/Firefox-and-Javascript-issue)
* [Firefox Bug 380639: dynamic removal of feeds/ elements (DOMLinkRemoved) don't cause updates to the feed discovery menu](https://bugzilla.mozilla.org/show_bug.cgi?id=380639)
* [Firefox Bug 396056: DOM changes to existing elements don't trigger RSS autodiscovery menu updates](https://bugzilla.mozilla.org/show_bug.cgi?id=396056) | ```
$('#rssfeed').attr('href, 'http://path.com/feed?id=25463456');
```
Setting the url with a random id means that it should not be cached, as it has never gone to that url before. And that should not affect your feed either. | Possible to make IE7 reload the DOM? Trying to update RSS href url in link tags | [
"",
"javascript",
"jquery",
""
] |
So I have a table as follows:
```
ID_STUDENT | ID_CLASS | GRADE
-----------------------------
1 | 1 | 90
1 | 2 | 80
2 | 1 | 99
3 | 1 | 80
4 | 1 | 70
5 | 2 | 78
6 | 2 | 90
6 | 3 | 50
7 | 3 | 90
```
I need to then group, sort and order them to give:
```
ID_STUDENT | ID_CLASS | GRADE | RANK
------------------------------------
2 | 1 | 99 | 1
1 | 1 | 90 | 2
3 | 1 | 80 | 3
4 | 1 | 70 | 4
6 | 2 | 90 | 1
1 | 2 | 80 | 2
5 | 2 | 78 | 3
7 | 3 | 90 | 1
6 | 3 | 50 | 2
```
Now I know that you can use a temp variable to rank, [like here](https://stackoverflow.com/questions/431053/what-is-the-best-way-to-generate-ranks-in-mysql), but how do I do it for a grouped set? Thanks for any insight! | ```
SELECT id_student, id_class, grade,
@student:=CASE WHEN @class <> id_class THEN 0 ELSE @student+1 END AS rn,
@class:=id_class AS clset
FROM
(SELECT @student:= -1) s,
(SELECT @class:= -1) c,
(SELECT *
FROM mytable
ORDER BY id_class, id_student
) t
```
This works in a very plain way:
1. Initial query is ordered by `id_class` first, `id_student` second.
2. `@student` and `@class` are initialized to `-1`
3. `@class` is used to test if the next set is entered. If the previous value of the `id_class` (which is stored in `@class`) is not equal to the current value (which is stored in `id_class`), the `@student` is zeroed. Otherwise is is incremented.
4. `@class` is assigned with the new value of `id_class`, and it will be used in test on step 3 at the next row. | There is a problem with Quassnoi's solution (marked as best answer).
I have the same problematic (i.e. simulating SQL Window Function in MySQL) and I used to implement Quassnoi's solution, using user-defined variables to store previous row value...
But, maybe after a MySQL upgrade or whatever, my query did not work anymore. This is because the order of evaluation of the fields in SELECT is not guaranteed. @class assignment could be evaluated before @student assignment, even if it is placed after in the SELECT.
This is mentionned in MySQL documentation as follows :
> As a general rule, you should never assign a value to a user variable
> and read the value within the same statement. You might get the
> results you expect, but this is not guaranteed. The order of
> evaluation for expressions involving user variables is undefined and
> may change based on the elements contained within a given statement;
> in addition, this order is not guaranteed to be the same between
> releases of the MySQL Server.
source : <http://dev.mysql.com/doc/refman/5.5/en/user-variables.html>
Finally I have used a trick like that to be sure to assign @class AFTER reading it :
```
SELECT id_student, id_class, grade,
@student:=CASE WHEN @class <> id_class THEN concat(left(@class:=id_class, 0), 0) ELSE @student+1 END AS rn
FROM
(SELECT @student:= -1) s,
(SELECT @class:= -1) c,
(SELECT *
FROM mytable
ORDER BY id_class, grade desc
) t
```
Using left() function is just used to set @class variable. Then, concatenate the result of left() (equal to NULL) to the expected result is transparent.
Not very elegant but it works! | How to perform grouped ranking in MySQL | [
"",
"mysql",
"sql",
"window-functions",
""
] |
So lately I've been catching a lot of crap from a junior developer whenever I use the term "dHTML". I know the term is dated, but it's descriptive of what the task is: changing rendered markup on the client. I cringe whenever I see the term "Ajax" applied to client side animation or form validation where no asynchronous request is being made. "Web 2.0" is used a lot as well, but that term can be applied to everything from a business model to a visual style.
What term is used to describe the combination of client-side scripting and CSS effects that may or may not be accompanied by asynchronous server requests? | [DOM Scripting/Manipulation](http://en.wikipedia.org/wiki/DOM_scripting) | It's DHTML.
* It's not AJAX; there is no necessity to do stuff asynchronously or with XML to manipulate the DOM.
* It's not HTML; that's static markup.
* It's not Javascript; Javascript is a language that doesn't necessarily have to have anything to do with HTML.
* It's not JQuery; that's a framework and whole different ball of wax. | What do you call DHTML these days? | [
"",
"javascript",
"ajax",
"terminology",
"dhtml",
""
] |
I understand that this may be construed as one of those "what's your preference" questions, but I really want to know why you would choose one of the following methods over the other.
Suppose you had a *super complex* class, such as:
```
class CDoSomthing {
public:
CDoSomthing::CDoSomthing(char *sUserName, char *sPassword)
{
//Do somthing...
}
CDoSomthing::~CDoSomthing()
{
//Do somthing...
}
};
```
How should I declare a local instance within a global function?
```
int main(void)
{
CDoSomthing *pDoSomthing = new CDoSomthing("UserName", "Password");
//Do somthing...
delete pDoSomthing;
}
```
-- or --
```
int main(void)
{
CDoSomthing DoSomthing("UserName", "Password");
//Do somthing...
return 0;
}
``` | Prefer local variables, unless you need the object's lifetime to extend beyond the current block. (Local variables are the second option). It's just easier than worrying about memory management.
P.S. If you need a pointer, because you need it to pass to another function, just use the address-of operator:
```
SomeFunction(&DoSomthing);
``` | There are two main considerations when you declare a variable on the stack vs. in the heap - lifetime control and resource management.
Allocating on the stack works really well when you have tight control over the lifetime of the object. That means you are not going to pass a pointer or a reference of that object to code outside of the scope of the local function. This means, no out parameters, no COM calls, no new threads. Quite a lot of limitations, but you get the object cleaned up properly for you on normal or exceptional exit from the current scope (Though, you might want to read up on stack unwinding rules with virtual destructors). The biggest drawback of the stack allocation - the stack is usually limited to 4K or 8K, so you might want to be careful what you put on it.
Allocating on the heap on the other hand would require you to cleanup the instance manually. That also means that you have a lot of freedom how to control the lifetime of the instance. You need to do this in two scenarios: a) you are going to pass that object out of scope; or b) the object is too big and allocating it on the stack could cause stack overflow.
BTW, a nice compromise between these two is allocating the object on the heap and allocating a smart pointer to it on the stack. This ensures that you are not wasting precious stack memory, while still getting the automatic cleanup on scope exit. | Why should/shouldn't I use the "new" operator to instantiate a class, and why? | [
"",
"c++",
"class",
"instantiation",
""
] |
I'm aware that you can get session variables using `request.session['variable_name']`, but there doesn't seem to be a way to grab the session id(key) as a variable in a similar way. Is this documented anywhere? I can't find it. | ```
request.session.session_key
```
Note the key will only exist if there is a session, no key, no session. You can use this to test if a session exists. If you want to create a session, call create. | Django sessions save their key in a cookie. At least its middleware extracts it like this:
```
from django.conf import settings
session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
``` | How to find out the request.session sessionid and use it as a variable in Django? | [
"",
"python",
"django",
"session",
"sessionid",
"django-sessions",
""
] |
I am using the jQuery plugin [Cross Slide](http://www.gruppo4.com/~tobia/cross-slide.shtml). My page is working fine in Chrome and Firefox. But in Internet Explorer 7, I get:
> Debug error as Object expected on line 1:
> $(document).ready(function() {
> $('#image').crossSlide({sleep:4,fade:1},[{src:'images/1.jpg'},{src:'images/2.jpg'}]);
> });
How can I fix the bug for Internet Explorer 8 and Internet Explorer 7? | Could you provide more code or even better, a working page that reproduces the problem? That little piece of code looks fine so far...
By the way, the "on line 1" tells you absolutely nothing in IE, don't trust it. | I had the same problem, you just have to delete the comma after the last picture you point to. This should work in IE.
Greets | jQuery plugin Cross Slide and Internet Explorer | [
"",
"javascript",
"jquery",
"internet-explorer-7",
"cross-browser",
""
] |
When I define a Django form class similar to this:
```
def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
```
It expands to HTML that looks like this:
```
<form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
```
I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?
**[Edit]**
Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)
I'd like to avoid overriding \_html\_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in \_html\_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible.
CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.
Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer.
**[Edit]**
Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy. | Here's what I ended up doing. I wrote a custom template stringfilter to switch the tags around. Now, my template code looks like this:
```
{% load pretty_forms %}
<form action="." method="POST">
{{ form.as_p|pretty_checkbox }}
<p><input type="submit" value="Submit"></p>
</form>
```
The only difference from a plain Django template is the addition of the {% load %} template tag and the **pretty\_checkbox** filter.
Here's a functional but ugly implementation of **pretty\_checkbox** - this code doesn't have any error handling, it assumes that the Django generated attributes are formatted in a very specific way, and it would be a bad idea to use anything like this in your code:
```
from django import template
from django.template.defaultfilters import stringfilter
import logging
register=template.Library()
@register.filter(name='pretty_checkbox')
@stringfilter
def pretty_checkbox(value):
# Iterate over the HTML fragment, extract <label> and <input> tags, and
# switch the order of the pairs where the input type is "checkbox".
scratch = value
output = ''
try:
while True:
ls = scratch.find('<label')
if ls > -1:
le = scratch.find('</label>')
ins = scratch.find('<input')
ine = scratch.find('/>', ins)
# Check whether we're dealing with a checkbox:
if scratch[ins:ine+2].find(' type="checkbox" ')>-1:
# Switch the tags
output += scratch[:ls]
output += scratch[ins:ine+2]
output += scratch[ls:le-1]+scratch[le:le+8]
else:
output += scratch[:ine+2]
scratch = scratch[ine+2:]
else:
output += scratch
break
except:
logging.error("pretty_checkbox caught an exception")
return output
```
**pretty\_checkbox** scans its string argument, finds pairs of <label> and <input> tags, and switches them around if the <input> tag's type is "checkbox". It also strips the last character of the label, which happens to be the ':' character.
Advantages:
1. No futzing with CSS.
2. The markup ends up looking the way it's supposed to.
3. I didn't hack Django internals.
4. The template is nice, compact and idiomatic.
Disadvantages:
1. The filter code needs to be tested for exciting values of the labels and input field names.
2. There's probably something somewhere out there that does it better and faster.
3. More work than I planned on doing on a Saturday. | Here's a solution I've come up with (Django v1.1):
```
{% load myfilters %}
[...]
{% for field in form %}
[...]
{% if field.field.widget|is_checkbox %}
{{ field }}{{ field.label_tag }}
{% else %}
{{ field.label_tag }}{{ field }}
{% endif %}
[...]
{% endfor %}
```
You'll need to create a custom template tag (in this example in a "myfilters.py" file) containing something like this:
```
from django import template
from django.forms.fields import CheckboxInput
register = template.Library()
@register.filter(name='is_checkbox')
def is_checkbox(value):
return isinstance(value, CheckboxInput)
```
More info on custom template tags available [here](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/).
**Edit**: in the spirit of asker's own answer:
Advantages:
1. No futzing with CSS.
2. The markup ends up looking the way it's supposed to.
3. I didn't hack Django internals. (but had to look at quite a bunch)
4. The template is nice, compact and idiomatic.
5. The filter code plays nice regardless of the exact values of the labels and input field names.
Disadvantages:
1. There's probably something somewhere out there that does it better and faster.
2. Unlikely that the client will be willing to pay for all the time spent on this just to move the label to the right... | How do I create a Django form that displays a checkbox label to the right of the checkbox? | [
"",
"python",
"django",
"checkbox",
""
] |
Is it OK to use `==` on enums in Java, or do I need to use `.equals()`? In my testing, `==` always works, but I'm not sure if I'm guaranteed of that. In particular, there is no `.clone()` method on an enum, so I don't know if it is possible to get an enum for which `.equals()` would return a different value than `==`.
For example, is this OK:
```
public int round(RoundingMode roundingMode) {
if(roundingMode == RoundingMode.HALF_UP) {
//do something
} else if (roundingMode == RoundingMode.HALF_EVEN) {
//do something
}
//etc
}
```
Or do I need to write it this way:
```
public int round(RoundingMode roundingMode) {
if(roundingMode.equals(RoundingMode.HALF_UP)) {
//do something
} else if (roundingMode.equals(RoundingMode.HALF_EVEN)) {
//do something
}
//etc
}
``` | Just my 2 cents: Here is the code for Enum.java, as published by Sun, and part of the JDK:
```
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable {
// [...]
/**
* Returns true if the specified object is equal to this
* enum constant.
*
* @param other the object to be compared for equality with this object.
* @return true if the specified object is equal to this
* enum constant.
*/
public final boolean equals(Object other) {
return this==other;
}
}
``` | Yes, == is fine - there's guaranteed to be just a single reference for each value.
However, there's a better way of writing your round method:
```
public int round(RoundingMode roundingMode) {
switch (roundingMode) {
case HALF_UP:
//do something
break;
case HALF_EVEN:
//do something
break;
// etc
}
}
```
An even *better* way of doing it is to put the functionality within the enum itself, so you could just call `roundingMode.round(someValue)`. This gets to the heart of Java enums - they're *object-oriented* enums, unlike the "named values" found elsewhere.
EDIT: The spec isn't very clear, but [section 8.9](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9) states:
> The body of an enum type may contain
> enum constants. An enum constant
> defines an instance of the enum type.
> An enum type has no instances other
> than those defined by its enum
> constants. | Is it OK to use == on enums in Java? | [
"",
"java",
"syntax",
"enums",
""
] |
Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?
If not, what would you recommend as "the Python equivalent of Hibernate"? | The short answer is: no, you can't use the Django ORM separately from Django.
The long answer is: yes, you can if you are willing to load large parts of Django along with it. For example, the database connection that is used by Django is opened when a request to Django occurs. This happens when a signal is sent so you could ostensibly send this signal to open the connection without using the specific request mechanism. Also, you'd need to setup the various applications and settings for the Django project.
Ultimately, it probably isn't worth your time. [SQL Alchemy](http://www.sqlalchemy.org/) is a relatively well known Python ORM, which is actually more powerful than Django's anyway since it supports multiple database connections and connection pooling and other good stuff.
---
**Edit:** in response to James' criticism elsewhere, I will clarify what I described in my original post. While it is gratifying that a major Django contributor has called me out, I still think I'm right :)
First off, consider what needs to be done to use Django's ORM separate from any other part. You use one of the [methods](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) described by James for doing a basic setup of Django. But a number of these methods don't allow for using the `syncdb` command, which is required to create the tables for your models. A settings.py file is needed for this, with variables not just for `DATABASE_*`, but also `INSTALLED_APPLICATIONS` with the correct paths to all models.py files.
It is possible to roll your own solution to use `syncdb` without a settings.py, but it requires some advanced knowledge of Django. Of course, you don't need to use `syncdb`; the tables can be created independently of the models. But it is an aspect of the ORM that is not available unless you put some effort into setup.
Secondly, consider how you would create your queries to the DB with the standard `Model.objects.filter()` call. If this is done as part of a view, it's very simple: construct the `QuerySet` and view the instances. For example:
```
tag_query = Tag.objects.filter( name='stackoverflow' )
if( tag_query.count() > 0 ):
tag = tag_query[0]
tag.name = 'stackoverflowed'
tag.save()
```
Nice, simple and clean. Now, without the crutch of Django's request/response chaining system, you need to initialise the database connection, make the query, then close the connection. So the above example becomes:
```
from django.db import reset_queries, close_connection, _rollback_on_exception
reset_queries()
try:
tag_query = Tag.objects.filter( name='stackoverflow' )
if( tag_query.count() > 0 ):
tag = tag_query[0]
tag.name = 'stackoverflowed'
tag.save()
except:
_rollback_on_exception()
finally:
close_connection()
```
The database connection management can also be done via Django signals. All of the above is defined in [django/db/**init**.py](http://code.djangoproject.com/browser/django/trunk/django/db/__init__.py). Other ORMs also have this sort of connection management, but you don't need to dig into their source to find out how to do it. SQL Alchemy's connection management system is documented in the [tutorials](http://www.sqlalchemy.org/docs/05/ormtutorial.html) and elsewhere.
Finally, you need to keep in mind that the database connection object is local to the current thread at all times, which may or may not limit you depending on your requirements. If your application is not stateless, like Django, but persistent, you may hit threading issues.
In conclusion, it is a matter of opinion. In my opinion, both the limitations of, and the setup required for, Django's ORM separate from the framework is too much of a liability. There are perfectly viable dedicated ORM solutions available elsewhere that are designed for library usage. Django's is not.
Don't think that all of the above shows I dislike Django and all it's workings, I really do like Django a lot! But I'm realistic about what it's capabilities are and being an ORM library is not one of them.
P.S. Multiple database connection support is being [worked](http://code.djangoproject.com/ticket/1142) on. But it's not there now. | If you like Django's ORM, it's perfectly simple to use it "standalone"; I've [written up several techniques for using parts of Django outside of a web context](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/), and you're free to use any of them (or roll your own).
Shane above seems to be a bit misinformed on this and a few other points -- for example, Django *can* do multiple different databases, it just doesn't *default* to that (you need to do a custom manager on the models which use something other than the "main" DB, something that's not too hard and there are recipes floating around for it). It's true that Django itself doesn't do connection management/connection pooling, but personally I've always used external tools for that anyway (e.g., `pgpool`, which rocks harder than anything built in to an ORM ever could).
I'd suggest spending some time reading up and possibly trying a few likely Google searches (e.g., the post I linked you to comes up as the top result for "standalone Django script") to get a feel for what will actually best suit your needs and tastes -- it may be Django's ORM isn't right for you, and you shouldn't use it if it isn't, but unfortunately there's a lot of misinformation out there which muddies the waters.
**Editing to respond to Shane:**
Again, you seem to be misinformed: SQLAlchemy needs to be configured (i.e., told what DB to use, how to connect, etc.) before you can run queries with it, so how is the fact that Django needs similar configuration (accomplished via your choice of methods -- you **do not** need to have a full Django settings file) any disadvantage?
As for multiple DB support, you seem to be confused: the support is there at a low level. The query object -- not `QuerySet`, but the underlying `Query` object it will execute knows what DB it's connecting to, and accepts a DB connection as one of its initialization arguments. Telling one model to use one DB and another model to use another is as simple as setting up one method on a manager which passes the right connection info down into the `Query`. True, there's no higher-level API for this, but that's not the same as "no support" and not the same as "requires custom code" (unless you'd argue that configuring multiple DBs explicitly in SQLAlchemy, required if you want multiple DBs, is also "custom code").
As for whether you end up *indirectly* using things that aren't in `django.db`, well, so what? The fact that `django.db` imports bits of, say, `django.utils` because there are data structures and other bits of code which are useful for more than just an ORM is fine as far as I'm personally concerned; one might as well complain if something has external dependencies or makes use of standard Python libraries instead of being 100% self-contained. | Using only the DB part of Django | [
"",
"python",
"django",
"orm",
""
] |
I currently have this type of code:
```
private void FillObject(Object MainObject, Foo Arg1, Bar Arg2)
{
if (MainObject is SomeClassType1)
{
SomeClassType1 HelpObject = (SomeClassType1)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
else if (MainObject is SomeClassType2)
{
SomeClassType2 HelpObject = (SomeClassType2)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
}
```
Assuming that SomeClassType1 and SomeClassType2 have the same set of properties that I want to assign (although they may differ in other ones), is it possible to dynamically cast MainObject to the appropriate type and then assign the value, without duplicating the code?
This is what I would like to see in the end:
```
private void FillObject(Object MainObject, Foo Arg1, Bar Arg2)
{
Type DynamicType = null;
if (MainObject is SomeClassType1)
{
DynamicType = typeof(SomeClassType1);
}
else if (MainObject is SomeClassType2)
{
DynamicType = typeof(SomeClassType2);
}
DynamicType HelpObject = (DynamicType)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
```
And obviously C# complains about not being able to find DynamicType:
> The type or namespace name 'DynamicType' could not be found (are you missing a using directive or an assembly reference?)
Is something like this possible in C# 2.0? If it's more messy than my current code, than I see no point in doing this, but I'm very interested to find out. Thanks!
EDIT: Just to clarify, I perfectly understand that implementing an interface is the most appropriate and probably correct solution. That said, I'm more interested in seeing how to I could do it without implementing an interface. Thanks for great replies! | It looks like both of the types you care about implement the same two properties. In that case, what you want to do is define an interface for those properties:
```
public interface IMyInterface
{
public Foo Property1 {get; set;}
public Bar Property2 {get;set;}
}
```
Then, make sure each of your classes tell the compiler that they implement that new interface. Finally, use a generic method with a type argument that is constrained to that interace:
```
private void FillObject<T>(T MainObject, Foo Arg1, Bar Arg2)
where T : IMyInterface
{
MainObject.Property1 = Arg1;
MainObject.Property2 = Arg2;
}
```
Note that even with the extra code to declare the interface, these snippets still end up shorter than either one of the snippets you posted in the question, and this code is much easier to extend if the number of types you care about increases. | Essentially what you're doing here is writing a switch statement based on the type fo the object. There is no inherently good way to do this other than your first example (which is tedious at best).
I wrote a small framework for switching on types that makes the syntax a bit more concise. It allows you to write code like the following.
```
TypeSwitch.Do(
sender,
TypeSwitch.Case<Button>(
() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case<CheckBox>(
x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(
() => textBox1.Text = "Not sure what is hovered over"));
```
Blog Post: <http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx> | C#: Casting types dynamically | [
"",
"c#",
"dynamic-cast",
""
] |
I have a "searchable pdf" aka 'image files with invisible but selectable text'. (When this file is opened in Acrobat, I am alerted "You are viewing this document in PDF/A mode.")
I need to extract the bounding rectangle of each word in this document. Any suggested toolkits and the methods for accessing the "invisi-text" words' bounding-boxes?
I would prefer tools in java, but appreciate any suggestions. | Acrobat's javascript libraries look to be the most straightforward, especially:
```
getPageNthWordQuads
```
which works on a "searchable pdf".
Would be nice if the acrobat javascript library was available as java calls... | Check out the iText library: <http://www.lowagie.com/iText/> | toolkit & methods for extracting text bounds in 'searchable pdf' | [
"",
"java",
"pdf",
""
] |
I am trying to use cywin to get some linux code building on a win32 machine.
I get the following VS.net 2003 error in ym compiler:
"c:\cygwin\usr\include\sys\_types.h(15): error C2144: syntax error : '\_\_int64' should be preceded by ';'
"
and
c:\cygwin\usr\include\sys\_types.h(15): error C2501: '**extension**' : missing storage-class or type specifiers
The code line is
```
__extension__ typedef long long _off64_t;
```
Obviously I am missing something here but I have never used cygwin before and this is killing me.
I want to be able to at least compile my CPP files on my win32 machine for a few reasons.
(this is just the first two errors of hundreds it looks like)
thanks,
tim
EDIT:
the simple workaround I have chosen as the answer - though I do understand that is not as complete or as desirable as using gcc to compile...
This is a quick and dirty compilation so that I can use my familiar tools before trying to integrate with linux machines. (oh the joys of cross-platform development)
I've voted up each of those answers so far and appreciate the help) | I think that the **extension** macro may not be defined. You may want to do a text search on your cygwin header dir to see if this is the case. If so, make sure that you header search path is defined correctly, etc. | I could be wrong, but the cygwin headers could be made specifically for compiling using the cygwin gcc, not visual studio. Try compiling using gcc/g++ in cygwin.
EDIT: I may be possible to use Visual Studio, this page (for another project) seems to imply that you can compile something with vc++/cygwin. <http://opensg.vrsource.org/trac/wiki/BuildVS2005Cygwin>.
You may want to check it out.
EDIT2: Also See: <http://www.coin-or.org/OS/documentation/node14.html>
EDIT3: I would guess that the best coarse of action would be to make sure that visual studio searches the standard windows paths first. So if there is a system `<sys/types.h>`, that may be preferred over the cygwin version. | cygwin compile error in sys/_types.h | [
"",
"c++",
"cygwin",
""
] |
I have a PHP file at my server root.. **index.php** .. which [`include`](http://www.php.net/include/)'s .. DIR/**main.php**
Now .. DIR/**main.php** .. has relative links to many nearby files.
All the relative links are broken.
---
Any way I can change the relative-URL base path **for links?**
... so the included content of DIR/**main.php** has all its links to **friend1.php** changed to **DIR/friend1.php**.
---
Edit: This in NOT about include's, this is about CHANGING ahref links en-masse. | The **base** tag in html works for relative links. See [w3schools](http://www.w3schools.com/TAGS/tag_base.asp) for an example on how to use it. | Assuming main.php is a mix of HTML and PHP then when you output a link you'll need to include a prefix:
```
<a href="<?php echo $web_root; ?>relative/path/">relative link</a>
```
Where $web\_root is your root path ('DIR'). Probably a good idea to define it in a separate include file so you only have to define it once for all your scripts. | Change relative link paths for included content in PHP | [
"",
"php",
"url",
"include",
"relative-path",
""
] |
I have PHP 5.1.6 (cli) installed and whenever the GET query string is more than 128 characters it fails with HTTP 406 Not Acceptable error. Any suggestions how I can fix this so can use more than 128 characters? POST is not an option.
The error is being returned by the server so don't think it's browser issue.
And the reason I think it's PHP and not Apache is because it works fine with an HTML file.
```
GET /test.php?phptestof129characterstring-NEW-WOVEN-FENCE-PANELS-GARDEN_W0QQitemZ200303392512QQihZ010QQcategoryZ139954QQtcZphotoQQcmdZViewItem
HTTP/1.1
Host: *****
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: agent_name=Tim
HTTP/1.1 406 Not Acceptable
Date: Tue, 03 Feb 2009 12:05:33 GMT
Server: Apache/2.2.3 (Red Hat)
X-Powered-By: PHP/5.1.6
Content-Length: 0
Connection: close
Content-Type: text/html
```
---
```
GET /test.html?phptestof129characterstring-NEW-WOVEN-FENCE-PANELS-GARDEN_W0QQitemZ200303392512QQihZ010QQcategoryZ139954QQtcZphotoQQcmdZViewItem
HTTP/1.1
Host: *****
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: agent_name=Tim
HTTP/1.1 200 OK
Date: Tue, 03 Feb 2009 12:18:19 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Fri, 19 Dec 2008 15:01:17 GMT
ETag: "156960d-221-94be8940"
Accept-Ranges: bytes
Content-Length: 545
Connection: close
Content-Type: text/html
``` | Have found answer thanks to comment from Ben.
Although this generates 406 error:
test.php?129+characters
This works fine:
test.php?data=129+characters
So my guess is that in the first instance PHP is attempting to use the 129 characters as name in $\_GET array whereas the second example has only 4 characters for the name and the rest is assigned as value, so array must have 128 character limit for index name. | Do you have [mod\_security](http://www.modsecurity.org/) enabled on your webserver? It sounds like something it would do. If so, you may be able to disable locally inside your `<VirtualHost>` block or with an .htaccess file for v1.x
```
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
```
Version 2.x has different configuration syntax:
```
<IfModule mod_security2.c>
SecRuleEngine Off
</IfModule>
```
That's a bit of a brute force approach, you may want to read the [documentation](http://www.modsecurity.org/documentation/modsecurity-apache/2.5.7/html-multipage/) to see how you might allow particular URIs to pass through. See also [Handling False Positives and Creating Custom Rules](http://www.modsecurity.org/blog/archives/2007/02/handling_false.html) | PHP Query String Limit | [
"",
"php",
"apache",
""
] |
I'm curious to see how other developers go about testing their web sites. PHP specifically in my case, but this probably spans multiple languages. I've been working on a site for over a year now, and I'd really like to automate a lot of the regression testing I do between versions.
This specific site is in CodeIgniter, so I have some tests for my models. I'd like to move beyond just testing those though. However, this is an issue even non-MVC developers have had to tackle I'm sure.
**Edit:** I think the functionality that would satisfy a lot of my test desires is the ability to assert that paramters have a specific value at the end of the script processing. In my case a lot of logic is in the controller, and that's the main area I'd like to test. | For actual unit testing without testing the UI, you should just test the functions in the model. Most of your functionality should be in there anyways.
You might want to have a look at [Selenium](http://seleniumhq.org/) for testing the UI of your site. It can record your actions and play them back, or you can edit the scripting directly.
[](https://i.stack.imgur.com/nm6EH.gif)
(source: [seleniumhq.org](http://seleniumhq.org/projects/ide/selenium-ide.gif)) | Have you tried [Fitnesse](http://fitnesse.org/) ?
It helps on creating Acceptance tests. They are specially useful for websites, which doing this kind of tests are a pain.
There are a couple of videos from unclebob inside the webpage too. The good thing is that Fitnesse is not restricted for website testing, so your knowledge about using it can be used with other apps too.
The project I'm working on is a Desktop APP written in c++ that uses Fitnesse tests.
But if you meant unit testing the models (which I think you didn't), they can be create using the phpunit lib. I think the ZEND framework has a similar lib for that. | Unit Testing a Website | [
"",
"php",
"unit-testing",
"codeigniter",
""
] |
What exactly do I need delegates, and threads for? | Delegates act as the logical (but safe) equivalent to function-pointers; they allow you to talk about an operation in an abstract way. The typical example of this is events, but I'm going to use a more "functional programming" example: searching in a list:
```
List<Person> people = ...
Person fred = people.Find( x => x.Name == "Fred");
Console.WriteLine(fred.Id);
```
The "lambda" here is essentially an instance of a delegate - a delegate of type `Predicate<Person>` - i.e. "given a person, is something true or false". Using delegates allows very flexible code - i.e. the `List<T>.Find` method can find all sorts of things based on the delegate that the caller passes in.
In this way, they act largely like a 1-method interface - but much more succinctly. | [Delegates](http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx): Basically, a delegate is a method to reference a method. It's like a pointer to a method which you can set it to different methods that match its signature and use it to pass the reference to that method around.
[Thread](http://en.wikipedia.org/wiki/Thread_(computer_science)) is a sequentual stream of instructions that execute one after another to complete a computation. You can have different threads running simultaneously to accomplish a specific task. A thread runs on a single logical processor. | C# Delegates and Threads! | [
"",
"c#",
""
] |
At my company we develop applications that run on the JVM (Java EE and Grails) as well as .NET applications (ASP.NET and client/server Forms apps). In your experience, when have you recommended one over the other to a customer?
I asked this question incorrectly [here](https://stackoverflow.com/questions/512321/java-vs-net) but I think the fact that I put an initial list got it closed. I'm looking for things like if you want to do X then Y is better because of Z. I think this would be a valuable resource/case-study to the community. For example, I tried doing some USB hardware stuff in Java/Windows and would not recommend it again because of the lack of good libraries in Java. | If you want tight integration with Windows, other Microsoft products, or COM components, .NET is better because it's designed with such integration in mind.
If you need to provide or consume XML Web Services, then .NET is better because the tools for that kind of development are more consistent and easy to use.
If you want to develop or deploy on non-Windows platforms, then target the JVM because there are stable implementations of it available for most platforms. | Don't bother explaining technology, explain solution and its benefits. | Explaining .NET or Java to a client | [
"",
"java",
".net",
""
] |
I have an ASP.NET web page with a databound RadioButtonList. I do not know how many radio buttons will be rendered at design time. I need to determine the SelectedValue on the client via JavaScript. I've tried the following without much luck:
```
var reasonCode = document.getElementById("RadioButtonList1");
var answer = reasonCode.SelectedValue;
```
("answer" is being returned as "undefined")
Please forgive my JavaScript ignorance, but what am I doing wrong?
Thanks in advance. | ASP.NET renders a table and a bunch of other mark-up around the actual radio inputs. The following should work:-
```
var list = document.getElementById("radios"); //Client ID of the radiolist
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
selected = inputs[i];
break;
}
}
if (selected) {
alert(selected.value);
}
``` | Try this to get the selected value from the RadioButtonList.
```
var selectedvalue = $('#<%= yourRadioButtonList.ClientID %> input:checked').val()
``` | How can I determine the SelectedValue of a RadioButtonList in JavaScript? | [
"",
"asp.net",
"javascript",
"radio-button",
""
] |
Forum; I am a newbie working out a bit of code. I would like to know the best way to use separate .cs files containing other classes and functions. As an example of a basic function would would like to click on a clear button and have it clear all fields on a form. The code is split up into three .cs files. Main.cs, MainForm.Designer.cs and btClear.cs.
MainForm.Designer.cs contains the designers automatically created code including the Clear Button, and the text boxes I would like to clear.
I would like to have the code to clear the text boxes contained in btClear.cs. I understand it would be easy to simply to place this code in MainForm.Designer.cs however I would like to use this as a template in order to use separate .cs files as a standard practice.
Can someone give me an example of how to do this please? | The way most .net programmers would do it is:
* Leave all your code inside `MainForm.cs`, but declare a new method for separating the code that does the clearing.
I always leave in the event handler method (the one VS generates when you double-click the button) code to change the mouse cursor (in case the code I'm calling takes a couple of seconds or more to run) and catch all unhandled exceptions, and put my logic in a separate private method:
```
partial class MainForm : Form // this is MainForm.cs
{
// This is the method VS generates when you double-click the button
private void clearButton_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
ClearForm();
}
catch(Exception ex)
{
// ... have here code to log the exception to a file
// and/or showing a message box to the user
}
finally
{
this.Cursor = Cursors.Default;
}
}
private void ClearForm()
{
// clear all your controls here
myTextBox.Clear();
myComboBox.SelectedIndex = 0;
// etc...
}
}
```
In my opinion, if you want to follow the conventional way of doing things in .net, you should stick with this first example.
Moving code out of the form .cs files is recommended **when the code is not part of the form logic**, for example, data access code or business logic. It this case I don't think that clearing the form controls qualifies as business logic. It is just part of the form code and should stay in the `MainForm.cs`.
But if you really want to put the `ClearForm` method in another .cs file, you could create a new class and move the `ClearForm` method there. You would also need to change the Modifiers property of each control to Public so your new class can have access to them from outside MainForm. Something like this:
```
public class FormCleaner // this is FormCleaner.cs
{
public void ClearForm(MainForm form)
{
// clear all your controls here
form.myTextBox.Clear();
form.myComboBox.SelectedIndex = 0;
// etc...
}
}
```
You would have to change the main form code to:
```
partial class MainForm : Form // this is MainForm.cs
{
// This is the method VS generates when you double-click the button
private void clearButton_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
FormCleaner cleaner = new FormCleaner();
cleaner.ClearForm(this);
}
catch(Exception ex)
{
// ... have here code to log the exception to a file
// and/or showing a message box to the user
}
finally
{
this.Cursor = Cursors.Default;
}
}
}
```
But note that your `FormCleaner` class would have to know about your `MainForm` class in order to know how to clear each of the controls of the form, or you would need to come up with a generic algorithm that is able to loop through the `Controls` collection of any form to clean them:
```
public class FormCleaner // this is FormCleaner.cs
{
// 'generic' form cleaner
public void ClearForm(Form form)
{
foreach(Control control on form.Controls)
{
// this will probably not work ok, because also
// static controls like Labels will have their text removed.
control.Text = "";
}
}
}
```
And as others have said, `MainForm.Designer.cs` is machine-generated and you should never put your own code there. | You can use a [`partial`](http://msdn.microsoft.com/en-us/library/wa80x488.aspx) class for your `MainForm` class, since that's already being done in `MainForm.cs` and `MainForm.Designer.cs`.
`btnClear.cs`
```
public partial class MainForm
{
private void clearForm(object sender, EventArgs e)
{
// ...
}
}
```
And register for the event in `MainForm.cs` or `MainForm.Designer.cs`
```
this.btnClear.click += clearForm;
```
Edit:
If you want a generic way of doing it, you could set the [`Tag`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag.aspx) property of your controls to be the default value. And with an extension method, you could do something like `formGroup.Reset();`
```
using System.Windows.Forms;
public class ControlExtensions
{
public void Reset(this Control control)
{
if (control.Tag != null)
{
if (control is TextBoxBase && control.Tag is string)
{
control.Text = control.Tag as string;
}
else if (control is CheckBox && control.Tag is bool)
{
control.Checked = control.Tag as bool;
}
// etc
}
foreach (Control child in control.Children)
child.Reset();
}
}
``` | How to use separate .cs files in C#? | [
"",
"c#",
""
] |
Okay, maybe this is because I've been coding for over 24 hours and my eyes are glazing over, but I'm stumped here. Why does this happen:
```
<?php
session_start();
$tmp = "index";
echo "A: " . $_SESSION['page_loaded']['index']; // returns 1
echo "B: " . $_SESSION['page_loaded'][$tmp]; // is set, but is empty
?>
```
I feel like I'm missing something very basic here but I don't know what. | I have a feeling you haven't actually cut and pasted that code? Is there anything you're leaving out? | Where are you setting the following?
```
$_SESSION['page_loaded'][$tmp];
```
The following works:
```
<?php
session_start();
$tmp = "index";
$_SESSION["page_loaded"][$tmp] = "Foo";
echo "A: " . $_SESSION['page_loaded']["index"]; // foo
echo "<br/>";
echo "B: " . $_SESSION['page_loaded'][$tmp]; // foo
?>
``` | PHP Session variable is set, but PHP doesn't see it. Very strange | [
"",
"php",
"session",
"session-variables",
""
] |
I'd like to know what people's best practices are for removing unused code. Personally I'm a fan of deleting (not just commenting) anything that's not currently being used. But I'm unsure of how far to go.
Take this as an example (although I'm interested in general discussion). In my project I have a dozen or so UserControls. For a feature that later got canned, I implemented a couple of methods and properties on one of the UserControls. The additional code is not specific to the feature, but needed to support it. It may potentially be useful later on.
* Should I remove the code because we're not using it at the moment, and the less code there is the easier it is to read? The problem with this is, how do future developers know that this work has already been done?
* Or should I keep it there, so another developer can find it easily if they need to use it later (they're not going to think to go through source control to see if anyone had done this and deleted it)?
* Or is there another option?
The same applies to UserControls not currently being used. Should I remove them or keep them?
**Edit:** It goes without saying (or I thought it would) that we're using source control. | The first thing to remember is **all your code should be in source control**.
With that in mind, of course you want to delete obsolete code rather than just comment it out. Commented code blocks of any length are *dangerous*, for at least two reasons:
1. There's a tendency to assume that the comments were maintained with the rest of the code. This isn't true and can lead to problems like bug regressions.
2. It's easy to miss an uncommented closing curly brace (for example) in the middle of a long block.
The deleted code is still available if you really need it, but it's no longer cluttering up your working copies. If you're *really* concerned about discoverability for the old code you can leave a comment indicating code was removed and the revision number you need to find it. At one line, that's a lot better than what the actual code block was using. It's also much clearer this code has been allowed to lapse, and for exactly how long. | If you are using a source control system, deleting the code is my preferred option.
It won't get in your way when working with the current code, and you'll always have the code in the repository if you ever need it again. | Best Practices for Removing Unused Code | [
"",
"c#",
""
] |
Hi I'm pretty new to Stack Overflow so I hope that I'm doing this correctly and that someone out there has the answer I need.
I'm currently coding a program in Java with Eclipse IDE an my question is this:
I need a snippet of code that does the following
It's supposed to get a .TXT file containing text and from that .TXT file
count the number of rows and print it,
count the number of words and print it,
count the number of characters and print it.
And finally make a list of the top 10 words used and print that.
Allt the printing is done to system outprintln
I'm pretty new to Java and am having some difficulties.
Anyone out there who can provide me with these lines of code or that knows where i can find them? I want to study the code provided that's how I learn best=)
Thanks to all
Didnt find the edit button sorry...
I Added this to my question:
Hehe it´s an assignment but not a homework assignment ok i see well i could provide what i've done so far, i think im pretty close but it´s not working for me. Is there anything i have missed?
```
// Class Tip
import java.io.*;
import java.util.*;
class Tip
{
public static void main(String [] args) throws Exception
{
String root = System.getProperty("user.dir");
InputStream is = new FileInputStream( root + "\\tip.txt" );
Scanner scan = new Scanner( is );
String tempString = "";
int lines = 0;
int words = 0;
Vector<Integer> wordLength = new Vector<Integer>();
int avarageWordLength = 0;
while(scan.hasNextLine() == true)
{
tempString = scan.nextLine();
lines++;
}
is.close();
is = new FileInputStream( root );
scan = new Scanner( is );
while(scan.hasNext() == true)
{
tempString = scan.next();
wordLength.add(tempString.length());
words++;
}
for(Integer i : wordLength)
{
avarageWordLength += i;
}
avarageWordLength /= wordLength.size();
System.out.println("Lines : " + lines);
System.out.println("Words : " + words);
System.out.println("Words Avarage Length : " + avarageWordLength);
is.close();
}
}
``` | This sounds a bit too much like a homework assignment to warrant providing a full answer, but I'll give you some tips on where to look in the Java API:
FileReader and BufferedReader for getting the data in.
Collections API for storing your data
A custom data structure for storing your list of words and occurence count
Comparator or Comparable for sorting your data structure to get the top 10 list out
Once you've started work and have something functioning and need specific help, come back here with specific questions and then we'll do our best to help you.
Good luck! | Typing "java count words example" into [Google](http://www.google.com.au/search?hl=en&q=java+count+words+example&meta=) came up with a few suggestions.
This [link](http://www.java.happycodings.com/Beginners_Lab_Assignments/code7.html) looks to be a decent starting point.
This simple example from [here](http://blog.taragana.com/index.php/archive/simplifying-java-how-to-count-the-number-of-words-in-a-string-using-java-one-liner/) might also give you some ideas:
```
public class WordCount
{
public static void main(String args[])
{
System.out.println(java.util.regex.Pattern.compile("[\\w]+").split(args[0].trim()).length);
}
}
``` | Counting lines, words, characters and top ten words? | [
"",
"java",
"count",
""
] |
I'm a C# developer working with either Windows Forms or WPF.
Sometimes I have to deal with unmanaged code, which I don't like.
I think that the main reason why I dislike this is ignorance. I don't know the underlying Win API.
I think that I'm not the only person who has negative feelings against unmanaged Windows code.
Question: Should a Windows Forms\WPF developer start digging the WinAPI in order to be a better developer?
Sorry for not being very clear..
Thank you. | I think that looking at the WinAPI could be counter-productive to WPF, since it has a largely re-written stack. Even more so if you are looking at WPF in parallel to Silverlight.
It might be marginally useful **occasionally** for winforms - but I've been writing winforms for years, and have only once or twice needed lower level details. Every time I did, "google" did the job fine; or more recently, stackoverflow ;-p
If you were writing raw windows directly, then maybe. But that would be unusual for C#. | No.
The WPF is a rewrite (almost) of the current Win32 api. It is not like WPF is built over Win32.
People learning Win32 were new to windows programming - it was required to learn the basic structure of a windows app: the winmain, messageloop, windows class etc. Now with WPF, you will be well off mastering similar concepts in WPF (and also concentrate in understanding XAML).
There will be lot of conceptually similar topics with win32, but you can just stay within WPF. You won't gain anything learning win32 for wpf. | I'm a Windows Forms\WPF developer. Should I read Petzold's Programming Windows (the C language one) book? | [
"",
"c#",
"winforms",
"winapi",
""
] |
In Python, I've seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his [Python Design Patterns](http://www.lecturefox.com/blog/python-design-patterns-by-alex-martelli) talk. I've seen this pattern used in libraries for dependency injection, like [pycontainer](http://pypi.python.org/pypi/PyContainer/0.4).
One problem that I've run into is that when I have to interface with code that uses the
[isinstance anti-pattern](https://stackoverflow.com/questions/576988/python-specific-antipatterns/577848#577848), this pattern fails because the holding/wrapping object fails the `isinstance` test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., [simple\_decorator](http://wiki.python.org/moin/PythonDecoratorLibrary) or Michele Simionato's [decorator](http://pypi.python.org/pypi/decorator)).
A qualification: I'm not asserting that all `isinstance` usage is inappropriate; several answers make good points about this. That said, it should be recognized that `isinstance` usage poses significant limitations on object interactions---it forces *inheritance* to be the source of polymorphism, rather than *behavior*.
There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from [pycontainer](http://pypi.python.org/pypi/PyContainer/0.4)). Let's say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don't---think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:
```
class Foo(object):
def bar():
print 'We\'re out of Red Leicester.'
class LogWrapped(object):
def __init__(self, wrapped):
self.wrapped = wrapped
def __getattr__(self, name):
attr = getattr(self.wrapped, name)
if not callable(attr):
return attr
else:
def fun(*args, **kwargs):
print 'Calling ', name
attr(*args, **kwargs)
print 'Called ', name
return fun
class FooFactory(object):
def get_foo(with_logging = False):
if not with_logging:
return Foo()
else:
return LogWrapped(Foo())
foo_fact = FooFactory()
my_foo = foo_fact.get_foo(True)
isinstance(my_foo, Foo) # False!
```
There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:
* We don't want to touch the Foo class. Assume we're writing framework code that could be used by clients we don't know about yet.
* The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo---as much as possible---to any other client code expecting a Foo. Hence the desire to work around `isinstance`.
* Yes, I know that I don't need the factory class (preemptively defending myself here). | If the library code you depend on uses `isinstance` and relies on inheritance why not follow this route? If you cannot change the library then it is probably best to stay consistend with it.
I also think that there are legitimate uses for `isinstance`, and with the introduction of [abstract base classes](http://www.python.org/dev/peps/pep-3119/) in 2.6 this has been officially acknowledged. There are situations where `isinstance` really is the right solution, as opposed to duck typing with `hasattr` or using exceptions.
Some dirty options if for some reason you really don't want to use inheritance:
* You could modify only the class instances by using instance methods. With `new.instancemethod` you create the wrapper methods for your instance, which then calls the original method defined in the original class. This seems to be the only option which neither modifies the original class nor defines new classes.
If you can modify the class at runtime there are many options:
* Use a runtime mixin, i.e. just add a class to the `__base__` attribute of your class. But this is more used for adding specific functionality, not for indiscriminate wrapping where you don't know what need to be wrapped.
* The options in Dave's answer (class decorators in Python >= 2.6 or Metaclasses).
Edit: For your specific example I guess only the first option works. But I would still consider the alternative of creating a `LogFoo` or chosing an altogether different solution for something specific like logging. | One thing to keep in mind is that you don't necessarily have to *use* anything in a base class if you go the inheritance route. You can make a stub class to inherit from that doesn't add any concrete implementation. I've done something like this several times:
```
class Message(object):
pass
class ClassToBeWrapped(object):
#...
class MessageWithConcreteImplementation(Message):
def __init__(self):
self.x = ClassToBeWrapped()
#... add concrete implementation here
x = MessageWithConcreteImplementation()
isinstance(x, Message)
```
If you need to inherit from other things, I suppose you could run into some problems with multiple inheritance, but this should be fairly minimal if you don't provide any concrete implementation.
> One problem that I've run into is that when I have to interface with code that uses the isinstance anti-pattern
I agree that isinstance is to be avoided if possible, but I'm not sure I'd call it an antipattern. There are some valid reasons to use isinstance. For instance, there are some message passing frameworks that use this to define messages. For example, if you get a class that inherits from Shutdown, it's time for a subsystem to shut down. | Wrapping objects to extend/add functionality while working around isinstance | [
"",
"python",
"design-patterns",
""
] |
I have a table with 10 columns as col\_1,col\_2,.... col\_10. I want to write a select statement that will select a value of one of the row and from one of these 10 columns. I have a variable that will decide which column to select from. Can such query be written where the column name is dynamically decided from a variable. | Since I don't have enough details, I can't give code. Instead, I'll explain.
Declare a string variable, something like:
```
declare @sql varchar(5000)
```
Set that variable to be the completed SQL string you want (as a string, and not actually querying... so you embed the row-name you want using string concatenation).
Then call: `exec(@sql)`
All set. | Yes, using a CASE statement:
```
SELECT CASE @MyVariable
WHEN 1 THEN [Col_1]
WHEN 2 THEN [Col_2]
...
WHEN 10 THEN [Col_10]
END
```
Whether this is a good idea is another question entirely. You should use better names than Col\_1, Col\_2, etc.
You could also use a string substitution method, as suggested by others. However, that is an option of last resort because it can open up your code to sql injection attacks. | Dynamic Query in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
Database structure:
```
Clubs: ID, ClubName
Teams: ID, TeamName, ClubID
Players: ID, Name
Registrations: PlayerID, TeamID, Start_date, End_date, SeasonID
```
Clubs own several teams. Players may get registered into several teams (inside same club or into different club) during one year.
I have to generate a query to list all players that have been registered into DIFFERENT CLUBS during one season. So if player swapped teams that were owned by the same club then it doesn't count.
My attempts so far:
```
SELECT
c.short_name,
p.surname,
r.start_date,
r.end_date,
(select count(r2.id) from ejl_registration as r2
where r2.player_id=r.player_id and r2.season=r.season) as counter
FROM
ejl_registration AS r
left Join ejl_players AS p ON p.id = r.player_id
left Join ejl_teams AS t ON r.team_id = t.id
left Join ejl_clubs AS c ON t.club_id = c.id
WHERE
r.season = '2008'
having counter >1
```
I can't figure out how to count and show only different clubs... (It's getting too late for clear thinking). I use MySQL.
Report should be like: Player name, Club name, Start\_date, End\_date | This is a second try at this answer, simplifying it to merely count the distinct clubs, not report a list of club names.
```
SELECT p.surname, r.start_date, r.end_date, COUNT(DISTINCT c.id) AS counter
FROM ejl_players p
JOIN ejl_registration r ON (r.player_id = p.id)
JOIN ejl_teams t ON (r.team_id = t.id)
JOIN ejl_clubs c ON (t.club_id = c.id)
WHERE r.season = '2008'
GROUP BY p.id
HAVING counter > 1;
```
Note that since you're using MySQL, you can be pretty flexible with respect to columns in the select-list not matching columns in the GROUP BY clause. Other brands of RDBMS are more strict about the Single-Value Rule.
There's no reason to use a LEFT JOIN as in your example.
---
Okay, here's the first version of the query:
You have a chain of relationships like the following:
```
club1 <-- team1 <-- reg1 --> player <-- reg2 --> team2 --> club2
```
Such that club1 must not be the same as club2.
```
SELECT p.surname,
CONCAT_WS(',', GROUP_CONCAT(DISTINCT t1.team_name),
GROUP_CONCAT(DISTINCT t2.team_name)) AS teams,
CONCAT_WS(',', GROUP_CONCAT(DISTINCT c1.short_name),
GROUP_CONCAT(DISTINCT c2.short_name)) AS clubs
FROM ejl_players p
-- Find a club where this player is registered
JOIN ejl_registration r1 ON (r1.player_id = p.id)
JOIN ejl_teams t1 ON (r1.team_id = t1.id)
JOIN ejl_clubs c1 ON (t1.club_id = c1.id)
-- Now find another club where this player is registered in the same season
JOIN ejl_registration r2 ON (r2.player_id = p.id AND r1.season = r2.season)
JOIN ejl_teams t2 ON (r2.team_id = t2.id)
JOIN ejl_clubs c2 ON (t2.club_id = c2.id)
-- But the two clubs must not be the same (use < to prevent duplicates)
WHERE c1.id < c2.id
GROUP BY p.id;
``` | Here's a list of players for one season.
```
SELECT sub.PlayerId
FROM
(
SELECT
r.PlayerId,
(SELECT t.ClubID FROM Teams t WHERE r.TeamID = t.ID) as ClubID
FROM Registrations r
WHERE r.Season = '2008'
) as sub
GROUP BY PlayerId
HAVING COUNT(DISTINCT sub.ClubID) > 1
```
Here's a list of players and seasons, for all seasons.
```
SELECT PlayerId, Season
FROM
(
SELECT
r.PlayerId,
r.Season,
(SELECT t.ClubID FROM Teams t WHERE r.TeamID = t.ID) as ClubID
FROM Registrations r
) as sub
GROUP BY PlayerId, Season
HAVING COUNT(DISTINCT sub.ClubID) > 1
```
By the way, this works in MS SQL. | How to count number of different items in SQL | [
"",
"sql",
""
] |
In the example below, can anyone tell me how to make "slow response when clicked" respond more quickly without modifying appendContent()? I'm wondering if there's a way to place cheap operations before more expensive ones, and make sure the cheap ones actually get carried out quickly.
```
<div id="draw">slow response when clicked</div>
<div style="overflow: auto; height: 300px; border:solid 1px grey" id="content"></div>
<script language="javascript">
var clickLink = document.getElementById("draw");
var contentDiv = document.getElementById("content")
function appendContent(){
contentDiv.innerHTML = contentDiv.innerHTML + "hello ";
}
clickLink.onclick = function(){
clickLink.style.color = "red";
for (var i = 0; i < 1500; i++){
appendContent();
}
};
</script>
``` | The mechanism for feedback should be different for the duration the user has to wait. Less than 0.1 seconds and a user will not notice.
Between 1 and 10 seconds you can simply display a symbol such as an animated gif of some sort that indicates your app is processing. See <http://www.ajaxload.info/>
I use a div with an ID "processing" and style it with a spinner and use the following jquery code to show and hide it before and after the process.
```
function showProcessing(){
$("#processing").fadeIn("fast");
}
function hideProcessing(){
$("#processing").fadeOut("fast");
}
```
Beyond 10 seconds it would be ideal to provide an estimate of processing time.
See [Response Time Overview](http://www.useit.com/papers/responsetime.html) for the source of these numbers.
The following code immediately changes the link colour to red and calls the append method a fraction of a second later. Essentially is allows the browser to execute a separate thread before getting hung up in a loop. The timeout may need to be adjusted depending on the browser. Check out Neil Mix's [Threading in JavaScript 1.7](http://www.neilmix.com/2007/02/07/threading-in-javascript-17/) if you need to relinquish control in a more generic manner.
```
function startAppend(){
for (var i = 0; i < 1500; i++){
appendContent();
}
}
clickLink.onclick = function(){
clickLink.style.color = "red";
setTimeout('startAppend()', 10)
};
``` | If what you want to do is simply provide the user with some feedback so they know something's happening, you may try putting an animated gif - a loading circle or something, next to the button and disabling the button itself, then setting things back to normal after the redraw is complete. | What are some techniques for improving UI responsiveness? | [
"",
"javascript",
"performance",
"dom",
"user-experience",
""
] |
I'm building a C++ Linux application and I need to log its activity. What are the existing Linux facilities to create logs? What would you recommend? | How about [log4cxx](http://logging.apache.org/log4cxx/index.html)? | The historic one is syslog(3). From C:
```
#include <syslog.h>
openlog("myprogram", LOG_PID, LOG_LOCAL0);
syslog(LOG_INFO, "data %d %s", 3, "example");
```
From Perl:
```
use Sys::Syslog;
openlog "myprogram", "pid", "local0";
syslog 'info', 'data %d %s', 3, 'example';
```
From shell:
```
logger -p local0.info -t myprogram -- data 3 example
```
The syslogd daemon can be configured to put log files in different places (files, tty, other machines) depending on the facility (here `LOG_LOCAL0`) and the priority (here `LOG_INFO`) | Recommendations for logger in Linux application | [
"",
"c++",
"linux",
"logging",
""
] |
Isn't that an inconsistent behavior? (PHP 5.2.6)
```
<?php
$a = new SimpleXMLElement('<a/>');
$a->addAttribute('b', 'One & Two');
//$a->addChild('c', 'Three & Four'); -- results in "unterminated entity reference" warning!
$a->addChild('c', 'Three & Four');
$a->d = 'Five & Six';
print($a->asXML());
```
Renders:
```
<?xml version="1.0"?>
<a b="One & Two">
<c>Three & Four</c>
<d>Five & Six</d>
</a>
```
At bugs.php.net they reject all the submissions about that, saying it's a feature. Why could that possibly be? BTW, there's nothing in the docs about that discrepancy of escaping text values by SimpleXMLElement.
Can anyone convince me it's the best API design decision possible? | Just to make sure we're on the same page, you have three situations.
1. The insertion of an ampersand into an attribute using addAttribute
2. The insertion of an ampersand into an element using addChild
3. The insertion of an ampersand into an element by property overloading
It's the discrepancy between 2 and 3 that has you flummoxed. Why does addChild not automatically escape the ampersand, whereas adding a property to the object and setting its value **does** escape the ampersand automatically?
Based on my instincts, and buoyed by [this bug](http://bugs.php.net/bug.php?id=45253&edit=1), this was a deliberate design decision. The property overloading ($a->d = 'Five & Six';) is intended to be the "escape ampersands for me" way of doing things. The addChild method is meant to be "add exactly what I tell you to add" method. So, whichever behavior you need, SimpleXML can accommodate you.
Let's say you had a database of text where all the ampersands were already escaped. The auto-escaping wouldn't work for you here. That's where you'd use addChild. Or lets say you needed to insert an entity in your document
```
$a = simplexml_load_string('<root></root>');
$a->b = 'This is a non-breaking space ';
$a->addChild('c','This is a non-breaking space ');
print $a->asXML();
```
That's what the PHP Developer in that bug is advocating. The behavior of addChild is meant to provide a "less simple, more robust" support when you need to insert a ampersand into the document without it being escaped.
Of course, this does leave us with the first situation I mentioned, the addAttribute method. The addAttribute method **does** escape ampersands. So, we might now state the inconsistency as
1. The addAttribute method escapes ampersands
2. The addChild method **does not** escape ampersands
3. This behavior is somewhat inconsistent. It's reasonable that a user would expect the **methods** on SimpleXML to escape things in a consistent way
This then exposes the real problem with the SimpleXML api. The ideal situation here would be
1. Property Overloading on Element Objects escapes ampersands
2. Property Overloading on Attribute Objects escapes ampersands
3. The addChild method does not escape ampersands
4. the addAttribute method does not escape ampersands
This is impossible though, because SimpleXML has no concept of an Attribute Object. The addAttribute method is (appears to be?) the only way to add an attribute. Because of that, it turns out (seems?) SimpleXML in incapable of creating attributes with entities.
All of this reveals the paradox of **Simple**XML. The idea behind this API was to provide a simple way of interacting with something that turns out to be complex.
The team could have added a SimpleXMLAttribute Object, but that's an added layer of complexity. If you want a multiple object hierarchy, use DomDoument.
The team could have added flags to the addAttribute and addChild methods, but flags make the API more complex.
The real lesson here? Maybe it's that simple is hard, and simple on a deadline is even harder. I don't know if this was the case or not, but with SimpleXML it seems like someone started with a simple idea (use property overloading to make the creation of XML documents easy), and then adjusted as the problems/feature requests came in.
Actually, I think the real lesson here is to just use JSON ;) | This is my solution, especially this solves adding several childs with the same tag-name
```
$job->addChild('industrycode')->{0} = $entry1;
$job->addChild('industrycode')->{0} = $entry2;
$job->addChild('industrycode')->{0} = $entry3;
``` | Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute | [
"",
"php",
"xml",
""
] |
I have a base class that inherits List<> which has multiple classes derived from it.
I want to create a method that can add items to any class that has inherited from this base class, is this possible ?
**pseudo code:**
```
public class BaseList<T> : List<T> where T: baseItem
{
}
public BaseList<T> AddItems<T>(int someArg) where T: new(), baseItem
{
BaseList<T> temp = new BaseList<T>();
temp.add(new T());
temp.add(new T());
return temp;
}
public class MyDerived: BaseList<SomeClass>
{
}
```
Then to call this code:
```
MyDerived temp = (MyDerived)AddItems();
```
is something like this possible ? I can't figure out the correct syntax | Do you really need to derive from `List<T>` instead of using composition?
It sounds like you want a static method in a non-generic type:
```
public static TList CreateList<TList,TItem>(int someArg)
where TList : BaseList<TItem>, new()
where TItem : baseItem, new()
{
TList temp = new TList();
temp.Add(new TItem());
temp.Add(new TItem());
return temp;
}
```
It doesn't seem particularly nice though... perhaps if you explained the purpose of this, we could come up with a better idea. | I can't really understand your question but I have run into this problem before. If you ran into the same problem as me: you don't know the <T> parameter at compile time. Fortunately, this is a cynch to solve using interfaces - you can create a stronger type binding by using a non-generic interface.
```
class Program
{
static void Main(string[] args)
{
IAddBaseItem addItem = new DerivedList();
BaseItem item = new DerivedItem();
IgnorantMethod(addItem, item);
}
static void IgnorantMethod(IAddBaseItem list, BaseItem item)
{
list.Add(item);
}
}
class BaseItem
{
}
class BaseList<T> : List<T>, IAddBaseItem
{
#region IAddBaseItem Members
void IAddBaseItem.Add(BaseItem item)
{
if (item == null)
Add(item);
else
{
T typedItem = item as T;
// If the 'as' operation fails the item isn't
// of type T.
if (typedItem == null)
throw new ArgumentOutOfRangeException("T", "Wrong type");
Add(typedItem);
}
}
#endregion
}
class DerivedList : BaseList<DerivedItem>
{
}
class DerivedItem : BaseItem
{
}
interface IAddBaseItem
{
void Add(BaseItem item);
}
```
As I said, this is my best guess as to what you are asking. | How to handle this c# generics problem? | [
"",
"c#",
"generics",
""
] |
Does anybody know how to move the keyboard caret in a textbox to a particular position?
For example, if a text-box (e.g. input element, not text-area) has 50 characters in it and I want to position the caret before character 20, how would I go about it?
This is in differentiation from this question: [jQuery Set Cursor Position in Text Area](https://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area) , which requires jQuery. | Excerpted from Josh Stodola's *[Setting keyboard caret Position in a Textbox or TextArea with Javascript](https://web.archive.org/web/20090210030453/http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx)*
A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:
```
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
```
The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.
Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).
An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:
```
function addLoadEvent(func) {
if(typeof window.onload != 'function') {
window.onload = func;
}
else {
if(func) {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad)
oldLoad();
func();
}
}
}
}
// The setCaretPosition function belongs right here!
function setTextAreasOnFocus() {
/***
* This function will force the keyboard caret to be positioned
* at the end of all textareas when they receive focus.
*/
var textAreas = document.getElementsByTagName('textarea');
for(var i = 0; i < textAreas.length; i++) {
textAreas[i].onfocus = function() {
setCaretPosition(this.id, this.value.length);
}
}
textAreas = null;
}
addLoadEvent(setTextAreasOnFocus);
``` | The link in the answer is broken, this one should work (all credits go to [blog.vishalon.net](http://blog.vishalon.net/javascript-getting-and-setting-caret-position-in-textarea)):
[http://snipplr.com/view/5144/getset-cursor-in-html-textarea/](http://snipplr.com/view/5144/getset-cursor-in-html-textarea/ "Get/set cursor in html area")
In case the code gets lost again, here are the two main functions:
```
function doGetCaretPosition(ctrl)
{
var CaretPos = 0;
if (ctrl.selectionStart || ctrl.selectionStart == 0)
{// Standard.
CaretPos = ctrl.selectionStart;
}
else if (document.selection)
{// Legacy IE
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
return (CaretPos);
}
function setCaretPosition(ctrl,pos)
{
if (ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange)
{
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
``` | Set keyboard caret position in html textbox | [
"",
"javascript",
"textbox",
"input",
""
] |
I need to insert UIElements into a Grid that does not get generated until runtime. More specifically, I need to add UIElements to the RowDefinitions I create after I determine how many elements need to be displayed. Is there a way to contorl the Grid.Row and Grid.Column and Grid.RowSpan like in XAML for objects in C#? If I am going about this wrong, please let me know. I can not use a StackPanel (I am creating an dynamic accordian panel and it messes with the animation).
Right now what happens is that I generate the number of RowDefinitions at runtime and add UIElements as the children. This isn't working, all the UIElements end up in the first row layered on top of each other.
Here is an example of what I am trying:
```
public partial class Page : UserControl
{
string[] _names = new string[] { "one", "two", "three" };
public Page()
{
InitializeComponent();
BuildGrid();
}
public void BuildGrid()
{
LayoutRoot.ShowGridLines = true;
foreach (string s in _names)
{
LayoutRoot.RowDefinitions.Add(new RowDefinition());
LayoutRoot.Children.Add(new Button());
}
}
}
```
Thanks! | Apart from the Grid not really being the right tool for the job (a ListView would be) you need to tell the Button which row it belongs to.
```
public void BuildGrid()
{
LayoutRoot.ShowGridLines = true;
int rowIndex = 0;
foreach (string s in _names)
{
LayoutRoot.RowDefinitions.Add(new RowDefinition());
var btn = new Button()
LayoutRoot.Children.Add(btn);
Grid.SetRow(btn, rowIndex);
rowIndex += 1;
}
}
``` | The best way to do what you're looking for is to follow the pattern below:
Page.xaml:
```
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<data:DataGrid x:Name="DataGridTest" />
</Grid>
</UserControl>
```
Page.xaml.cs:
```
public partial class Page : UserControl
{
string[] _names = new string[] { "one", "two", "three" };
public Page()
{
InitializeComponent();
BuildGrid();
}
public void BuildGrid()
{
DataGridTest.ItemsSource = _names;
}
}
```
This builds the rows dynamically from the contents of your string array. In future an even better way would be to use an [ObservableCollection](http://msdn.microsoft.com/en-us/library/ms668604(VS.95).aspx) where T implements [INotifyPropertyChanged](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(VS.95).aspx). This will notify the DataGrid to update it's rows if you remove or add an item from the collection and also when properties of T change.
To further customize the UIElements used to display things you can use a [DataGridTemplateColumn](http://msdn.microsoft.com/en-us/library/system.windows.controls.datagridtemplatecolumn(VS.95).aspx):
```
<data:DataGridTemplateColumn Header="Symbol">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding PutNameOfPropertyHere}" />
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
``` | Dynamic Grid In Silverlight 2 using C# | [
"",
"c#",
"silverlight-2.0",
""
] |
Bleh; Knowing how to ask the question is always the hardest so I explain a little more.
I'm using CAxWindow to create an IE window internally and passing in the URL via the string class argument:
```
CAxWindow wnd;
m_hwndWebBrowser = wnd.Create(m_hWnd, rect, m_URI, WS_CHILD|WS_DISABLED, 0);
```
It's part of an automated utility for anyone to get images from their "internal" javascript-based apps; the issue is that some people try getting images from their apps that have lots of errors; The errors fire off the IE debug window and my capture utility sits waiting for input.
Initially I thought I could disable the debugging ability via IE in windows however the process that Apache runs in and hence my App is via the SYSTEM account; not sure how I'd change the debugging options without hacking the registry. | I found some projects on CodeProject that does something similar...
<http://www.codeproject.com/KB/shell/popupblocker.aspx?fid=15235&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=51&select=646577>
<http://www.codeproject.com/KB/shell/popupblocker2.aspx?df=100&forumid=15709&fr=51&select=548519#xx548519xx>
And also an MSDN article regarding web browser customisation:
<http://msdn.microsoft.com/en-us/library/aa770041(VS.85).aspx>
I found that what I was after was two interfaces called: IOleCommandTarget and IDocHostUIHandler; I needed to override the UI handler and interpret the Script exception messages and respond with a "false" to indicate I didn't care about the error;
Unfortunately I spent waaaaay too much time getting my head back into COM and trying to get their god awful system set up that I wasn't able to finish it and after a discussion with my bos regarding spending more time trying to get this working or just disabling debug in IE; we chose the later.
3 Words; I hate COM :-p (the smilie doesn't count)
I think the path I was on would solve the issue I had and my response can contribute as an "answer"; sorry if it's not what you're looking for. | Link your app with [detours](http://research.microsoft.com/en-us/projects/detours/) or other API hooking library, hook `RegQueryValue` function from advapi32 and return "yes" when IE queries value for registry key `"HKCU\Software\Microsoft\Internet Explorer\Main\Disable Script Debugger"`. | Disable IE script debugging via IE control | [
"",
"c++",
"debugging",
"internet-explorer",
"screen-capture",
""
] |
Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see [F1.com](http://www.formula1.com/)). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
---
### Current code:
```
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
```
---
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: **Warning: Invalid argument supplied for foreach()** this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
```
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
```
Do I need to add mysql\_fetch\_array somewhere to set the array up? | I would just iterate through the results and apply a css class to the first entry:
```
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
``` | It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
```
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
``` | When listing information from a database using php and mysql how would you make the first row look different to the rest? | [
"",
"php",
"mysql",
"database",
"arrays",
"resultset",
""
] |
I have a bit of a problem here:
```
#foreach($image in $command.lessonLearned.images)
Image: $image.fileName <input type="submit" onclick="submitForm();setImageToRemove($image.id);setAction('removeImage');" value="REMOVE"/><br/>
#end
```
$image.id inside the onclick event is not evaluated as a velocity variable. How do I make it write out the variable content and not just the variable name? | Are you sure that $image.id has a value? Was it $image.ID or $image.getID() that you should have typed? | Try replacing `$image.id` with `${image.id}` | Velocity and JavaScript | [
"",
"javascript",
"variables",
"velocity",
""
] |
How can I show a systray tooltip longer than 63 chars? NotifyIcon.Text has a 63 chars limit, but I've seen that VNC Server has a longer tooltip.
How can I do what VNC Server does? | Actually, it is a bug in the property setter for the Text property. The P/Invoke declaration for NOTIFYICONDATA inside Windows Forms uses the 128 char limit. You can hack around it with Reflection:
```
using System;
using System.Windows.Forms;
using System.Reflection;
public class Fixes {
public static void SetNotifyIconText(NotifyIcon ni, string text) {
if (text.Length >= 128) throw new ArgumentOutOfRangeException("Text limited to 127 characters");
Type t = typeof(NotifyIcon);
BindingFlags hidden = BindingFlags.NonPublic | BindingFlags.Instance;
t.GetField("text", hidden).SetValue(ni, text);
if ((bool)t.GetField("added", hidden).GetValue(ni))
t.GetMethod("UpdateIcon", hidden).Invoke(ni, new object[] { true });
}
}
``` | From the MSDN documentation on the Win32 [NOTIFYICONDATA structure](http://msdn.microsoft.com/en-us/library/bb773352(VS.85).aspx):
> **szTip**
>
> A null-terminated string that specifies the text for a standard
> ToolTip. It can have a maximum of 64
> characters, including the terminating
> null character.
>
> For Windows 2000 (Shell32.dll version 5.0) and later, szTip can have
> a maximum of 128 characters, including
> the terminating null character.
It looks like the Windows Forms library supports the lowest common denominator here. | How can I show a systray tooltip longer than 63 chars? | [
"",
"c#",
"winforms",
"systray",
""
] |
Our win32 applications (written in C++) have been around for over 10 years, and haven't been updated to follow "good practices" in terms of where they keep files. The application defaults to installing in the "C:\AppName" folder, and keeps application-generated files, configuration files, downloaded files, and saved user documents in subfolders of that folder.
Presumably, it's "best practices" to default to installing under "c:\Program Files\AppName" nowadays. But if we do that, where should we keep the rest of our files? Starting from Vista, writing to the program files folder is problematic, and there seem to be a million other places that you can put different files, and I'm confused.
Is there a reference somewhere for what goes where?
---
**Edit: To expand on questions people have asked so far:**
---
I'm familiar with the SHGetFolderPath function, but there are lots and lots of options that you can get from it, and I can't find a resource that says "Here is exactly what each of these options is used for, and when you might want to use it".
Up until now, we've done the "All files, including saved user files, under one folder" thing, and it's worked fine - but not when people want to install the app under the Program Files folder. For some reason, the virtualization monkeying around that Vista does isn't working for our application; if we're going to be making changes anyway, we might as well make an effort to do things the "right" way, since we don't want to have to change it again in 12 months time.
---
**Further question:**
---
We include some "sample" documents with our app, which we update every now and again. Is it appropriate to install them into My Documents, if we'll be overwriting them every few months? Or is My Documents assumed to be totally safe for users to mess around in?
If we can't install them to My Documents, where should we put them so that users can see them easily? | > Presumably, it's "best practices" to default to installing under "c:\Program Files\AppName"
Close, but not quite. Users can configure the name of the Program Files folder and may not even have a C: drive. Instead, install to the `%ProgramFiles%\AppName` environment variable folder.
Note you should assume you only have read access to this folder after the installation has finished. For program data files where you might need write access, use `%AppData%\AppName`.
Finally, are you sure yours is the only app with that name? If you're not 100% certain of that, you might want to include your company name in there as well.
The mechanisms you use to retrieve those variables will vary depending on your programming platform. It normally comes down to the `SHGetFolderPath()` Win32 method in the end, but different platforms like Java or .Net may provide simpler abstractions as well. | Some guidelines are in this Knowledge Base article: [How to write a Windows XP Application that stores user and application data in the correct location by using Visual C++](http://support.microsoft.com/kb/310294). Also, if you search MSDN for *Windows Logo Program* you will find documentation regarding what an app needs to do to be truly compliant.
[SHGetKnownFolderPath](http://msdn.microsoft.com/en-us/library/bb762188(VS.85).aspx) can get you the directories you need. If backwards compatibility with XP and earlier is required, use the deprecated [SHGetFolderPath](http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx)
Having said that, if you app came with documentation that said "everything used by this app is in this directory" I would *love* it ;) | Where should my win32 program keep its files? | [
"",
"c++",
"winapi",
""
] |
I'm trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Python? | Actually, `pywin32` and `ctypes` seem to be an overkill for this simple task. [`tkinter`](https://docs.python.org/3/library/tkinter.html) is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.
If all you need is to put some text to system clipboard, this will do it:
```
from tkinter import Tk # in Python 2, use "Tkinter" instead
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
```
And that's all, no need to mess around with platform-specific third-party libraries.
If you are using Python 2, replace `tkinter` with `Tkinter`. | I didn't have a solution, just a workaround.
Windows Vista onwards has an inbuilt command called `clip` that takes the output of a command from command line and puts it into the clipboard. For example, `ipconfig | clip`.
So I made a function with the `os` module which takes a string and adds it to the clipboard using the inbuilt Windows solution.
```
import os
def addToClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)
# Example
addToClipBoard('penny lane')
# Penny Lane is now in your ears, eyes, and clipboard.
```
As previously noted in the comments however, one downside to this approach is that the `echo` command automatically adds a newline to the end of your text. To avoid this you can use a modified version of the command:
```
def addToClipBoard(text):
command = 'echo | set /p nul=' + text.strip() + '| clip'
os.system(command)
```
If you are using Windows XP it will work just following the steps in *[Copy and paste from Windows XP Pro's command prompt straight to the Clipboard](http://www.techrepublic.com/blog/window-on-windows/copy-and-paste-from-windows-xp-pros-command-prompt-straight-to-the-clipboard/521)*. | How do I copy a string to the clipboard? | [
"",
"python",
"windows",
"interop",
"clipboard",
""
] |
Let's say you're running an UPDATE statement on a table, but the information you're putting into this base table is from some other auxiliary table. Normally, you would JOIN the data and not expect the rows in the UPDATE statement's FROM clause to multiply, maintaining that one new row maps to one old row in the base table.
But I was wondering what would happen if your JOIN table was ambiguous somehow, like you couldn't account for each base entity mapping only to one joined entity. Or if you did something nonsensical like join to a base table to a table of its children and updated the base table using that information. How would it choose? Now there are multiple rows per one base table row.
I ran a statement like this in SQL Server 2005 and it seemed to be choosing the first row in each set. But that just seems wrong to me. Shouldn't it fire an error? Why is this desired behavior?
**Example code**
```
-- normal
-- categories are one-to-many bundles
update bundles_denormalized set category = c.description
from bundles_denormalized b
left join categories c
on b.category_id = c.id
-- ambiguous
-- bundles are one-to-many products
update bundles_denormalized set category = p.description
from bundles_denormalized b
left join products p
on b.id = p.bundle_id
``` | [From BOL on UPDATE](http://msdn.microsoft.com/en-us/library/ms177523(SQL.90).aspx)
> **Using UPDATE with the FROM Clause**
>
> The results of an UPDATE statement are
> undefined if the statement includes a
> FROM clause that is not specified in
> such a way that only one value is
> available for each column occurrence
> that is updated, that is if the UPDATE
> statement is not deterministic.
> For example, in the UPDATE statement
> in the following script, both rows in
> Table1 meet the qualifications of the
> FROM clause in the UPDATE statement;
> but it is undefined which row from
> Table1 is used to update the row in
> Table2.
>
> ```
> USE AdventureWorks;
> GO
> IF OBJECT_ID ('dbo.Table1', 'U') IS NOT NULL
> DROP TABLE dbo.Table1;
> GO
> IF OBJECT_ID ('dbo.Table2', 'U') IS NOT NULL
> DROP TABLE dbo.Table2;
> GO
> CREATE TABLE dbo.Table1
> (ColA int NOT NULL, ColB decimal(10,3) NOT NULL);
> GO
> CREATE TABLE dbo.Table2
> (ColA int PRIMARY KEY NOT NULL, ColB decimal(10,3) NOT NULL);
> GO
> INSERT INTO dbo.Table1 VALUES(1, 10.0);
> INSERT INTO dbo.Table1 VALUES(1, 20.0);
> INSERT INTO dbo.Table2 VALUES(1, 0.0);
> GO
> UPDATE dbo.Table2
> SET dbo.Table2.ColB = dbo.Table2.ColB + dbo.Table1.ColB
> FROM dbo.Table2
> INNER JOIN dbo.Table1
> ON (dbo.Table2.ColA = dbo.Table1.ColA);
> GO
> SELECT ColA, ColB
> FROM dbo.Table2;
> ```
In other words, it is a valid syntax and it is not going to throw an error or exception.
But at the same time you cannot be sure that the update value will be the first or the last record from your FROM clause as it is not defined. | Actually if I understand the question correctly it is updating the field multiple times, it is just that since there is only one record, so it ends up with only one value. Why doesn't it error? Because the syntax is correct and the database has not way of knowing what your intent was. Would you want to do this? Not normally, this is why you should do a select of your update before you run it to ensure the corret records are getting the correct values.
I usually write an update with a join this way:
```
update b
set category = p.description
--select b.category, p.description
from bundles_denormalized b
left join products p on b.id = p.bundle_id
```
I also would be wary of using a left join in an update as you will may get values changed to nulls. That's ok if that is what you wanted, but not if it isn't. | Why/how does this ambiguous UPDATE statement work? | [
"",
"sql",
"database",
"sql-server-2005",
"theory",
""
] |
I have the 3 following tables in a MySQL 4.x DB :
* hosts: *(300.000 records)*
+ id (UNSIGNED INT) PRIMARY KEY
+ name (VARCHAR 100)
* paths: *(6.000.000 records)*
+ id (UNSIGNED INT) PRIMARY KEY
+ name (VARCHAR 100)
* urls: *(7.000.000 records)*
+ host (UNSIGNED INT) PRIMARY KEY <--- links to hosts.id
+ path (UNSIGNED INT) PRIMARY KEY <--- links to paths.id
As you can see, the schema is really simple but the problem is the amount of data in these tables.
Here is the query I'm running :
```
SELECT CONCAT(H.name, P.name)
FROM hosts AS H
INNER JOIN urls as U ON H.id = U.host
INNER JOIN paths AS P ON U.path = P.id;
```
This query works perfectly fine, but takes 50 minutes to run. Does anyone have any idea about how I could speed up that query?
Thanks in advance.
Nicolas | For one thing I wouldn't do the CONCAT in the query. Do it outside.
But really you're query runs slowly because you're retrieving millions of rows. | Perhaps you should include a WHERE clause? Or do you really need ALL the data? | SQL query : inner joins optimization between big tables | [
"",
"sql",
"mysql",
"optimization",
"inner-join",
"bigtable",
""
] |
Can I return more than one item in a select? For instance I have a List of Fixtures (think football (or soccer for the yanks) fixtures). Each fixture contains a home and away team and a home and away score. I want to get all the teams that drew. I want to use something like
```
IEnumerable<Team> drew = from fixture in fixtures
where fixture.Played && (fixture.HomeScore == fixture.AwayScore)
select fixture.HomeTeam && fixture.AwayTeam;
```
I know this syntax is incorrect, what I don't know is if it's possible to do this. Would I need two queries and then concatenate them?
**Edit: this is really a learning thing so it's not critical to achieve this in any particular way. Basically, at this stage all i want is a list of teams that have drawn. An example usage might be that for a given list of fixtures i can find all of the drawn teams so that i could update their standings in a table by 1 point (3 for a win, 0 for a loss).** | I think you're looking for the Union method as follows:
```
IEnumerable<Team> drew = (from fixture in fixtures
where fixture.Played
&& (fixture.HomeScore == fixture.AwayScore)
select fixture.HomeTeam)
.Union(from fixture in fixtures
where fixture.Played
&& (fixture.HomeScore == fixture.AwayScore)
select fixture.AwayTeam);
``` | [101 LINQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx), namely Select - Anonymous Types 1
```
... select new { HomeTeam = fixture.HomeTeam, AwayTeam = fixture.AwayTeam };
``` | Can I select multiple objects in a Linq query | [
"",
"c#",
"linq",
"list",
""
] |
I am using a jQuery plugin to set cookies and when I use localhost for the domain it will not store the cookie.
Here is the plugin I am using with jQuery 1.2.6.
<http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/>
Below is the code that I am using. You can see it does not like localhost, and I am running it from a development web server on localhost. One detail is that I am running off port 4005 but that should not affect the domain, AFAIK.
```
$(function() {
console.log('Testing');
var one = $.cookie('Test.One');
var two = $.cookie('Test.Two');
var three = $.cookie('Test.Three');
console.log(['one', one]);
console.log(['two', two]);
console.log(['three', three]);
$('#div1').text(one);
$('#div2').text(two);
$('#div3').text(three);
$.cookie('Test.One', 'Test 1');
$.cookie('Test.Two', 'Test 2', { path: '/' });
$.cookie('Test.Three', 'Test 3', { path: '/', domain: 'localhost' });
});
``` | I had similar problem with setting cookies. Make up a domain name and add it to your hosts file as 127.0.0.1. Then run web application on that domain. | I think the domain name of a cookie must have exactly two dots (not counting the final dot after the TLD). So `.something.localhost` is okay, `.google.com` is okay, but `.localhost` or `google.com` is not. But a glance at [RFC 2965](https://www.rfc-editor.org/rfc/rfc2965) suggests that it's more complicated than that... you might want to read that document, especially section 3.3 (and/or its precursor, [RFC 2109](https://www.rfc-editor.org/rfc/rfc2109)). | Can I use localhost as the domain when setting an HTTP cookie? | [
"",
"javascript",
"jquery",
"cookies",
""
] |
Consider:
```
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//int[] val = { 0, 0};
int val;
if (textBox1.Text == "")
{
MessageBox.Show("Input any no");
}
else
{
val = Convert.ToInt32(textBox1.Text);
Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));
ot1.Start(val);
}
}
private static void ReadData(object state)
{
System.Windows.Forms.Application.Run();
}
void setTextboxText(int result)
{
if (this.InvokeRequired)
{
this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });
}
else
{
SetTextboxTextSafe(result);
}
}
void SetTextboxTextSafe(int result)
{
label1.Text = result.ToString();
}
private static void SumData(object state)
{
int result;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
delegate void IntDelegate(int result);
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
```
Why is this error occurring?
> An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int) | It looks like you are calling a non static member (a property or method, specifically `setTextboxText`) from a static method (specifically `SumData`). You will need to either:
1. If you can, make `setTextboxText` static:
`static void setTextboxText(int result)`
HOWEVER, in this case, setTextboxText REQUIRES access to instance variables, so cannot be static.
Instead do:
2. Call `setTextboxText` via a static singleton of Form1:
```
class Form1
{
public static Form1 It; // Singleton.
public Form1()
{
It = this;
}
private static void SumData(object state)
{
...
It.setTextboxText(result);
}
}
```
3. Create an instance of `Form1` within the calling method:
```
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
```
BUT that won't do what you want, if an instance of Form1 already exists.
Passing in an instance of `Form1` would be an option also.
4. Make the calling method a non-static instance method (of `Form1`):
```
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
```
More info about this error can be found [on MSDN](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0120). | For this case, where you want to get a Control of a Form and are receiving this error, then I have a little bypass for you.
Go to your Program.cs and change
```
Application.Run(new Form1());
```
to
```
public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);
```
Now you can access a control with
```
Program.form1.<Your control>
```
Also: Don't forget to set your Control-Access-Level to Public.
And yes I know, this answer does not fit to the question caller, but it fits to googlers who have this specific issue with controls. | CS0120: An object reference is required for the nonstatic field, method, or property 'foo' | [
"",
"c#",
""
] |
I'm trying to convert a time info I reveive as a UTC string to a timestamp using `std::mktime` in C++. My problem is that in `<ctime>` / `<time.h>` there is no function to convert to UTC; mktime will only return the timestamp as local time.
So I need to figure out the timezone offset and take it into account, but I can't find a platform-independent way that doesn't involve porting the whole code to `boost::date_time`. Is there some easy solution which I have overlooked? | mktime assumes that the date value is in the local time zone. Thus you can change the timezone environment variable beforehand (setenv) and get the UTC timezone.
[Windows tzset](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/tzset?view=msvc-160)
Can also try looking at various home-made [utc-mktimes, mktime-utcs, etc.](http://www.koders.com/c/fidB1A0A680FBCF84DDC534E66371053D726A5546EB.aspx?s=md5) | ```
timestamp = mktime(&tm) - _timezone;
```
or platform independent way:
```
timestamp = mktime(&tm) - timezone;
```
If you look [in the source of mktime()](https://web.archive.org/web/20130509004432/http://www.raspberryginger.com/jbailey/minix/html/mktime_8c-source.html) on line 00117, the time is converted to local time:
```
seconds += _timezone;
``` | std::mktime and timezone info | [
"",
"c++",
""
] |
Some of my forms show errors when i load them in the designer. This is because in their constructors they use system settings loaded from a configuration file. When the form is loaded in the designer it uses some random path and unsurprisingly the config file isn't there.
eg.
The configuration file C:\Documents and Settings\Rory\Local Settings\Application Data\Microsoft\VisualStudio\8.0\ProjectAssemblies\it3dtcgg01\PrioryShared.dll.config could not be found.
Is there some way I can deal with this so that the form displays correctly in the designer?
eg:
```
if (!inDesignerMode)
{
loadSettingsFromConfigFile();
}
```
UPDATE:
ok, I'm still getting this error. The composition is like this
* MyForm.cs
+ MyCustomControl.cs
In MyCustomControl's constructor I've put
```
if (!this.DesignMode)
{
// Get settings from config file <- this is where the error occurs
}
```
but it's on that line that I still get the error in the designer. What gives?
UPDATE: Worth noting [this link](http://msdn.microsoft.com/en-us/library/ms996457.aspx#) that describes how to debug design-time controls.
UPDATE: Control.DesignMode isn't set to true when called within the constructor ([MSDN](http://msdn.microsoft.com/en-us/library/ms996457.aspx)) of the object! So that sort of code should go in the onLoad. Alternatively you can use an approach like [this](http://devlicious.com/blogs/derik_whittaker/archive/2006/09/25/Determining-if-the-.Net-IDE-is-in-Design-Mode.aspx) | How about simply putting that logic into `OnLoad` instead, and check `DesignMode`?
```
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
if (!this.DesignMode)
{
/* do stuff */
}
}
``` | You should wrap the items in a check on `this.DesignMode`, which is set to `true` when in the designer, or move them to `OnLoad` or some other place that doesn't get called during designer use. | I get errors when viewing forms in the designer - how can i avoid this? | [
"",
"c#",
".net",
"winforms",
"windows-forms-designer",
""
] |
I'm looking for an easy way to find the process tree (as shown by tools like Process Explorer), in C# or other .NET language. It would also be useful to find the command-line arguments of another process (the StartInfo on System.Diagnostics.Process seems invalid for process other than the current process).
I think these things can only be done by invoking the win32 api, but I'd be happy to be proved wrong. | If you don't want to P/Invoke, you can grab the parent Id's with a performance counter:
```
foreach (var p in Process.GetProcesses())
{
var performanceCounter = new PerformanceCounter("Process", "Creating Process ID", p.ProcessName);
var parent = GetProcessIdIfStillRunning((int)performanceCounter.RawValue);
Console.WriteLine(" Process {0}(pid {1} was started by Process {2}(Pid {3})",
p.ProcessName, p.Id, parent.ProcessName, parent.ProcessId );
}
//Below is helper stuff to deal with exceptions from
//looking-up no-longer existing parent processes:
struct MyProcInfo
{
public int ProcessId;
public string ProcessName;
}
static MyProcInfo GetProcessIdIfStillRunning(int pid)
{
try
{
var p = Process.GetProcessById(pid);
return new MyProcInfo() { ProcessId = p.Id, ProcessName = p.ProcessName };
}
catch (ArgumentException)
{
return new MyProcInfo() { ProcessId = -1, ProcessName = "No-longer existant process" };
}
}
```
now just put it into whatever tree structure want and you are done. | You could also try to look into WMI (Win32\_Process class for example).
Here is an example to get the command line of a process by its process id:
```
using (var mos = new ManagementObjectSearcher(
"SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + pid))
{
foreach (var obj in mos.Get())
{
object data = obj.Properties["CommandLine"].Value;
if (data != null)
{
Console.WriteLine("{0}: commandline = {1}", pid, data.ToString());
}
}
}
}
}
```
I ripped this from some code I've recently written. For your purposes you might use other techniques (like getting multiple properties and/or processes at once). But you get the idea.
EDIT: The parent process id, which you'll need for building the tree is the "ParentProcessId" Property, for example.
I guess, however, using the Win32 API is faster. Note that not every functionality you required is rightly available there as well. For some stuff you would have resort to the (somewhat) unsupported NtQueryProcessInformation() function or others from NTDLL. | find the process tree in .NET | [
"",
"c#",
".net",
"windows",
"interop",
""
] |
A hobby project of mine is a Java web application. It's a simple web page with a form. The user fills out the form, submits, and is presented with some results.
The data is coming over a JDBC Connection. When the user submits, I validate the input, build a "CREATE ALIAS" statement, a "SELECT" statement, and a "DROP ALIAS" statement. I execute them and do whatever I need to do with the ResultSet from the query.
Due to an issue with the ALIASes on the particular database/JDBC combination I'm using, it's required that each time the query is run, these ALIASes are created with a unique name. I'm using an int to ensure this which gets incremented each and every time we go to the database.
So, my data access class looks a bit like:
```
private final static Connection connection = // initialized however
private static int uniqueInvocationNumber = 0;
public static Whatever getData(ValidatedQuery validatedQuery) {
String aliasName = "TEMPALIAS" + String.valueOf(uniqueInvocationNumber);
// build statements, execute statements, deal with results
uniqueInvocationNumber++;
}
```
This works. However, I've recently been made aware that I'm firmly stuck in Jon Skeet's phase 0 of [threading knowledge](https://stackoverflow.com/questions/423823/whats-your-favorite-programmer-ignorance-pet-peeve/424160#424160) ("Complete ignorance - ignore any possibility of problems.") - I've never written either threaded code or thread-aware code. I have absolutely no idea what can happen when many users are using the application at the same time.
So my question is, (assuming I haven't stumbled to thread-safety by blind luck / J2EE magic):
How can I make this safe?
I've included information here which I believe is relevant but let me know if it's not sufficient.
Thanks a million.
**EDIT:** This is a proper J2EE web application using the Wicket framework. I'm typically deploying it inside Jetty.
**EDIT:** A long story about the motivation for the ALIASes, for those interested:
The database in question is DB2 on AS400 (i5, System i, iSeries, whatever IBM are calling it these days) and I'm using [jt400](http://jt400.sourceforge.net/).
Although DB2 on AS400 is kind of like DB2 on any other platform, tables have a concept of a "member" because of legacy stuff. A member is kind of like a chunk of a table. The query I want to run is
```
SELECT thisField FROM thisTable(thisMember)
```
which treats thisMember as a table in its own right so just gives you thisField for all the rows in the member.
Now, queries such as this run fine in an interactive SQL session, but don't work over JDBC (I don't know why). The workaround I use is to do something like
```
CREATE ALIAS tempAlias FOR thisTable(thisMember)
```
then a
```
SELECT thisField FROM tempAlias
```
then a
```
DROP ALIAS tempAlias
```
which works but for one show-stopping issue: when you do this repeatedly with the ALIAS always called "tempAlias", and have a case where thisField has a different length from one query to the next, the result set comes back garbled for the second query (getString for the first row is fine, the next one has a certain number of spaces prepended, the next one the same number of spaces further prepended - this is from memory, but it's something like that).
Hence the workaround of ensuring each ALIAS has a distinct name which clears this up.
I've just realised (having spent the time to tap this explanation out) that I probably didn't spend enough time thinking about the issue in the first place before seizing on the workaround. Unfortunately I haven't yet fulfilled my dream of getting an AS400 for my bedroom ;) so I can't try anything new now. | Well, I'm going to ignore any SQL stuff for the moment and just concentrate on the uniqueInvocationNumber part. There are two problems here:
* There's no guarantee that the thread will see the latest value at any particular point
* The increment isn't atomic
The simplest way to fix this in Java is to use [AtomicInteger](http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html):
```
private static final AtomicInteger uniqueInvocationNumber = new AtomicInteger();
public static Whatever getData(ValidatedQuery validatedQuery) {
String aliasName = "TEMPALIAS" + uniqueInvocationNumber.getAndIncrement()
// build statements, execute statements, deal with results
}
```
Note that this still assumes you're only running a single instance on a single server. For a home project that's probably a reasonable assumption :)
Another potential problem is sharing a single connection amongst different threads. Typically a better way of dealing with database connections is to use a connection pool, and "open/use/close" a connection where you need to (closing the connection in a finally block). | If that static variable and the incrementing of the unique invocation number is visible to all requests, I'd say that it's shared state that needs to be synchronized. | Thread safety in Java web application data access class | [
"",
"java",
"multithreading",
"jakarta-ee",
""
] |
For a program I am writing, I need to ask a user for an integer between 1 and 8. I've tried multiple (cleaner) ways of doing this but none of them worked, so I'm left with this:
```
int x = 0;
while (x < 1 || x > 8)
{
System.out.print("Please enter integer (1-8): ");
try
{
x = Integer.parseInt(inputScanner.next());
}
catch(NumberFormatException e)
{
x = 0;
}
}
```
Where `inputScanner` is a Scanner. Surely there is a better way? | Scanner does regular expressions, right? Why not check if it matches "^[1-8]$" first? | Using the nextInt() is already an improvement compare to simply using the next() method. And before that, you can use the hasNextInt() to avoid haing all this bunch of useless exceptions.
Resulting in something like this:
```
int x = 0;
do {
System.out.print("Please...");
if(scanner.hasNextInt()) x = scanner.nextInt();
else scanner.next();
} while (x < 1 || x > 8);
``` | Easier way to guarantee integer input through Scanner? | [
"",
"java",
"parsing",
"integer",
"user-input",
"java.util.scanner",
""
] |
How would I do this in PHP?
```
Server.Transfer("/index.aspx")
```
(add ';' for C#)
**EDIT:**
It is important to have the URL remain the same as before; you know, for Google. In my situation, we have a bunch of .html files that we want to transfer and it is important to the client that the address bar doesn't change. | As far as I know PHP doesn't have a real transfer ability, but you could get the exact same effect by using include() or require() like so:
```
require_once('/index.aspx");
``` | The easiest way is to use a `header` redirect.
```
header('Location: /index.php');
```
Edit:
Or you could just include the file and exit if you don't want to use HTTP headers. | Code Translation: ASP.NET Server.Transfer in PHP | [
"",
"php",
"asp.net",
""
] |
I am writing a winforms app in which a user selects an item from a listbox and edits some data that forms part of an associated object. The edits are then applied from the object list to an underlying file.
In ASP.Net assigning a different system value to a list item than the display text the user sees is trivial. In a winforms app you have to set the "Displaymember" and the "Valuemember" of each item in a slightly more complicated (and not oft related on the internet) process.
This I have done. In debug mode I have confirmed that every item now has a value which is the display member (a "friendly" string that the user sees) and a key, the valuemember, which holds the key to a hashtable object where the data to be updated exists.
So when a user picks a string to edit the program should pass the "key" to the hashtable, yank out the object and allow editing to take place upon it.
The catch?
I can't see any obvious way of telling the program to look at the item's valuemember. I naively expected it to populate the list box's "SelectedValue" property, but that would be too simple by far. So how the hell do I get to the list item value? | Okay so the answer came as a result of Andy's answer, hence my upvoting that answer.
But when I created a little class and tried to cast the listitem into that class the program threw an exception.
Revealingly the exception told me that the program could not cast a DictionaryEntry into a class of the type I had defined.
So I deleted the proxy class and reframed the request thus:
```
DictionaryEntry de = (DictionaryEntry)listbox.SelectedItem;
string htKey = de.Key.ToString();
```
And it's all good.
Bizarrely simple answer in the end. Thanks for the hint Andy. | Using both the `SelectedIndexChanged` and `SelectedValueChanged` didn't work for me - the `ListBox's` `SelectedValue` property was always null. This surprised me, too.
As a lame workaround, you could just pull the object out of the `ListBox` directly, using the `SelectedIndex`:
```
public Form1()
{
InitializeComponent();
this.listBox1.DisplayMember = "Name";
this.listBox1.ValueMember = "ID";
this.listBox1.Items.Add(new Test(1, "A"));
this.listBox1.Items.Add(new Test(2, "B"));
this.listBox1.Items.Add(new Test(3, "C"));
this.listBox1.Items.Add(new Test(4, "D"));
this.listBox1.Items.Add(new Test(5, "E"));
}
private void OnSelectedIndexChanged(object sender, EventArgs e)
{
if(-1 != this.listBox1.SelectedIndex)
{
Test t = this.listBox1.Items[this.listBox1.SelectedIndex] as Test;
if(null != t)
{
this.textBox1.Text = t.Name;
}
}
}
```
(`Test` is just a simple class with two properties - `ID` and `Name`).
It seems like there should be a better way, but if nothing else this should work. | How do I get at the listbox item's "key" in c# winforms app? | [
"",
"c#",
"winforms",
"listbox",
""
] |
I do not want to stop the user from clicking the same ajax button many times, but I want to exercise some control to prevent someone from maliciously clicking the button repeatedly which would cause repeated database requests. What is simple way to handle this on a jquery .post in asp.net mvc? If I put in a time delay, the experience client side will be ruined (?) | Why not disable the button after it is clicked, and then re-enable it once you have received the response from the server? | This is not a client-side issue and can only be handled on the server side. If an AJAX request is being made, then a malicious user can make the AJAX request directly to your server directly through HTTP--it's quite trivial even for newbies using something like [WFtech](http://www.microsoft.com/downloads/details.aspx?FamilyID=b134a806-d50e-4664-8348-da5c17129210&displaylang=en) or [Curl](http://curl.haxx.se/).
Not to state the obvious, but if a user can click a button multiple times, then so can an adversary and there's no way of really determining who is who. You can do some kind of throttling to limit it to x clicks per y seconds etc but then the adversary can also throttle his click rate. | How do I control repeated Ajax 'post' submissions? | [
"",
"asp.net",
"javascript",
"asp.net-mvc",
"asp.net-ajax",
""
] |
I am using a C++ SDK where there is a function like (it has a python wrapper, but not docs):
```
getPos ( int uvId, float & u, float & v ) const
```
How do I specify in Python so that the passed variables are changed?
I tried this example to see if I could modify floats inside a function, but it didn't work, so printed 12.0:
```
def change ( a ) :
a = 35.0
b = 12.0
change ( b )
print b
```
So how do I call this function that I can change 2 external floats in Python?
Related:
* [Python: variable scope and function calls](https://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls/) | As far I know, Python doesn't support call-by-reference, so the exact code you are suggesting doesn't work (obviously).
The tool (or person) that generated the Python wrapper for the C++ function must have done something special to support this function (hopefully, or you won't be able to use it). Do you know what tool was used to generate the wrapper?
Usually tools like this will generate some sort of container data type:
```
b.value = 12.0
change(b)
print b.value
``` | In Python:
```
def getPos(uvID):
# compute u, v
return u, v
#
u, v = getPos(uvID)
``` | Change basic (immutable) types inside a function in Python? | [
"",
"python",
"variables",
"pass-by-reference",
""
] |
Is there a way to detect IP address changes on the local machine in Linux programmatically using C++? | In C, to get the current IP I use:
```
int s;
struct ifreq ifr = {};
s = socket(PF_INET, SOCK_DGRAM, 0);
strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));
if (ioctl(s, SIOCGIFADDR, &ifr) >= 0)
printf("%s\n",
inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
```
Replace "eth0" with the interface you're looking at. All you now need to do is poll for a change. | here you go.. this does it without polling.
it only listens for RTM\_NEWADDR but it should be easy to change to support RTM\_DELADDR if you need
```
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <net/if.h>
int
main()
{
struct sockaddr_nl addr;
int sock, len;
char buffer[4096];
struct nlmsghdr *nlh;
if ((sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) == -1) {
perror("couldn't open NETLINK_ROUTE socket");
return 1;
}
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_groups = RTMGRP_IPV4_IFADDR;
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("couldn't bind");
return 1;
}
nlh = (struct nlmsghdr *)buffer;
while ((len = recv(sock, nlh, 4096, 0)) > 0) {
while ((NLMSG_OK(nlh, len)) && (nlh->nlmsg_type != NLMSG_DONE)) {
if (nlh->nlmsg_type == RTM_NEWADDR) {
struct ifaddrmsg *ifa = (struct ifaddrmsg *) NLMSG_DATA(nlh);
struct rtattr *rth = IFA_RTA(ifa);
int rtl = IFA_PAYLOAD(nlh);
while (rtl && RTA_OK(rth, rtl)) {
if (rth->rta_type == IFA_LOCAL) {
char name[IFNAMSIZ];
if_indextoname(ifa->ifa_index, name);
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, RTA_DATA(rth), ip, sizeof(ip));
printf("interface %s ip: %s\n", name, ip);
}
rth = RTA_NEXT(rth, rtl);
}
}
nlh = NLMSG_NEXT(nlh, len);
}
}
return 0;
}
``` | How to detect IP address change programmatically in Linux? | [
"",
"c++",
"linux",
""
] |
I'm storing a varchar in a utf8 MySQL table and using utf8\_general\_ci collation. I have a unique index on the varchar. I'd like to do a string comparison in PHP that is equivalent to what MySQL will do on the index.
A specific example is that I'd like to be able to detect that 'a' is considered equivalent to 'À' in PHP before this happens:
```
mysql> insert UniTest (str) values ('a');
Query OK, 1 row affected (0.00 sec)
mysql> insert UniTest (str) values ('À');
ERROR 1062 (23000): Duplicate entry 'À' for key 1
``` | The collation has nothing to do with the storage. You need to set the charset to determine the storage encoding. The collation governs how comparison and sorting should happen. The collation must be charset aware, but otherwise it has nothing to do with the charset.
To answer your question, you can use `iconv` to translitter the text, and then compare it. For example:
```
function compare($s1, $s2) {
return strcmp(
iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $s1),
iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $s2));
}
```
This is basically what MySql will do for you, although it's probably faster and it may have a slightly different collation-table than `ISO-8859-1//TRANSLIT`. Not entirely sure about that.
Would probably be easier to use the database though, as others have already suggested. | Would it be reasonable just to let MySQL do the work, by submitting a query to MySQL like:
```
SELECT CASE WHEN '$a' = '$b' THEN 1 ELSE 0 END
```
---
EDIT post clarification:
You could one-time iterate through the entire character set of interest cartesian joined to itself and build a standard php associative array of equivalence sets.
```
for each $char1 in $charset {
for each $char2 in $charset {
$charmatch[$char1][$char2] = mysqlTestMatch($char1, $char2));
}
}
```
Then you'd need to test each string character by character, to see if a) they are the same, or if not, b) they are equivalent. | Comparing strings in PHP the same way MySQL does | [
"",
"php",
"mysql",
"utf-8",
"collation",
"mysql-error-1062",
""
] |
I am trying to limit the following SQL statement.
```
SELECT expense.*, transaction.* FROM expense
INNER JOIN transaction ON expense_id = transaction_expense_id
```
What I want to do, is limit the number of 'parent' rows. IE. if I do a LIMIT 1, I would receive only one expense item, but still get all transactions associated with it.
How would this be achieved? I am using MySQL 5.0
At this stage, if I do LIMIT 1, I get one expense, and only one transaction. | So assuming we can exclude the user table, it could be rewritten as:
```
select * from expense, transaction where expense_id = transaction_expense_id
```
Now if you want to apply a limit, you could do it like this:
```
select * from expense, transaction where expense_id = transaction_expense_id and
expense_id in (select expense_id from expense limit 1)
```
Would that do what you wanted? Obviously you need to be cautious about what order your expense\_ids are going to come back in, so you probably want to use ORDER BY whatever.
Edit: Given the MySQL limitation described in your comment below, maybe this will work:
```
select * from (select id from expense order by WHATEVER limit 1) as t1, transaction where expense_id=transaction_expense_id;
```
Ben | You'll have to specify which **expense** item you want to get. The most expensive? The newest? Then join against a subquery that returns only that:
```
SELECT
expense.*, transaction.*, user.*
FROM
(SELECT * FROM expense WHERE ...) AS expense
INNER JOIN
transaction ON expense_id = transaction_expense_id
``` | How to limit returned results of a JOIN query in MySQL | [
"",
"mysql",
"sql",
"database",
"join",
"sql-limit",
""
] |
I am new to XML-RPC.
```
#client code
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
x,y = arg1,arg2
print proxy.fun1(x,y)
print proxy.fun2(x,y)
```
What server should do:
1. load fun1
2. register fun1
3. return result
4. unload fun1
and then do same with fun2.
What is the best way to do this?
I have figured out a way to do this but it sounds "clumsy,far fetched and unpythonic". | If you want dynamic registering, register an instance of an object, and then set attributes on that object. You can get more advanced by using the `__getattr__` method of the class if the function needs to be determined at run time.
```
class dispatcher(object): pass
def __getattr__(self, name):
# logic to determine if 'name' is a function, and what
# function should be returned
return the_func
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(dispatcher())
``` | Generally the server keeps on running - so register both methods at the start. I don't understand why you want to unregister your functions. Servers stay up and handle multiple requests. You might possible want a `shutdown()` function that shuts the entire server down, but I don't see anyway to unregister a single function.
The easiest way is with [SimpleXMLRPCServer](http://docs.python.org/library/simplexmlrpcserver.html):
```
from SimpleXMLRPCServer import SimpleXMLRPCServer
def fun1(x, y):
return x + y
def fun2(x, y):
return x - y
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(fun1)
server.register_function(fun2)
server.serve_forever()
``` | HOWTO: XML-RPC dynamic function registration in python? | [
"",
"python",
"xml-rpc",
""
] |
I'm writing a WebPart, which means that I inherit from `System.Web.UI.WebControls.WebParts.WebPart` and I override the method `protected override void CreateChildControls()`.
However, I'd like to make the class `sealed` if possible, but that gives two issues: Just sealing the class gives a warning "new protected member declared in sealed class".
Changing the access modifier from `protected` to `private` or `internal` gives a compiler error telling me I can't change the modifier when inheriting.
That leaves me wondering: Is there any problem with sealing it and ignoring the warning? Or could this lead to any negative side effects further down the road? It *seems* to work just fine, but the devil is usually in the details.
**Edit:** I was just being stupid. The "new protected member" error was for a function that was indeed NOT overridden and just accidentially was declared as `protected`. Thanks for the Pragma-Tip though! | The fact that it says there's a *new* protected member declared in the class is slightly worrying.
Hmm... I can't reproduce this in simple test code:
```
using System;
public class Base
{
protected virtual void Foo()
{
}
}
public sealed class Derived : Base
{
protected override void Foo()
{
}
}
```
compiles without warnings with .NET 3.5SP1. Are you *definitely* overriding the base method? Check that you really have got the `override` modifier. (Sorry if that sounds patronising - I'm not trying to accuse you of being lax or anything. I'm just stumped otherwise...) | A protected member can be seen by sub classes so you're slightly altering the interface of the class; If you declare it 'private' it's only ever seen locally so it doesn't affect the interface.
Declare your method private not protected and the warning should go away. | protected members in a sealed class | [
"",
"c#",
".net",
""
] |
Just started programming in C++.
I've created a Point class, a std::list and an iterator like so:
```
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
std::list <Point> pointList;
std::list <Point>::iterator iter;
```
I then push new points onto pointList.
Now, I'm needing to iterate through all the points in pointList, so I need to loop using the iterator. This is where I get screwed up.
```
for(iter = pointList.begin(); iter != pointList.end(); iter++)
{
Point currentPoint = *iter;
glVertex2i(currentPoint.x, currentPoint.y);
}
```
---
## Update
You guys were right, the problem isn't in my iterating the list. It appears the problem is when I am attempting to push something on to the list.
Exact error:
> mouse.cpp: In function `void mouseHandler(int, int, int, int)':
> mouse.cpp:59: error: conversion from`Point\*' to non-scalar type `Point' requested
Those lines are:
```
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
Point currentPoint = new Point(x, y);
pointList.push_front(currentPoint);
}
```
What does it conversion between Point\* to non-scalar type Point? I'm just trying to create new points and push them onto the list here. | That should be a valid bit of code.
```
#include <iostream>
#include <list>
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
int main()
{
std::list<Point> points;
points.push_back(Point(0, 0));
points.push_back(Point(1, 1));
points.push_back(Point(2, 2));
std::list<Point>::iterator iter;
for(iter = points.begin(); iter != points.end(); ++iter)
{
Point test = *iter;
std::cout << test.x << ", " << test.y << "; ";
}
std::cout << std::endl;
return 0;
}
```
Using this code:
```
jasons-macbook41:~ g++ test.cpp
jasons-macbook41:~ ./a.out
0, 0; 1, 1; 2, 2;
jasons-macbook41:~
```
Although I wouldn't create a temporary copy of the Point as your code does. I'd rewrite the loop like this:
```
for(iter = points.begin(); iter != points.end(); ++iter)
{
std::cout << iter->x << ", " << iter->y << "; ";
}
```
An iterator is syntactically similar to a pointer.
EDIT:
Given your new problem, drop the "new" from the construction line. That's creating a pointer to a Point, as opposed to a Point on the stack. This would be valid:
```
Point* temp = new Point(0, 0);
```
Or this:
```
Point temp = Point(0, 0);
```
And you'd be better off with the latter. | a few things..
* Did you try `iter->x` and `iter->y` instead of copying the value?
* the error you mention is hard to understand. You are not trying to get x and y via the iterator, you are copying the iterator data to a new point.
EDIT:
according to new information in the OP. You are trying to new into a non-pointer object and then trying to stuff the point into a vector that only accepts objects. You either have to make the vector a vector of pointers and remember to delete them afterwords or create the new point on the stack and copy them into the vector with a standard assign. Try this:
```
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
Point currentPoint = Point(x, y);
pointList.push_front(currentPoint);
}
``` | Why can't I push this object onto my std::list? | [
"",
"c++",
"linked-list",
"loops",
""
] |
I dont want to replace it with /u000A, do NOT want it to look like "asdxyz/u000A"
I want to replace it with the actual newline CHARACTER. | Based on your response to [Natso's answer](https://stackoverflow.com/questions/535227/take-string-asdxyz-n-and-replace-n-with-the-ascii-value/535235#535235), it seems that you have a fundamental misunderstanding of what's going on. The two-character sequence `\n` isn't the new-line character. But it's the way we *represent* that character in code because the actual character is hard to see. The compiler knows that when it encounters that two-character sequence in the context of a string literal, it should interpret them as the real new-line character, which has the ASCII value 10.
If you print that two-character sequence to the console, you won't see them. Instead, you'll see the cursor advance to the next line. That's because the compiler has already replaced those two characters with the new-line character, so it's really the new-line character that got sent to the console.
If you have *input* to your program that contains backslashes and lowercase *N*'s, and you want to convert them to new-line characters, then [Zach's answer](https://stackoverflow.com/questions/535227/take-string-asdxyz-n-and-replace-n-with-the-ascii-value/535239#535239) might be sufficient. But if you want your program to allow real backslashes in the input, then you'll need some way for the input to indicate that a backslash followed by a lowercase *N* is really supposed to be those two characters. The usual way to do that is to prefix the backslash with another backslash, *escaping* it. If you use Zach's code in that situation, you may end up turning the three-character sequence `\\n` into the two-character sequence consisting of a backslash followed by a new-line character.
The sure-fire way to read strings that use backslash escaping is to parse them one character at a time, starting from the beginning of the input. Copy characters from the input to the output, except when you encounter a backslash. In that case, check what the next character is, too. If it's another backslash, copy a single backslash to the output. If it's a lowercase *N*, then write a new-line character to the output. If it's any other character, so whatever you define to be the right thing. (Examples include rejecting the whole input as erroneous, pretending the backslash wasn't there, and omitting both the backslash and the following character.)
If you're trying to observe the contents of a variable in the debugger, it's possible that the debugger may detect the new-line character convert it *back* to the two-character sequence `\n`. So, if you're stepping through your code trying to figure out what's in it, you may fall victim to the debugger's helpfulness. And in most situations, it really is being helpful. Programmers usually want to know exactly what characters are in a string; they're less concerned about how those characters will appear on the screen. | Just use [`String.replace()`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)):
```
newtext = text.replace("\\n", "\n");
``` | Take string "asdxyz\n" and replace \n with the ascii value | [
"",
"java",
"apache-flex",
"compiler-construction",
""
] |
I am trying to convert code from mysql to mysqli.
The code uses a single mysql\_connect in a file which is included by every other file.
mysql\_connect returns a MySQL link identifier that is a superglobal so you can rely on having a database connection available in any of your own functions.
It looks like with mysqli\_connect this is not the case, the object returned isn't global.
Does this mean I have to add : global $mysqli; at the top of every function, or is there an way of making it a superglobal? | Relying on the fact that PHP will use the last opened connection resource if you don't specify one, is probably not a very good idea.
What happens if your application changes and you need two connections, or the connection is not there?
So it seems you need to do some refactoring anyway.
Here's a solution similar to Karsten's that always returns the same mysqli object.
```
class DB {
private static $mysqli;
private function __construct(){} //no instantiation
static function cxn() {
if( !self::$mysqli ) {
self::$mysqli = new mysqli(...);
}
return self::$mysqli;
}
}
//use
DB::cxn()->prepare(....
``` | I usually make a function:
```
$mysqli = new mysqli(...);
function prepare($query) {
global $mysqli;
$stmt = $msqyli->prepare($query);
if ($mysqli->error()) {
// do something
}
return $stmt;
}
function doStuff() {
$stmt = prepare("SELECT id, name, description FROM blah");
// and so on
}
```
and then call that. That being said, I've since abandoned mysqli as being too bug-ridden to be considered usable. Shame really. | Converting mysql to mysqli - how to get superglobal connection object? | [
"",
"php",
"mysql",
"mysqli",
""
] |
I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for.
I would like to figure out how to get it into a fieldstorage object. | Assuming you are trying to get just the POST data into a FieldStorage object:
```
# env is the environment handed to you by the WSGI server.
# I am removing the query string from the env before passing it to the
# FieldStorage so we only have POST data in there.
post_env = env.copy()
post_env['QUERY_STRING'] = ''
post = cgi.FieldStorage(
fp=env['wsgi.input'],
environ=post_env,
keep_blank_values=True
)
``` | ```
body= '' # b'' for consistency on Python 3.0
try:
length= int(environ.get('CONTENT_LENGTH', '0'))
except ValueError:
length= 0
if length!=0:
body= environ['wsgi.input'].read(length)
```
Note that WSGI is not yet fully-specified for Python 3.0, and much of the popular WSGI infrastructure has not been converted (or has been 2to3d, but not properly tested). (Even wsgiref.simple\_server won't run.) You're in for a rough time doing WSGI on 3.0 today. | Accessing POST Data from WSGI | [
"",
"python",
"python-3.x",
"wsgi",
""
] |
In the example below, is the connection going to close and disposed when an exception is thrown if it is within a `using` statement?
```
using (var conn = new SqlConnection("..."))
{
conn.Open();
// stuff happens here and exception is thrown...
}
```
I know this code below will make sure that it does, but I'm curious how using statement does it.
```
var conn;
try
{
conn = new SqlConnection("...");
conn.Open();
// stuff happens here and exception is thrown...
}
// catch it or let it bubble up
finally
{
conn.Dispose();
}
```
### Related:
[What is the proper way to ensure a SQL connection is closed when an exception is thrown?](https://stackoverflow.com/questions/141204/what-is-the-proper-way-to-ensure-a-sql-connection-is-closed-when-an-exception-is) | Yes, `using` wraps your code in a try/finally block where the `finally` portion will call `Dispose()` if it exists. It won't, however, call `Close()` directly as it only checks for the `IDisposable` interface being implemented and hence the `Dispose()` method.
See also:
* [Intercepting an exception inside IDisposable.Dispose](https://stackoverflow.com/questions/220234/intercepting-an-exception-inside-idisposable-dispose)
* [What is the proper way to ensure a SQL connection is closed when an exception is thrown?](https://stackoverflow.com/questions/141204/what-is-the-proper-way-to-ensure-a-sql-connection-is-closed-when-an-exception-is)
* [C# "Using" Syntax](https://stackoverflow.com/questions/149609/c-using-syntax)
* [C# USING keyword - when and when not to use it?](https://stackoverflow.com/questions/317184/c-using-keyword-when-and-when-not-to-use-it)
* ['using' statement vs 'try finally'](https://stackoverflow.com/questions/278902/using-statement-vs-try-finally)
* [What is the C# Using block and why should I use it?](https://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it)
* [Disposable Using Pattern](https://stackoverflow.com/questions/513672/disposable-using-pattern)
* [Does End Using close an open SQL Connection](https://stackoverflow.com/questions/376068/does-end-using-close-an-open-sql-connection) | This is how reflector decodes the IL generated by your code:
```
private static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("...");
try
{
conn.Open();
DoStuff();
}
finally
{
if (conn != null)
{
conn.Dispose();
}
}
}
```
So the answer is yes, it will close the connection if
```
DoStuff()
```
throws an exception. | Does Dispose still get called when exception is thrown inside of a using statement? | [
"",
"c#",
"asp.net",
"using-statement",
""
] |
I have an instance of the following object in the jsp page context:
```
Class User{
private boolean isAdmin;
public boolean isAdmin(){return isAdmin}
}
```
How can I query the isAdmin property from the EL? This doesn't seem to work:
```
${user.admin}
```
nor does this:
```
${user.isAdmin}
```
thanks!
-Morgan | Ok. I'm stupid. Vote this question down, ridicule me, etc. The problem was in the method that isAdmin() was delegating to. There was a null pointer exception in that method. In my defense, however, I'll say that the stack trace I got was a bit unclear, and made it look like it was an EL issue rather than a simple null pointer in my code.
Vinegar, your assurances that isAdmin() works even without a property did help me figure this out. Thanks for that.
```
javax.el.ELException: java.lang.NullPointerException
at javax.el.BeanELResolver.getValue(BeanELResolver.java:298)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175)
at com.sun.el.parser.AstValue.getValue(AstValue.java:138)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:206)
at org.apache.jasper.runtime.PageContextImpl.evaluateExpression(PageContextImpl.java:1001)
at org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp._jspx_meth_c_forEach_1(org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp:452)
at org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp._jspx_meth_c_forEach_0(org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp:399)
at org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp._jspx_meth_form_form_0(org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp:348)
at org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp._jspService(org.apache.jsp.WEB_002dINF.jsp.managepermissions_jsp:197)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:109)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:389)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:486)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:380)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:502)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:363)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:417)
at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:334)
at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:126)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:252)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1173)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:523)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:463)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
``` | Try this:
```
${user.Admin}
```
just in case capitalization is the problem. Sometimes EL does non-obvious things. However, I've usually been able to just use the equivalent of `${user.admin}` in my el. Looking at my own code, I have many examples of doing the obvious thing where it works.
Do you have the following methods in your class:
```
public boolean isAdmin(){return isAdmin}
public void isAdmin(boolean newValue) { ... }
```
or do you have only the getter? If my code, I notice that I do not do the above. My setters all start with `set` such as:
```
public boolean isAdmin(){return isAdmin}
public void setAdmin(boolean newValue) { ... }
```
and I am able to use the obvious lowercase solution `${user.admin}` in my JSPs. This may depend on which EL processor you're using.
**NOTE:** Added later because people still vote this down, obviously never having run into an example where this occurs. An example from my own JSPs that caused me to ask this question is that I have a method:
```
public int getLANSomething() { ... }
```
and I access this in EL as follows: `${agent.LANSomething}` The rule appears to be `getXXXyyy` where `XXX` is all caps, you have to use caps to access it in EL. At least with Tomcat versions 4-6 that I have used. | getting boolean properties from objects in jsp el | [
"",
"java",
"jsp",
""
] |
I use the wonderful Eclipse PDT for PHP development.
I often encounter irritating bugs due to me misspelling variable names.
Is there a way to highlight variables that have not been initialized? As they will almost certainly be due to a spelling mistake.
Thanks for any help. | No. Due to the dynamic, sometimes hackish nature of PHP, it would overall be a pain to have variables that the IDE thinks is undeclared be underlined. Since many functions can declare variables on their own (such as [extract](http://www.php.net/manual/en/function.extract.php)), this would be a major hindrance. | zend studio has this feature so i'm not sure if we'll see it in pdt, it will also highlight unreachable code, etc. | PHP - Eclipse PDT - Highlighting uinitialized (misspelled) variables | [
"",
"php",
"eclipse",
"eclipse-pdt",
""
] |
Suppose I have a string, for example,
```
string snip = "</li></ul>";
```
I want to basically write it multiple times, depending on some integer value.
```
string snip = "</li></ul>";
int multiplier = 2;
// TODO: magic code to do this
// snip * multiplier = "</li></ul></li></ul>";
```
EDIT:
I know I can easily write my own function to implement this, I was just wondering if there was some weird string operator that I didn't know about | In .NET 4 you can do this:
```
String.Concat(Enumerable.Repeat("Hello", 4))
``` | Note that if your "string" is only a single character, there is an overload of the string constructor to handle it:
```
int multipler = 10;
string TenAs = new string ('A', multipler);
``` | Can I "multiply" a string (in C#)? | [
"",
"c#",
"string",
"extension-methods",
""
] |
I'm not against using "Using" statement, but I'm wondering how this affect performance when we use it inside one of another.
For example:
```
using (test1 (type1))
{
using (test2(type2))
{
using (test2(type3))
{
}
}
}
```
This, will be translated in IL like this:
```
try
{
try
{
try
{
}
finally
{
}
}
finally
{
}
}
finally
{
}
```
This will increase the size of assembly and, I believe, affect the performance of the application, right?
Shouldn't we use this?
```
type1 test1 = new type1;
type2 test2 = new type2;
type3 test3 = new type3;
try
{
}
finally
{
test1.Dispose;
test2.Dispose;
test3.Dispose;
}
``` | No, *don't* use your second form. If `test1.Dispose()` throws an exception for some reason, `test2.Dispose()` and `test3.Dispose()` won't get called.
The performance difference, if any, will be microscopic. Don't throw away correctness for insignificant performance :) | I think you're looking for the following:
```
using (test1(type1))
using (test2(type2))
using (test3(type3))
{
// Code using test1/test2/test3 goes here.
}
```
It is equivalent to the first try-finally statement in your question, though clearly a lot more readable. Don't worry about the performance here really; it's good design practices and robust to use the nested method (as point out by previous posters), and additionally easily readable code (thanks to the multi-using statement) that count. | Using multiples "usings", how this affect performance? | [
"",
"c#",
"clr",
""
] |
wonder if you could help me out with some Javascript. I have a string that is log message, and i'm waniting to grab a section out of this log and display that on it's own
eg.(bear in mind the log section is not case sesitive and any letter can be any case, also could be placed anywhere withing the string)
**$LOG: 08880xbpnd $
fhdsafidsfsd
df
sd
fsd
f
sd
fsd**
thats the orignal log, Im wanting to grab the 08880xbpnd and get rid of the rest? how can this be done in javascript?
edit
if this is any help i have this regex in perl that grabs the log somewhere else
/(?i)\$LOG:\s\*(none|(temp(GD|MD)(.\d{1,2}){4}))\s\*\$/
basically what ever in between $LOg: and $ i want to grab and exclude any white space that value in between could be anything or that above | I would use this regular expression:
```
/\$LOG:([^$]+)\$/i
```
So:
```
"$LOG: 08880xbpnd $ fhdsafidsfsd df sd fsd f sd fsd".match(/\$LOG:([^$]+)\$/i)
``` | This works for me :
```
<script type="text/javascript">
// Call the function with a sample input string.
GetMyLog("$LOG: 08880xbpnd $ fhdsafidsfsd df sd fsd f sd fsd");
function GetMyLog(fullString)
{
// Create a Regex object. We want to capture all word-like characters within the $LOG and ending $
// This assumes that there will not be any more "$" characters in the trailing string.
var reg = /\$LOG:\s*([\w]+)\s*\$/;
// If the match attempt was successful, we need to get the second value in the array returned by the match.
if (fullString.match(reg))
{
alert(reg.exec(fullString)[1]);
}
}
</script>
``` | Get a similar string a discharge the rest | [
"",
"javascript",
"regex",
""
] |
I'm using PHP and xPath to crawl into a website I own (just crawl the html not going into the server) but I get this error:
> Catchable fatal error: Object of class
> DOMNodeList could not be converted to
> string in C:\wamp\www\crawler.php on
> line 46
I already tried echoing just that line to see what I was getting but I would just get the same error also I tried googling for the error but I, in the end, ended up in the php documentation and found out my example is exactly as the one in php documentation except I'm working with an HTML instead of a XML...so I have no idea what's wrong...here's my code...
```
<?php
$html = file_get_contents('http://miurl.com/mipagina#0');
// create document object model
$dom = new DOMDocument();
// load html into document object model
@$dom->loadHTML($html);
// create domxpath instance
$xPath = new DOMXPath($dom);
// get all elements with a particular id and then loop through and print the href attribute
$elements = $xPath->query("//*[@class='nombrecomplejo']");
if ($elements != null) {
foreach ($elements as $e) {
echo parse_str($e);
}
}
?>
```
---
**Edit**
Actually yes sorry that line was to test when I had commented other stuff...I deleted it here still have the error though. | According to the [documentation](http://www.php.net/manual/en/domxpath.query.php), the "`$elements != null`" check is unnecessary. `DOMXPath::query()` will always return a `DOMNodeList`, though maybe it will be of zero length, which won't confuse the `foreach` loop.
Also, note the use of the `nodeValue` property to get the element's textual representation:
```
$elements = $xPath->query("//*[@class='nombrecomplejo']");
foreach ($elements as $e) {
echo $e->nodeValue;
}
```
The reason for the error you got is that you can't feed anything other than a string to [`parse_str()`](http://www.php.net/manual/en/function.parse-str.php), you tried passing in a `DOMElement`. | Just a wild guess, but *echo $elements;* is line 46, right? I believe the echo command expects something that is a string or convertible to a string, which $elements is not. Try removing that line. | PHP & xPath Question | [
"",
"php",
"xpath",
""
] |
Quote from [The C++ standard library: a tutorial and handbook](http://books.google.com/books?id=n9VEG2Gp5pkC&pg=PA10&lpg=PA10&dq=%22The%20only%20portable%20way%20of%20using%20templates%20at%20the%20moment%20is%20to%20implement%20them%20in%20header%20files%20by%20using%20inline%20functions.%22&source=bl&ots=Ref8pl8dPX&sig=t4K5gvxtBblpcujNxodpwMfei8I&hl=en&ei=qkR6TvbiGojE0AHq4IzqAg&sa=X&oi=book_result&ct=result&resnum=3&ved=0CC8Q6AEwAg#v=onepage&q=%22The%20only%20portable%20way%20of%20using%20templates%20at%20the%20moment%20is%20to%20implement%20them%20in%20header%20files%20by%20using%20inline%20functions.%22&f=false):
> The only portable way of using templates at the moment is to implement them in header files by using inline functions.
Why is this?
(Clarification: header files are not the *only* portable solution. But they are the most convenient portable solution.) | Caveat: It is *not* necessary to put the implementation in the header file, see the alternative solution at the end of this answer.
Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:
```
template<typename T>
struct Foo
{
T bar;
void doSomething(T param) {/* do stuff using T */}
};
// somewhere in a .cpp
Foo<int> f;
```
When reading this line, the compiler will create a new class (let's call it `FooInt`), which is equivalent to the following:
```
struct FooInt
{
int bar;
void doSomething(int param) {/* do stuff using int */}
};
```
Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case `int`). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.
A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.
Foo.h
```
template <typename T>
struct Foo
{
void doSomething(T param);
};
#include "Foo.tpp"
```
Foo.tpp
```
template <typename T>
void Foo<T>::doSomething(T param)
{
//implementation
}
```
This way, implementation is still separated from declaration, but is accessible to the compiler.
# Alternative solution
Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:
Foo.h
```
// no implementation
template <typename T> struct Foo { ... };
```
Foo.cpp
```
// implementation of Foo's methods
// explicit instantiations
template class Foo<int>;
template class Foo<float>;
// You will only be able to use Foo with int or float
```
If my explanation isn't clear enough, you can have a look at the [C++ Super-FAQ on this subject](https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl). | It's because of the requirement for separate compilation and because templates are instantiation-style polymorphism.
Lets get a little closer to concrete for an explanation. Say I've got the following files:
* foo.h
+ declares the interface of `class MyClass<T>`
* foo.cpp
+ defines the implementation of `class MyClass<T>`
* bar.cpp
+ uses `MyClass<int>`
Separate compilation means I should be able to compile **foo.cpp** independently from **bar.cpp**. The compiler does all the hard work of analysis, optimization, and code generation on each compilation unit completely independently; we don't need to do whole-program analysis. It's only the linker that needs to handle the entire program at once, and the linker's job is substantially easier.
**bar.cpp** doesn't even need to exist when I compile **foo.cpp**, but I should still be able to link the **foo.o** I already had together with the **bar.o** I've only just produced, without needing to recompile **foo.cpp**. **foo.cpp** could even be compiled into a dynamic library, distributed somewhere else without **foo.cpp**, and linked with code they write years after I wrote **foo.cpp**.
"Instantiation-style polymorphism" means that the template `MyClass<T>` isn't really a generic class that can be compiled to code that can work for any value of `T`. That would add overhead such as boxing, needing to pass function pointers to allocators and constructors, etc. The intention of C++ templates is to avoid having to write nearly identical `class MyClass_int`, `class MyClass_float`, etc, but to still be able to end up with compiled code that is mostly as if we *had* written each version separately. So a template is *literally* a template; a class template is *not* a class, it's a recipe for creating a new class for each `T` we encounter. A template cannot be compiled into code, only the result of instantiating the template can be compiled.
So when **foo.cpp** is compiled, the compiler can't see **bar.cpp** to know that `MyClass<int>` is needed. It can see the template `MyClass<T>`, but it can't emit code for that (it's a template, not a class). And when **bar.cpp** is compiled, the compiler can see that it needs to create a `MyClass<int>`, but it can't see the template `MyClass<T>` (only its interface in **foo.h**) so it can't create it.
If **foo.cpp** itself uses `MyClass<int>`, then code for that will be generated while compiling **foo.cpp**, so when **bar.o** is linked to **foo.o** they can be hooked up and will work. We can use that fact to allow a finite set of template instantiations to be implemented in a .cpp file by writing a single template. But there's no way for **bar.cpp** to use the template *as a template* and instantiate it on whatever types it likes; it can only use pre-existing versions of the templated class that the author of **foo.cpp** thought to provide.
You might think that when compiling a template the compiler should "generate all versions", with the ones that are never used being filtered out during linking. Aside from the huge overhead and the extreme difficulties such an approach would face because "type modifier" features like pointers and arrays allow even just the built-in types to give rise to an infinite number of types, what happens when I now extend my program by adding:
* baz.cpp
+ declares and implements `class BazPrivate`, and uses `MyClass<BazPrivate>`
There is no possible way that this could work unless we either
1. Have to recompile **foo.cpp** every time we change *any other file in the program*, in case it added a new novel instantiation of `MyClass<T>`
2. Require that **baz.cpp** contains (possibly via header includes) the full template of `MyClass<T>`, so that the compiler can generate `MyClass<BazPrivate>` during compilation of **baz.cpp**.
Nobody likes (1), because whole-program-analysis compilation systems take *forever* to compile , and because it makes it impossible to distribute compiled libraries without the source code. So we have (2) instead. | Why can templates only be implemented in the header file? | [
"",
"c++",
"templates",
"undefined-reference",
"c++-faq",
""
] |
I'm working on a web application import program. Currently an admin user can upload a formatted csv file that my page will parse. I'm experiencing an execution duration issue as each line pertains to a file that has to be saved to Scribd, S3, as well as some internal processing.
What would you guys recommend for improving execution time? Since this is an admin only page, I doubt it would get run more than once a week, so my hope is to get it out the door asap.
I've looked some at the Async="true" flag, but I wasn't sure if that was the direction I wanted to go, or if I should look more that a windows server. | Two options come to mind:
**Threads**: In your code setup a collection of threads, join them and then have each one process a single file. Once all the threads complete you'll be able to return the page. This will increase your turn around time, but could still leave something to be desired on page returns
**Queue**: Have the user submit the csv file and provide a GUID/Hash/Whatever ID where the admin could then go to the "status" page, input their ID and check the details of their job. This solution will provide a quick feedback to the user and allow them to keep track of the results without having to wait around. | A quick and dirty option might be to set Page.Server.ScriptTimeout to a really high value on that page. (I think it maxes at Int.MaxValue).
Probably advisable to block the submit button after its been clicked, and inform the user that they may want to go make a coffee. | Handling long page execution times in ASP.NET | [
"",
"c#",
"asp.net",
"performance",
"asp.net-3.5",
""
] |
I am moving some data and I need to come up with a TSQL statement to convert dates currently in a datetime field to another database field with the varchar MM/yy format.
This statement needs to work on both SQL Server 2k5 **and also** SQL Compact Edition 3.5 - so the answer needs to be "set" based and not include cursors etc that are not supported in SQLCE. | relying on the type, i.e. "101" could be dangerous if you ever run on a non-US database server, as the mm and dd would be switched around. Probably the same with using type "3". As long as you know the language of the server will always be the same, those methods are the easiest.
Using datepart is probably more reliable, but if you want say 03/08 instead of 3/08, you have to make sure to prefix the month with a "0", so
```
select
right( '00' + convert(varchar(2), datepart( mm, @ddate)), 2) + '/' +
right( convert(varchar(4), datepart( yy, @ddate) ), 2 )
``` | Not exactly what you want but you should be able to alter easily:
```
DECLARE @ddate datetime
set @ddate = getdate()
SELECT CAST(DATEPART(month, @ddate) as varchar(2)) + '/' + CAST(DATEPART(year, @ddate) as varchar(4))
``` | Convert date in TSQL | [
"",
"sql",
"t-sql",
"sql-server-ce",
""
] |
Ideally I'd like to do as little preparation data work on the server as possible. The less I have to do to prep the data from the database to make a given chart, the happier I am and the more view I can make in the time.
Some of the things I'd like to chart are, for example:
* The distribution of a series of response times
* The number of occurrences per category (basic bar chart)
I'm sure there are others I haven't thought of yet.
Anything that helps me get from a series such as:
[1, 2, 2, 2, 3, 4, 5, 5, 3, 1] or more likely something like [1.2, 3.2, 3.1, 1.1, 4.3, 3.4] where it isn't just a case of counting the frequency of the item
to an actual distribution would be great.
Thanks.
**EDIT:** To clarify I guess I'm asking for more than just charting APIs, a search on Yahoo or Stack Overflow already finds answers to that. I'm looking for something that can help me turn data into visualizations with the least effort. So with the series above, something that could map it directly into some standard distributions such as a Gaussian distribution. | I like [Google Charts API](http://code.google.com/apis/chart/). It is brain-dead simple to use. You generate your data in the URL for an image, and the Google server spits back the GIF with the chart in it. You don't need JavaScript or Flash. | I use [JS Charts](http://www.jscharts.com/), which is a Javascript based one, looked simple and easy enough for me to use. They even have support for xml data in addition to js. It is free and they have got some [examples](http://www.jscharts.com/examples).
Works on IE and Chrome fine, so ideally should work on Firefox. as well.
On the Flash side, there is [Open Flash Chart](http://teethgrinder.co.uk/open-flash-chart/) , they have got some helper classes for major languages.
**Edit:** based on the additional information in question i guess Google Visualization API (<http://code.google.com/apis/visualization/>) might work out for you. | What are the best Javascript/Flash frameworks to render graphs or charts from data? | [
"",
"javascript",
"flash",
"statistics",
"charts",
"visualization",
""
] |
I am building an indexer application based on a suffix tree, that enables me to index whole documents and search strings, substrings, etc, extremely fast.
What I'm doing is entering a string in a textbox, pressing a button, and running a function that queries the suffixtree and adds the positions of all occurences of the string to a listbox. So the listbox has a lot of integers inside it.
Normally, this works fine. For instance, searching for "wizard" or "Gandalf", or "hobbit" (I am indexing FOTR as a test :D) works fine and dandy. However, I'm trying it out now with the letter e.
The problem is that the positions of the letter e do get listed inside the listbox. All 88974 of them. However, when I'm scrolling down by dragging the scroller button, the listbox appears to circularly go back to the top when I'm at around item 60000 or so. The problem is made wierder by the fact that I've tried scrolling with page down and everything works ok.
I know that scrolling through 88974 (based on listbox.Items.Count) items is a bit extreme, but logically, there is no reason why there should be such a problem.
Thanks for reading this far!
EDIT : To all those who answered, thanks for answering. I've finally implemented this with a listview, and it's much faster, and can hold many items quite well. Thanks! | Probably ListBox still uses the 16 bit range/position messages for scrollbars. You could try to reproduce it in Win32 if it's a problem of the underlying control.
You may want to try a list view control instead of the list box. I'd expect it to not run into this limitation, and its virtual mode should be more efficient, too. | It is a Vista specific bug. It goes bonkers when you scroll past 65536 + number of visible items. The bug did not get fixed in SP1. No problems in XP. But yes, that's a bug that rarely gets put to the test. | Windows Forms listbox is overflowing when there are too many items to scroll | [
"",
"c#",
".net",
"winforms",
"listbox",
""
] |
I'm trying to extend the `Array.push` method so that using push will trigger a callback method and then perform the normal array function.
I'm not quite sure how to do this, but here's some code I've been playing with unsuccessfully.
```
arr = [];
arr.push = function(data){
//callback method goes here
this = Array.push(data);
return this.length;
}
arr.push('test');
``` | Since *push* allows more than one element to be pushed, I use the *arguments* variable below to let the real push method have all arguments.
This solution only affects the *arr* variable:
```
arr.push = function () {
//Do what you want here...
return Array.prototype.push.apply(this, arguments);
}
```
This solution affects all arrays. I do not recommend that you do that.
```
Array.prototype.push = (function() {
var original = Array.prototype.push;
return function() {
//Do what you want here.
return original.apply(this, arguments);
};
})();
``` | First you need subclass `Array`:
ES6 (<https://kangax.github.io/compat-table/es6/>):
```
class SortedArray extends Array {
constructor(...args) {
super(...args);
}
push() {
return super.push(arguments);
}
}
```
ES5 (**proto** is almost deprecated, but it is the only solution for now):
```
function SortedArray() {
var arr = [];
arr.push.apply(arr, arguments);
arr.__proto__ = SortedArray.prototype;
return arr;
}
SortedArray.prototype = Object.create(Array.prototype);
SortedArray.prototype.push = function() {
this.arr.push(arguments);
};
``` | How can I extend Array.prototype.push()? | [
"",
"javascript",
"arrays",
"prototype",
"array-push",
""
] |
I'm designing a web driven SQL database application from ground up. The application will manage information for clients that are in the same type of industry. In other words, the information (entities and relations among them) regarding each client does not vary too much from one to the next. However, the volume of the information is dictated by the size of the company. The application could be hosted on our server(s) or anywhere a client chooses.
**My first question is: what are the pros and cons given the following options:**
* A. Manage multiple clients
information in the same database;
* B. Manage one client information per
database; so each client will have
its own database;
**My second question is: what are the pros and cons given the following methods of deployment?**
* A. Each client gets its own server (node);
* B. Use large RAID drive(s) with one powerful server with multiple websites;
As decisions to these choices affect my design, I would like to know the pros and cons from different perspectives including maintenance, cost(financially and in time) and architecture to name a few.
Technologies used:
* Database: MS SQL
* Platform: ASP.NET
* Language: C#
Any comments or suggestions are most welcome,
Thanks,
Cullen | I would not recommend giving each client their own database. I planned to do that for my current application and was talked into a single database. Good thing, since we now have 300 clients. Can you imagine managing 300 databases? Updating each one everytime you have an upgrade? Making sure each is up to date, etc.
Disclaimer: In practice we actually have several databases. A few very large clients have their own database and others share the remaining ones. I think maybe 7 databases in all.
We have the databases on one powerful SQL server. If you have multiple databases and put them on different servers, you run the risk that some servers are busier than others and small clients are underutilising their server. | I'd hybrid this. **Design it for the ability to use separate databases, but don't separate until there is a clear performance benefit.**
Design your application so that multiple clients can exist in the same database. (i.e. build a layer of separation between client data). Then plan for it all to be in one database.
That way, you don't overarchitect your solution to start out with, but it gives you the flexibility to spin off very high-usage clients to a dedicated database. If your database exists with only one client in it, so what? This will also save on server costs so that you can be sure that you're using the hardware investment in a reasonable way already before adding more capacity. | Software Architecture and Database Design: One database/web application per each company or one database/web application for all companies? | [
"",
"c#",
"sql-server",
"database-design",
"architecture",
"deployment",
""
] |
I recently refactored a piece of code used to generate unique negative numbers.
**edit:** Multiple threads obtain these ids and add as keys to a DB; numbers need to be negative to be easily identifiable -at the end of a test session they're removed from the DB.
My Java algorithm looks like this:
```
private final Set<Integer> seen = Collections.synchronizedSet(new HashSet<Integer>());
public Integer generateUniqueNegativeIds() {
int result = 0;
do {
result = random.nextInt();
if (result > 0) {
result *= -1;
}
} while (!seen.add(result));
return result;
}
```
The code structure above, with its speculative addition to the set and "retry" loop, makes me think there's an equivalent nonblocking algorithm that replaces the synchronized set with any of the [atomic variables](http://java.sun.com/docs/books/tutorial/essential/concurrency/atomicvars.html).
I made a few attempts to re-write using atomic variables but all failed the multithread attack test.
Is there an elegant nonblocking equivalent?
**edit:** for curiosity's sake here's a flawed attempt using an atomic integer as a guard
```
private final AtomicInteger atomi = new AtomicInteger(0);
public Integer generateUniqueNegativeIdsWithAtomicAlgo() {
boolean added = false;
int result = 0;
do {
result = random.nextInt();
if (result > 0) {
result *= -1;
}
if (atomi.compareAndSet(0, result)) {
added = cache.add(result);
}
} while (!added);
return atomi.getAndSet(0);
}
```
**edit:** test harness below:
```
public static void main(String[] args) {
final int NUMBER_OF_THREADS = 10000;
final Set<Integer> uniques = Collections.synchronizedSet(new HashSet<Integer>());
final List<Integer> positives = Collections.synchronizedList(new ArrayList<Integer>());
final NegativeUniqueIdGenerator nuig = new NegativeUniqueIdGenerator();
Thread[] workers = new Thread[NUMBER_OF_THREADS];
long start = System.nanoTime();
for (int i = 0; i < workers.length; i++) {
Runnable runnable = new Runnable() {
public void run() {
int number = nuig.generateUniqueNegativeIds();
if (number > 0) {
positives.add(number);
}
uniques.add(number);
}
};
workers[i] = new Thread(runnable);
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
try {
workers[i].join();
} catch (InterruptedException ie) {}
}
long end = System.nanoTime();
System.out.println(String.format("duration = %dns", (end - start)));
System.out.println(String.format("#threads = %d", NUMBER_OF_THREADS));
System.out.println(String.format("#uniques = %d", uniques.size()));
System.out.println(String.format("#positives = %d", positives.size()));
System.out.println(String.format("#duplicates = %d", NUMBER_OF_THREADS - uniques.size()));
System.out.println(String.format("ratio = %f",
((double) NUMBER_OF_THREADS - uniques.size())
/ NUMBER_OF_THREADS));
assert uniques.size() == NUMBER_OF_THREADS;
}
``` | From the requirements you've given, I would personally just use a medium-quality random number generator that you know won't produce duplicates within the number of unique numbers that you require. Unless you have an extra requirement you haven't mentioned, it seems overkill to keep the set of all the previously generated numbers.
For example, using a 32-bit XORShift generator will produce all 2^31 negative 4-byte integers in "random" order before repeating the pattern. If you need more numbers than that, you probably don't want to be putting them in a hash set anyway. So something like this (warning: off-top-of-head untested code...):
```
int seed = (int) System.nanoTime();
final int origSeed = seed;
public int nextUniqueNegativeNumber() {
int n = seed;
do {
n ^= (n << 13);
n ^= (n >>> 17);
n ^= (n << 5);
seed = n;
if (n == origSeed) {
throw new InternalError("Run out of numbers!");
}
} while (n > 0);
return n;
}
```
I'll leave it up to the reader to convert "seed" to use an AtomicInteger if concurrency is necessary...
Edit: actually, to optimise the concurrent case you maybe only want to write back to "seed" after getting the next *negative* number.
OK, by popular demand, the atomic version would then be something like this:
```
AtomicInteger seed = new AtomicInteger((int) System.nanoTime());
public int nextUniqueNegativeNumber() {
int oldVal, n;
do {
do {
oldVal = seed.get();
n = oldVal ^ (oldVal << 13); // Added correction
n ^= (n >>> 17);
n ^= (n << 5);
} while (seed.getAndSet(n) != oldVal);
} while (n > 0);
return n;
}
``` | If you're not concerned about the randomness, you can just decrement a counter, like this:
```
private final AtomicInteger ai=new AtomicInteger(0);
public int nextID() {
return ai.addAndGet(-1);
}
```
Edit:
For random numbers, you can just use your solution and use eg. ConcurrentHashMap or ConcurrentSkipListSet instead of the synchronizedSet. You have to ensure that different threads use different instances of the random generator, and that these generators are not correlated. | Nonblocking algorithm to generate unique negative numbers | [
"",
"java",
"algorithm",
"atomic",
"nonblocking",
""
] |
In the following jQuery JavaScript code, what value does the parameter "e" take on within the function? I'm having difficulty understanding this because this function cannot be passed an argument elsewhere in the code so how would having a parameter work? And how would I use parameters in such functions that are not named and not called anywhere else in the code?
```
$(document).ready( function() {
$('div').each(function() {
$(this).click(function(e){
//some code
});
});
});
``` | `click` sets the event handler. The click handler gets called by the browser when the event occurs, and the `e` parameter contains information about that event.
For keypress events, it contains which keys were pressed and what modifiers were pressed at that time (shift, control, etc.).
For mouse events, it contains the position of the click and which button was used.
See <http://www.quirksmode.org/js/events_properties.html> for more information about the properties of the event structure. | e is an *eventObject* as you can see in the [jQuery click documentation](http://docs.jquery.com/Events/click).
I do not know what you can do with it however, but it should contain information about the click event. Maybe it's the standard [DOM event](http://www.w3schools.com/htmldom/dom_obj_event.asp). | JavaScript: parameters for unnamed functions | [
"",
"javascript",
"parameters",
"function",
""
] |
What is the "critical section" of a thread (in Python)?
> A thread enters the critical section
> by calling the acquire() method, which
> can either be blocking or
> non-blocking. A thread exits the
> critical section, by calling the
> release() method.
- [Understanding Threading in Python, Linux Gazette](http://linuxgazette.net/107/pai.html)
Also, what is the purpose of a lock? | A critical section of code is one that can only be executed by one thread at a time. Take a chat server for instance. If you have a thread for each connection (i.e., each end user), one "critical section" is the spooling code (sending an incoming message to all the clients). If more than one thread tries to spool a message at once, you'll get BfrIToS mANtwD PIoEmesCEsaSges intertwined, which is obviously no good at all.
A lock is something that can be used to synchronize access to a critical section (or resources in general). In our chat server example, the lock is like a locked room with a typewriter in it. If one thread is in there (to type a message out), no other thread can get into the room. Once the first thread is done, he unlocks the room and leaves. Then another thread can go in the room (locking it). "Aquiring" the lock just means "I get the room." | Other people have given very nice definitions. Here's the classic example:
```
import threading
account_balance = 0 # The "resource" that zenazn mentions.
account_balance_lock = threading.Lock()
def change_account_balance(delta):
global account_balance
with account_balance_lock:
# Critical section is within this block.
account_balance += delta
```
Let's say that the `+=` operator consists of three subcomponents:
* Read the current value
* Add the RHS to that value
* Write the accumulated value back to the LHS (technically *bind* it in Python terms)
If you don't have the `with account_balance_lock` statement and you execute two `change_account_balance` calls in parallel you can end up interleaving the three subcomponent operations in a hazardous manner. Let's say you simultaneously call `change_account_balance(100)` (AKA pos) and `change_account_balance(-100)` (AKA neg). This could happen:
```
pos = threading.Thread(target=change_account_balance, args=[100])
neg = threading.Thread(target=change_account_balance, args=[-100])
pos.start(), neg.start()
```
* pos: read current value -> 0
* neg: read current value -> 0
* pos: add current value to read value -> 100
* neg: add current value to read value -> -100
* pos: write current value -> account\_balance = 100
* neg: write current value -> account\_balance = -100
Because you didn't force the operations to happen in discrete chunks you can have three possible outcomes (-100, 0, 100).
The `with [lock]` statement is a single, indivisible operation that says, "Let me be the only thread executing this block of code. If something else is executing, it's cool -- I'll wait." This ensures that the updates to the `account_balance` are "thread-safe" (parallelism-safe).
**Note:** There is a caveat to this schema: you have to remember to acquire the `account_balance_lock` (via `with`) every time you want to manipulate the `account_balance` for the code to remain thread-safe. There are ways to make this less fragile, but that's the answer to a whole other question.
**Edit:** In retrospect, it's probably important to mention that the `with` statement implicitly calls a blocking `acquire` on the lock -- this is the "I'll wait" part of the above thread dialog. In contrast, a non-blocking acquire says, "If I can't acquire the lock right away, let me know," and then relies on you to check whether you got the lock or not.
```
import logging # This module is thread safe.
import threading
LOCK = threading.Lock()
def run():
if LOCK.acquire(False): # Non-blocking -- return whether we got it
logging.info('Got the lock!')
LOCK.release()
else:
logging.info("Couldn't get the lock. Maybe next time")
logging.basicConfig(level=logging.INFO)
threads = [threading.Thread(target=run) for i in range(100)]
for thread in threads:
thread.start()
```
I also want to add that the lock's primary purpose is to guarantee the atomicity of acquisition (the indivisibility of the `acquire` across threads), which a simple boolean flag will not guarantee. The semantics of atomic operations are probably also the content of another question. | Python Threads - Critical Section | [
"",
"python",
"multithreading",
"language-agnostic",
""
] |
I have multiple lists of strings, `IList<string>`, that I want to consolidate in one list showing distinct string and count for each item (like a dictionary). what is the most efficient way to do this? | ```
Dictionary<string, int> count = new Dictionary<string, int>();
foreach(IList<int> list in lists)
foreach(int item in list) {
int value;
if (count.TryGetValue(item, out value))
count[item] = value + 1;
else
count[item] = 1;
}
``` | LINQ (certainly the most efficient in terms of code to type and maintain; the overall performance will be *about* the same as any other approach):
if the lists are in separate variables:
```
var qry = from s in listA.Concat(listB).Concat(listC) // etc
group s by s into tmp
select new { Item = tmp.Key, Count = tmp.Count() };
```
if the lists are all in a parent list (of lists):
```
var qry = from list in lists
from s in list
group s by s into tmp
select new { Item = tmp.Key, Count = tmp.Count() };
```
Then if you really want a list:
```
var resultList = qry.ToList();
``` | Adding Lists Together | [
"",
"c#",
""
] |
In a dictionary like this:
```
Dictionary<string, string> openWith = new Dictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
```
The output is:
> For Key = "rtf" value = wordpad.exe
What does the `{0}` mean? | You are printing a formatted string. The {0} means to insert the first parameter following the format string; in this case the value associated with the key "rtf".
For String.Format, which is similar, if you had something like
```
// Format string {0} {1}
String.Format("This {0}. The value is {1}.", "is a test", 42 )
```
you'd create a string "This **is a test**. The value is **42**".
You can also use expressions, and print values out multiple times:
```
// Format string {0} {1} {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1, 1+1, 1+2)
```
yielding "Fib: **1**, **1**, **2**, **3**"
See more at <http://msdn.microsoft.com/en-us/library/txafckwd.aspx>, which talks about composite formatting. | It's a placeholder in the string.
For example,
```
string b = "world.";
Console.WriteLine("Hello {0}", b);
```
would produce this output:
```
Hello world.
```
Also, you can have as many placeholders as you wish. This also works on `String.Format`:
```
string b = "world.";
string a = String.Format("Hello {0}", b);
Console.WriteLine(a);
```
And you would still get the very same output. | What does {0} mean when found in a string in C#? | [
"",
"c#",
"string",
"formatting",
""
] |
When I hover my mouse over a button in my program (Vista) the button turns blue (glows), I need to improve the way I guide my users through the program so I'm considering highlighting the appropriate button indicating the next step. Does this sound the wrong way to go or acceptable? I'm presuming I can code the button to glow.
Thanks | It depends on your target audience. Do you need to be cognizant of accessibility and users who are color blind, or legally blind? Additionally users can change the visual style of the OS, so you can't necessarily rely on being able to reproduce the "hover" effect.
In general, your UI design should be intuitive enough that you needn't add explicit visual cues on how to use it. Then again, it depends on what kind of app it is and what you are trying to achieve. | You shouldn't need colour to act as the next step indicator. What is it about your application that prevents "Next" or "Continue" buttoms from being used? Typically I'd stick with the expected norms that users for a particular platform have become accustomed too.
For 90% of applications, users just want to get something done as quickly and effectively as possible. So if you need colour to advise them of the next step then chances are your UI is too complicated. You may need to refactor some of your current single step screens into 2 or more less complicated screens.
Personally i think the better UI designs are the ones that we barely even notice. If the user has to waste brain cycles interpreting a UIs navigation system that requires them to associate blue with Go or Next then frankly i think its failed.... specially since where i come from "Green" would be more likely to mean "Go".
Btw who says you "need" to improve its navigation?? Do you really "need" too? Or do you just want to show off some potentially really cool, but probably completely unhelpful programming trick you just learnt? Cmon, be honest ;) | C# Light up button as it mouse is hovering? | [
"",
"c#",
"winforms",
""
] |
Consider the following code:
```
string propertyName;
var dateList = new List<DateTime>() { DateTime.Now };
propertyName = dateList.GetPropertyName(dateTimeObject => dateTimeObject.Hour);
// I want the propertyName variable to now contain the string "Hour"
```
Here is the extension method:
```
public static string GetPropertyName<T>(this IList<T> list, Func<T, object> func) {
//TODO: would like to dynamically determine which
// property is being used in the func function/lambda
}
```
Is there a way to do this? I thought that maybe this other method, using `Expression<Func<T, object>>` instead of `Func<T, object>` would give me more power to find what I need, but I am at a loss at how.
```
public static string GetPropertyName<T>(this IList<T> list, Expression<Func<T, object>> expr) {
// interrogate expr to get what I want, if possible
}
```
This is the first time I have done anything this deep with Linq, so maybe I am missing something obvious. Basically I like the idea of passing in lambdas, so that I get compile-time checking, but I don't know that my idea on how I can use them in this particular case will work.
Thanks | This is the version I use, it returns a `PropertyInfo`, but getting the name is trivial.
```
public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression)
{
MemberExpression memberExpression = null;
if (expression.Body.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression) expression.Body).Operand as MemberExpression;
}
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}
if (memberExpression == null)
{
throw new ArgumentException("Not a member access", "expression");
}
return memberExpression.Member as PropertyInfo;
}
``` | here is a very easy and fast way to do it on this blog: <http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx>
> So given:
>
> Func func = Name =>
> "Value";
>
> You can get the lambda parameter
> "Name" from the function delegate by
> calling:
>
> func.Method.GetParameters()[0].Name
> (would return "Name")
>
> Here's the revised Hash method from
> Andrey:
```
public Dictionary<string, T> Hash<T>(params Func<string, T>[] args)
where T : class
{
var items = new Dictionary<string, T>();
foreach (var func in args)
{
var item = func(null);
items.Add(func.Method.GetParameters()[0].Name, item);
}
return items;
}
```
Hope it helps,
Patrick | Can I get specific metadata from a Func<T, object>? | [
"",
"c#",
".net",
"linq",
"generics",
"reflection",
""
] |
Suppose a user is editing a record from a database,
in the schema you have a field named 'lock' so users can not edit
concurrently the same record, once the user ends editing you set
lock = false to allow other users to edit the record.
My question is, can i run some code when php session ends, so if a user
walks away from computer, close the browser or whatever, i can set the lock to false?.
Because if not, and correct me if I'm wrong, the record would remain locked?
I've read the `session_set_save_handler` section from php manual, but i'm not sure that
the 'close' callback it's what i need...
Or do I need to add a timestamp in the db schema and run a cronjob to 'unlock' the records
every x time?
Thanks! | I would not want to implement locking using your approach as described above, simply because of the reasons you mentioned in the second paragraph.
What I would do is to have a timestamp column in the table. Whenever an attempt is made to write to that table, it should be read first then its timestamp noted (say, in a session variable somewhere). Before writing the updated information back into the row I will take a look at the timestamp and ensure that its timestamp is exactly the same one that I saw (and noted in the session var). If it's not, someone updated the row while I wasn't looking (in this case, while you presented a form to the user and the user has not submitted the form back to the server yet).
This approach is what many O/RMs use to ensure that one session is not overwriting changes made in another session inadvertently. The upside to this approach is that you do not run the chance of a "lock" getting left by a user who's abandoned the session, and you don't need to have a cron job to unlock stale locks. The downside to this approach is that you would only know about the collision the moment you try to update the record in the DB. This means the user would have already submitted a form containing the data changes, and you would have to inform the user that he/she has to try again (after, say, presenting the updated/latest information from that record). | I think you're better of with the lock timestamp you described. The problem with the session closed callbacks is that you can never be certain that they get called. For instance, what happens if someone shuts down your webserver, or worse, kills the process. You want DB consistency in those situations as well. | release a db lock when php session ends? | [
"",
"php",
"database",
"session",
"locking",
""
] |
In my main method, I start the main form as usual:
```
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
```
In the main forms load thing I have the following, which will ask the user to log in and stuff.
```
using (loginForm)
{
DialogResult r = loginForm.ShowDialog();
switch (r)
{
case DialogResult.OK:
break;
default:
Application.Exit();
return;
}
}
```
My problem is that the main form shows up in the background, and I want it to, well... not. until the login is ok. How should I do this? The Application.Run() method say it automatically shows the form. Is there an alternative way of starting the main form without showing it? Or do I have to set visible to false in the constructor of the main form, and then back to true when log in is done, or something similar? What is the recommended way of doing something like that? The login forms intention is like a combined splash screen and login. So first it loads and sets up some different things, and then it tells the user to login. | Instead of:
```
Application.Run(new MainForm());
```
try:
```
LoginDialog // the class that handles login UI
login = new LoginDialog ();
if (login.ShowDialog () == DialogResult.OK)
{
// check credentials
// if credentials OK
Application.Run(new MainForm());
}
```
The `ShowDialog` method is a blocking call, the program will halt until the dialog is closed in response to user input - by pressing an 'OK' button or 'Cancel' button. | The simplest would be to start the login form with Application.Run. When the login is ok and other stuff has been set just show the 'main' form.
```
Application.Run(new LoginForm());
```
and in login form on the OK button:
```
this.Visible = false;
this.ShowInTaskbar = false;
MainForm mainForm = new MainForm();
mainForm.Show();
``` | C#: How to prevent main form from showing too early | [
"",
"c#",
"winforms",
""
] |
As you most likely already know, it's simple in JQuery to select all elements in the document that have a specific CSS class, and then, using chaining, assign common event handlers to the selected elements:
```
$(".toolWindow").click(toolWindow_click);
$(".toolWindow").keypress(toolWindow_keypress);
```
As usual the class "toolWindow" is also normally defined in CSS and associated with some visual styles:
```
.toolWindow{
color:blue;
background-color:white;
}
```
The class attribute is now responsible for indicating not just the appearance (visual state) of the element, but also the behaviour. As a result, I quite often use this approach and define CSS class names more as pseudo object oriented classes then visual only CSS classes. In other words, each class represents both state (CSS styles) and behaviour (events).
In some cases I have even created classes with no visual styling and simply use them as a convenient way to assign behaviour to elements.
Moreover, the jQuery LiveQuery plugin (and the live() built-in function) make this approach even more effective by automatically binding events to dynamically created elements belonging to a specificed class.
Of late I am primarily using class names as defining a common set of behaviour for associated DOM elements and only later using them to define a visual style.
Questions: Is this a terrible misuse of the CSS "class" attribute, if so why?
On the other hand, perhaps it is a perfectly valid approach to further implementing "separate of concerns" and improving the maintainability of HTML/DHTML pages? | The "class" is actually part of the document data (and hopefully semantically relevant) not the style or design of it.
This is why it's okay to use for both. | 1. It is perfectly valid approach to do so.
2. Class attributes don't define behaviour - JS does it, via CSS *selectors* (thank you jQuery).
3. Class attributes don't define visual styles - CSS *rules* do it. | Misuse of the CSS class attribute, or valid design pattern? | [
"",
"javascript",
"jquery",
"html",
"css",
"oop",
""
] |
I have a form where users can enter the amount they spend on their phone bill and then I tell them how much they could save if they switched to vonage, skype etc.
I pass the value "$monthlybill" in the url and then do some math to it. The problem is that if the user writes "$5" instead of "5" in the form, it breaks and is not recognized as a number. How do i strip out the dollar sign from a value? | ```
$monthlybill = str_replace("$", "", $monthlybill);
```
You might also want to look at the [money\_format function.](https://www.php.net/manual/en/function.money-format.php) if you are working with cash amounts. | [Ólafur's](https://stackoverflow.com/questions/580019/stripping-from-php-values/580029#580029) solution works, and is probably what I'd use, but you could also do:
```
$monthlybill = ltrim($monthlybill, '$');
```
That would remove a $ at the beginning of the string.
You can then validate further that it is a monetary amount depending on your needs. | Stripping $ from php values | [
"",
"php",
""
] |
I am using C#.
I am trying to pull in a text file to an object. I am using an ODBC connection and it looks like this
Driver={Microsoft Text Driver (\*.txt; \*.csv)};Dbq=C:\Users\Owner\Desktop\IR\IR\_Files\Absolute;Extensions=asc,csv,tab,txt;
I am able to make the connection but I can't get my columns separated. I'm using a schema.ini file but it isn't working. Here is my schema file.
[MyTextFile.CSV]
Format=Delimited(|)
ColNameHeader=False
Col1=fullstockn Text
col2=FULLINFO Text
MaxScanRows=0
CharacterSet=ANSI
The text file looks like this.
fullstockn|FULLINFO
"555555 "|
Contenu : Neuf Ttudes sur l Some more text here..... | I use the following connection string
```
string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"text;HDR=YES;Format=Delimited(|)\";", Path.GetDirectoryName(path));
```
and a Schema.ini file that typically begins
```
[myFile.txt]
Format=Delimited(|)
TextDelimiter="none"
```
and I'll execute a reader via
```
command.CommandText = String.Format("SELECT * FROM [{0}]", Path.GetFileName(path));
OleDbDataReader reader = command.ExecuteReader();
```
Also, the [MSDN page](http://tinyurl.com/caqkpr) on the text file driver was helpful when I first investigated this. Specifically, the [page](http://msdn.microsoft.com/en-us/library/ms709353.aspx) on the `Schema.ini` file is quite useful. | Is there a reason you need to use an ODBC connection for this? I would think it'd be easier to just open the text file directly and parse it yourself. | Can't Separate Text File By Delimiter | | [
"",
"c#",
"text-files",
"flat-file",
"csv",
""
] |
Does it make sense to restrict yourself to the STL libraries when learning C++ and then tackle boost and its additions after you have become fairly proficient with vanilla C++?
Or should you dive right into BOOST while learning C++? | The STL has some core concepts to it. Boost builds on and expands on them. If you understand them, then moving right on to Boost may be of use to you. If not, I would start with the STL.
* The distinction between the various container types (sequences like `vector`, `list` and `deque`, and associations like `map`, `set` and their `multi*` and `unordered_*` varieties). Sometimes you can swap one for the other -- sometimes you can't. Know their strengths and their limits.
* The role of iterators, and how they provide a bridge between containers and algorithms. (This one I find I use over and over).
* Why there are standard algorithms: they are often tiny amounts of code, so it may not be obvious why they exist. Learn which containers they work with, and how to specialize them for particular cases (for example see how generic `copy` differs from `copy` specialized for `const char *`).
* How and when traits classes are used.
* How to use binders (`bind1st`, `ptr_fun` and `mem_fun`): the syntax can obscure their utility.
* How to use `string` -- and when *not* to use it. (All string classes have tradeoffs: learning the pros and cons of the standard one is educational).
* The difference between streams and streambufs: how to use the former to do formatted I/O (try reading a string from a stream: it's not as straightforward as it should be), and the latter to do low-level fast I/O.
The principles used to design the STL are built upon and expanded on by the Boost libraries. If you get them, Boost is manageable. If you don't, and Boost ends up hard to follow, you can go back to the STL to get your bearings.
(In general Boost really pushes the boundaries of the language. If you decide you want to really push your own knowledge of C++, and test if you really know what you think you know then it can provide an interesting challenge. I've used C++ for more than a dozen years, have taught other people how to use it, have acquired proficiency in many more high-level languages since then and Boost still surprises me. It's *very* useful, but its not trivial). | I'd suggest getting a clear handle on STL, before looking at Boost. Boost is meant to build on top of STL and many of the libraries are slated to become part of the standard library eventually. Boost libraries are generally less mature and less standard than STL. Also, many boost libraries go too far, in my opinion, adding "features" that don't natively exist in C++ (leading to really insane syntax). In many cases there are more sane C++ idioms available for solving most programming problems without using these arcane Boost libraries. | Should I become proficient with STL libraries before learning BOOST alternatives? | [
"",
"c++",
"stl",
"boost",
""
] |
I am currently working on a mantenance project that is written in Java. We are currently working to clean up the code some and try to provide a little more organization to the project overall.
The list of libraries that are included in the build have grown long, and honestly no one remains that knows/remembers what each library is used for or why? So I am looking for a tool that would be able to essentially find where the library is used in the code. Essentially like a find usage function in an IDE has for functions.
Does such a tool exist? I am curently using Netbeans and as mentioned our code is in java.
I know I could remove each library and compile the project for each library to find the usages, but it just seems there should be a better way. Any ideas? | Since you're using NetBeans, I suggest the [SQE](https://sqe.dev.java.net/) plugin, which includes [Dependency Finder](http://depfind.sourceforge.net/). (And if you weren't already using FindBugs, this is a good time to start.) | Try using [jarjar](http://code.google.com/p/jarjar/). It has a command line interface that will analyze your dependency tree. | Java library inspector? | [
"",
"java",
""
] |
There are a few ways to include jQuery and jQuery UI and I'm wondering what people are using?
* Google JSAPI
* jQuery's site
* your own site/server
* another CDN
I have recently been using Google JSAPI, but have found that it takes a long time to setup an SSL connection or even only to resolve google.com. I have been using the following for Google:
```
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.3.1');
</script>
```
I like the idea of using Google so it's cached when visiting other sites and to save bandwidth from our server, but if it keeps being the slow portion of the site, I may change the include.
What do you use? Have you had any issues?
**Edit:** Just visited jQuery's site and they use the following method:
```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
```
**Edit2:** Here's how I've been including jQuery without any problems for the last year:
```
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
```
The difference is the removal of `http:`. By removing this, you don't need to worry about switching between http and https. | Without a doubt I choose to have JQuery served by Google API servers. I didn't go with the jsapi method since I don't leverage any other Google API's, however if that ever changed then I would consider it...
**First:** The Google api servers are distributed across the world instead of my single server location: Closer servers usually means faster response times for the visitor.
**Second:** Many people choose to have JQuery hosted on Google, so when a visitor comes to my site they may already have the JQuery script in their local cache. Pre-cached content usually means faster load times for the visitor.
**Third:** My web hosting company charges me for the bandwidth used. No sense consuming 18k per user session if the visitor can get the same file elsewhere.
I understand that I place a portion of trust on Google to serve the correct script file, and to be online and available. Up to this point I haven't been disappointed with using Google and will continue this configuration until it makes sense not to.
**One thing worth pointing out...** If you have a mixture of secure and insecure pages on your site you might want to dynamically change the Google source to avoid the usual warning you see when loading insecure content in a secure page:
Here's what I came up with:
```
<script type="text/javascript">
document.write([
"\<script src='",
("https:" == document.location.protocol) ? "https://" : "http://",
"ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js' type='text/javascript'>\<\/script>"
].join(''));
</script>
```
**UPDATE 9/8/2010** -
Some suggestions have been made to reduce the complexity of the code by removing the HTTP and HTTPS and simply use the following syntax:
```
<script type="text/javascript">
document.write("\<script src='//ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js' type='text/javascript'>\<\/script>");
</script>
```
In addition you could also change the url to reflect the jQuery major number if you wanted to make sure that the latest Major version of the jQuery libraries were loaded:
```
<script type="text/javascript">
document.write("\<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'>\<\/script>");
</script>
```
Finally, if you don't want to use Google and would prefer jQuery you could use the following source path (keep in mind that jQuery doesn't support SSL connections):
```
<script type="text/javascript">
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
</script>
``` | One reason you might want to host on an external server is to work around the browser limitations of concurent connections to particular server.
However, given that the jQuery file you are using will likely not change very often, the browser cache will kick in and make that point moot for the most part.
Second reason to host it on external server is to lower the traffic to your own server.
However, given the size of jQuery, chances are it will be a small part of your traffic. You should probably try to optimize your actual content. | Where do you include the jQuery library from? Google JSAPI? CDN? | [
"",
"javascript",
"jquery",
"ssl",
"google-ajax-libraries",
""
] |
I need to copy the subscribers of one event to another event. Can I get the subscribers of an event (like MyEvent[0] returning a delegate)?
If this is not possible I would use the add accessor to add the delegates to a list. Would that be the best solution? | C# events/delegates are multicast, so the delegate is *itself* a list. From within the class, to get individual callers, you can use:
```
if (field != null)
{
// or the event-name for field-like events
// or your own event-type in place of EventHandler
foreach(EventHandler subscriber in field.GetInvocationList())
{
// etc
}
}
```
However, to assign all at once, just use += or direct assignment:
```
SomeType other = ...
other.SomeEvent += localEvent;
``` | If the event is one published by another class, you can't - at least, not reliably. While we often think of an event as being just a delegate variable, it's actually just a pair of methods: add and remove (or subscribe and unsubscribe).
If it's your own code that's publishing the event, it's easy - you can make the add/remove accessors do whatever you like.
Have a look at [my article on events](http://pobox.com/~skeet/csharp/events.html) and see if that helps you. If not, please give more details about what you want to do, specifying which bits of code you're able to modify and which you aren't. | How do I get the subscribers of an event? | [
"",
"c#",
"events",
""
] |
I want to use a collection initializer for the next bit of code:
```
public Dictionary<int, string> GetNames()
{
Dictionary<int, string> names = new Dictionary<int, string>();
names.Add(1, "Adam");
names.Add(2, "Bart");
names.Add(3, "Charlie");
return names;
}
```
So typically it should be something like:
```
return new Dictionary<int, string>
{
1, "Adam",
2, "Bart"
...
```
But what is the correct syntax for this? | ```
var names = new Dictionary<int, string> {
{ 1, "Adam" },
{ 2, "Bart" },
{ 3, "Charlie" }
};
``` | The syntax is slightly different:
```
Dictionary<int, string> names = new Dictionary<int, string>()
{
{ 1, "Adam" },
{ 2, "Bart" }
}
```
Note that you're effectively adding tuples of values.
As a sidenote: collection initializers contain arguments which are basically arguments to whatever *Add()* function that comes in handy with respect to compile-time type of argument. That is, if I have a collection:
```
class FooCollection : IEnumerable
{
public void Add(int i) ...
public void Add(string s) ...
public void Add(double d) ...
}
```
the following code is perfectly legal:
```
var foos = new FooCollection() { 1, 2, 3.14, "Hello, world!" };
``` | Can I use a collection initializer for Dictionary<TKey, TValue> entries? | [
"",
"c#",
".net",
"generics",
"collections",
"c#-3.0",
""
] |
I have a collection of polymorphic objects, all derived from my Animal class: Cat, Dog, and MonkeyFish.
My usual mode of operation is to store these objects in a vector of Animal pointers, like so:
std::vector< Animal \* > my\_vector;
```
my_vector.push_back( new Animal_Cat() );
my_vector.push_back( new Animal_Dog() );
my_vector.push_back( new Animal_MonkeyFish() );
```
And life is great...or is it?
I've recently been told that I should really try to avoid allocating memory in this fashion, because it makes memory management a chore. When I need to destroy my\_vector, I have to iterate through all the elements and **delete** everything.
I don't think that I can store a vector of references (I might be wrong about this), so it seems like storing a vector of Animal objects is my only alternative.
When should I choose to use a vector of pointers versus a vector of objects? In general, which method is preferable? (I would like to reduce object copying as much as possible.) | You should use a vector of objects whenever possible; [but in your case it isn't possible](https://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c).
Containers of pointers let you avoid the slicing problem. But then you have to call delete on each element, like you are doing. That's annoying but possible. Unfortunately there are cases (when an exception is thrown) where you can't be sure that delete is properly called, and you end up with a memory leak.
The main solution is to use a smart pointer. Pre-C++11 comes with `auto_ptr`, [but that cannot be used in a standard container](http://www.gotw.ca/publications/using_auto_ptr_effectively.htm). C++11 has `std::unique_ptr` and `std::shared_ptr` which are designed to be usable in containers (I prefer `std::unique_ptr` unless I really need reference counting). If you can't use C++11, the best solution is [Boost smart pointers](http://www.boost.org/libs/smart_ptr). | In this case, storing a vector of `Animal` would not work for you, as your animals have different sizes, and you wouldn't be able to store the derived objects in the spaces intended to hold the base class. (And even if they're the same size, you won't get the intended polymorphic effect, as base class methods will be executed - the virtualness of a method doesn't come into play unless you access it through a pointer or reference.)
If you want to avoid the annoyance of managing the memory yourself, you could consider storing a smart pointer such as a [shared\_ptr](http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm) (note that [auto\_ptr](http://en.wikipedia.org/wiki/Auto_ptr) doesn't work with STL containers, according to Max Lybbert), or some variant thereof. That way you can still use your polymorphic class, but it's a little less work for you.
There's no real hard and fast rules about when to use objects and pointers, although it's worth noting that in some cases, like yours, objects just aren't going to work for you. I tend to use objects whenever nothing precludes it though, although you do have to be concerned about expensive copy operations as you note (although sometimes they can be ameliorated by passing containers by reference). | When should I use a vector of objects instead of a vector of pointers? | [
"",
"c++",
""
] |
How would one create a ***deterministic*** Javascript HTML colour picker which given arguments of how many colours are desired returns an array of HTML hex colour codes, ie:
```
function createColours(numColours) {
return [/* colours array of size numColours */]
}
```
The colours themselves can be *chosen / generated* randomly, but the method must guarantee that colours chosen are always the same between calls and always in the same order in series.
For example, if the series of colours decided on by the function started with the following 8:
```
"#47092E", "#CC2A43", "#00C66B", "#BC1300", "#667E00", "#795800", "#FFD245", "#6EFFAD", etc, etc
```
The function would behave with the following consistent responses across separate method invocations on the client
```
["#47092E", "#CC2A43"] == createColours(2);
["#47092E", "#CC2A43", "#00C66B", "#BC1300", "#667E00"] == createColours(5);
["#47092E"] == createColours(1);
["#47092E", "#CC2A43", "#00C66B", "#BC1300", "#667E00", "#795800", "#FFD245", "#6EFFAD", #and 49 others#] == createColours(57);
```
**Note**: The colours are not defined as a variable in advance; the method might be asked for 345 colours, all of which it would be required to generate by whatever suitable means.
The problem to be solved is - **first and foremost** - how would you create a capability within the method to generate the n HEX colour values consistently the same each time also preserving the sequence | You need to use a pseudo random number generator (PRNG), with a fixed start seed. The Math.random method in javascript is a PRNG, but you can't set the seed like you can in other languages.
A PRNG is reasonably simple to create - lots of code on the internet. Given a fixed start seed it will always generate the same sequence of random numbers, which is what you're asking for.
Whether those colors look pleasing or not, is [another question entirely](https://stackoverflow.com/questions/43044/coloring-algorithm)...
One javascript implementation with seeding capability:
<http://www.erikoest.dk/rng2.htm>
You'll also find C implementations (easy to convert to javascript) and other details of building your own PRNG of the Lehmer type here:
<http://www.google.com/search?q=Lehmer%20random%20number%20generator>
Another one with code ([Mersenne twister](http://en.wikipedia.org/wiki/Mersenne_Twister)):
<http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVASCRIPT/java-script.html>
This question covers several types of PRNG in javascript:
[Seedable JavaScript random number generator](https://stackoverflow.com/questions/424292/how-to-create-my-own-javascript-random-number-generator-that-i-can-also-set-the-s)
If you give the same starting seed to the PRNG at the beginning of the function, it will always return the same number sequence with each successive call.
Convert that number into a color, and you're all set.
-Adam | Using the answers provided above, and the RNG code [here](https://stackoverflow.com/questions/424292/how-to-create-my-own-javascript-random-number-generator-that-i-can-also-set-the-s), I ended up with (assumes using of [Prototype](http://prototypejs.org/) library for class creation):
```
var ColourPicker = Class.create({
initialize: function() {
this.hash = '#';
this.rngRed = new RNG(5872323); // using same seed always guarantees number order response same
this.rngGreen = new RNG(332233);
this.rngBlue = new RNG(3442178);
},
numberToHex: function(number, padding) {
var hex = number.toString(16);
return hex;
},
createColours: function(numColours) {
var colours = [];
for (var i = numColours - colours.length; i-- > 0;) {
var r = this.rngRed.nextRange(5,240);
var g = this.rngGreen.nextRange(10,250);
var b = this.rngBlue.nextRange(0,230);
colours.push(this.hash + this.numberToHex(r) + this.numberToHex(g) + this.numberToHex(b));
}
return colours;
}
});
var colourPicker = new ColourPicker();
var colours = colourPicker.createColours(10);
for (var i = 0 ; i < colours.length ; i++) {
alert(colours[i]);
}
``` | Create programmatic colour picker | [
"",
"javascript",
"colors",
"random",
"color-picker",
"prng",
""
] |
The following for creating a Global Object is resulting in compilation errors.
```
#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace std;
#pragma hdrstop
class Tester;
void input();
class Tester
{
static int number = 5;
public:
Tester(){};
~Tester(){};
void setNumber(int newNumber)
{
number = newNumber;
}
int getNumber()
{
return number;
}
}
Tester testerObject;
void main(void)
{
cout << "Welcome!" << endl;
while(1)
{
input();
}
}
void input()
{
int newNumber = 0;
cout << "The current number is " << testerObject.getNumber();
cout << "Change number to: ";
cin >> newNumber;
cout << endl;
testerObject.setNumber(newNumber);
cout << "The number has been changed to " << testerObject.getNumber() << endl;
}
```
Here are the compile errors:
```
1>------ Build started: Project: test, Configuration: Debug Win32 ------
1>Compiling...
1>test.cpp
1>.\test.cpp(15) : error C2864: 'Tester::number' : only static const integral data members can be initialized within a class
1>.\test.cpp(33) : error C2146: syntax error : missing ';' before identifier 'testerObject'
1>.\test.cpp(33) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\test.cpp(49) : error C2039: 'getNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>.\test.cpp(55) : error C2039: 'setNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>.\test.cpp(57) : error C2039: 'getNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>Build log was saved at "file://c:\Users\Owner\Documents\Visual Studio 2008\Projects\test\test\Debug\BuildLog.htm"
1>test - 6 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
```
1. How do I create a Global Class
Object correctly like I've attempted
here.
2. And how do I fix that "only static
const integral data members can be
initialized within a class"
3. And basically how do I fix the rest
of the errors so I can get this to
compile?
I like declaring Global Class Objects at file scope (I like declaring all globals at file scope) because when I have to create separate source files and do "extern" and everything it becomes extremely complicated and never works for me. Although, I do want to figure out how to do that eventually... it seems every tutorial I look at won't compile though and unless it compiles I have no idea how to recreate it!
If I can just get this to compile...then I can successfully learn how to do this. So if someone could rewrite the above to where it literally copies & pastes into Visual C++ Express 2008 and works I will finally be able to figure out how to recreate it. I'm extremely excited on seeing the fix for this! It is just I can't get Global Objects to work right! Any other information on declaring Global Class Objects...or anything for that matter is welcome! | Just start addressing the errors one by one. A lot of the errors are just cascaded from the initial errors, so it looks like there are a lot of problems when there's only a couple. Just start from the top:
```
1>.\test.cpp(15) : error C2864: 'Tester::number' : only static const integral data members can be initialized within a class
```
You can't initialize a member in the class definition unless it's static, const, and one of the integral types. Leave the "`= 5`" off of the declaration of `number`. Then you'll need to have a definition of `Tester::number` outside of the class definition, like so:
```
int Tester::number = 5;
```
Problem #2:
```
1>.\test.cpp(33) : error C2146: syntax error : missing ';' before identifier 'testerObject'
```
Almost exactly what it says (missing semi-colon errors can be a bit inexact in saying where the semicolon should be) - you need a semi-colon after the definition of the `Tester` class.
Fix those and your compilation problems go away.
The key thing is to try and take compiler errors one at a time from the top. If you get more than about 3 of them, you can probably just ignore everything after the 3rd or so because the initial error just cause the compile to into the weeds (and if they are real errors, they'll show up again in the next compile anyway). | * Error C2864: either add a `const` modifier to your integer, or move the initialization outside the class (as in `class Tester { static int number; }; int Tester::number = 5;`). The latter seems more appropriate to your case.
* Error C2146: you're missing a semicolon after the declaration of `class Tester { ... }`. It should be `class Tester { ... }`**`;`**
The other errors are probably caused by the previous error. They should fix themselves automatically when it is fixed.
As a side note, I don't think you really want the `static` modifier on your member. It seems more appropriate for an instance field. You still can't initialize it in-place though (this isn't C#), you have to move the initialization to the constructor. For example:
```
class Tester {
int number;
static int staticNumber; // just to show you how to use a static field
public:
Tester() : number(5) {}
~Tester() {} // I suggest you remove the destructor unless you need it
int getNumber() { return number; }
void setNumber(int value) { number = value; }
static int getStaticNumber() { return staticNumber; }
static void setStaticNumber(int value) { staticNumber = value; }
};
// initialize static members *outside* the class
int Tester::staticNumber = 5;
``` | Resolving "only static const integral data members can be initialized within a class" compilation error | [
"",
"c++",
"visual-studio",
"compiler-errors",
""
] |
I think its possible but i cant come up with the right algorithm for it.
What i wanted to do was:
If today is monday feb 2 2009, how would i know the date of last week's tuesday? Using that same code 2 days after, i would find the same date of last week's tuesday with the current date being wednesday, feb 4 2009. | I know there is an accepted answer already, but imho it does not meet the second requirement that was asked for. In the above case, strtotime would yield yesterday if used on a wednesday. So, just to be exact you would still need to check for this:
```
$tuesday = strtotime('last Tuesday');
// check if we need to go back in time one more week
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400 : $tuesday;
```
---
As davil pointed out in his comment, this was kind of a quick-shot of mine. The above calculation will be off by one once a year due to daylight saving time. The good-enough solution would be:
```
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400+7200 : $tuesday;
```
If you need the time to be 0:00h, you'll need some extra effort of course. | Most of these answers are either too much, or technically incorrect because "last Tuesday" doesn't necessarily mean the Tuesday from last week, it just means the previous Tuesday, which could be within the same week of "now".
The correct answer is:
```
strtotime('tuesday last week')
``` | how to get the date of last week's (tuesday or any other day) in php? | [
"",
"php",
"date",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.