Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
How to write bits (not bytes) to a file with c#, .net? I'm preety stuck with it.
**Edit**: i'm looking for a different way that just writing every 8 bits as a byte | The smallest amount of data you can write at one time is a byte.
If you need to write individual bit-values. (Like for instance a binary format that requires a 1 bit flag, a 3 bit integer and a 4 bit integer); you would need to buffer the individual values in memory and write to the file when you have a whole byte to write. (For performance, it makes sense to buffer more and write larger chunks to the file). | 1. Accumulate the bits in a buffer (a single byte can qualify as a "buffer")
2. When adding a bit, left-shift the buffer and put the new bit in the lowest position using OR
3. Once the buffer is full, append it to the file | How to write bits to a file? | [
"",
"c#",
".net",
"io",
"bit",
""
] |
Suppose I want to lock based on an integer id value. In this case, there's a function that pulls a value from a cache and does a fairly expensive retrieve/store into the cache if the value isn't there.
The existing code isn't synchronized and could potentially trigger multiple retrieve/store operations:
```
//psuedocode
public Page getPage (Integer id){
Page p = cache.get(id);
if (p==null)
{
p=getFromDataBase(id);
cache.store(p);
}
}
```
What I'd like to do is synchronize the retrieve on the id, e.g.
```
if (p==null)
{
synchronized (id)
{
..retrieve, store
}
}
```
Unfortunately this won't work because 2 separate calls can have the same Integer id value but a different Integer object, so they won't share the lock, and no synchronization will happen.
Is there a simple way of insuring that you have the same Integer instance? For example, will this work:
```
syncrhonized (Integer.valueOf(id.intValue())){
```
The javadoc for Integer.valueOf() seems to imply that you're likely to get the same instance, but that doesn't look like a guarantee:
> Returns a Integer instance
> representing the specified int value.
> If a new Integer instance is not
> required, this method should generally
> be used in preference to the
> constructor Integer(int), as this
> method is likely to yield
> significantly better space and time
> performance by caching frequently
> requested values.
So, any suggestions on how to get an Integer instance that's guaranteed to be the same, other than the more elaborate solutions like keeping a WeakHashMap of Lock objects keyed to the int? (nothing wrong with that, it just seems like there must be an obvious one-liner than I'm missing). | You really don't want to synchronize on an `Integer`, since you don't have control over what instances are the same and what instances are different. Java just doesn't provide such a facility (unless you're using Integers in a small range) that is dependable across different JVMs. If you really must synchronize on an Integer, then you need to keep a Map or Set of Integer so you can guarantee that you're getting the exact instance you want.
Better would be to create a new object, perhaps stored in a `HashMap` that is keyed by the `Integer`, to synchronize on. Something like this:
```
public Page getPage(Integer id) {
Page p = cache.get(id);
if (p == null) {
synchronized (getCacheSyncObject(id)) {
p = getFromDataBase(id);
cache.store(p);
}
}
}
private ConcurrentMap<Integer, Integer> locks = new ConcurrentHashMap<Integer, Integer>();
private Object getCacheSyncObject(final Integer id) {
locks.putIfAbsent(id, id);
return locks.get(id);
}
```
To explain this code, it uses `ConcurrentMap`, which allows use of `putIfAbsent`. You could do this:
```
locks.putIfAbsent(id, new Object());
```
but then you incur the (small) cost of creating an Object for each access. To avoid that, I just save the Integer itself in the `Map`. What does this achieve? Why is this any different from just using the Integer itself?
When you do a `get()` from a `Map`, the keys are compared with `equals()` (or at least the method used is the equivalent of using `equals()`). Two different Integer instances of the same value will be equal to each other. Thus, you can pass any number of different Integer instances of "`new Integer(5)`" as the parameter to `getCacheSyncObject` and you will always get back only the very first instance that was passed in that contained that value.
There are reasons why you may not want to synchronize on `Integer` ... you can get into deadlocks if multiple threads are synchronizing on `Integer` objects and are thus unwittingly using the same locks when they want to use different locks. You can fix this risk by using the
```
locks.putIfAbsent(id, new Object());
```
version and thus incurring a (very) small cost to each access to the cache. Doing this, you guarantee that this class will be doing its synchronization on an object that no other class will be synchronizing on. Always a Good Thing. | Use a thread-safe map, such as `ConcurrentHashMap`. This will allow you to manipulate a map safely, but use a different lock to do the real computation. In this way you can have multiple computations running simultaneous with a single map.
Use `ConcurrentMap.putIfAbsent`, but instead of placing the actual value, use a `Future` with computationally-light construction instead. Possibly the `FutureTask` implementation. Run the computation and then `get` the result, which will thread-safely block until done. | Synchronizing on an Integer value | [
"",
"java",
"synchronization",
""
] |
I have a pretty simple question. I want to make some date-based generic views on a Django site, but I also want to paginate them. According to the documentation the object\_list view has page and paginate\_by arguments, but the archive\_month view does not. What's the "right" way to do it? | Date based generic views don't have pagination. It seems you can't add pagination via wrapping them as well since they return rendered result.
I would simply write my own view in this case. You can check out generic views' code as well, but most of it will probably be unneeded in your case.
Since your question is a valid one, and looking at the code; I wonder why they didn't decouple queryset generation as separate functions. You could just use them and render as you wish then. | I created a template tag to do template-based pagination on collections passed to the templates that aren't already paginated. Copy the following code to an `app/templatetags/pagify.py` file.
```
from django.template import Library, Node, Variable
from django.core.paginator import Paginator
import settings
register = Library()
class PagifyNode(Node):
def __init__(self, items, page_size, varname):
self.items = Variable(items)
self.page_size = int(page_size)
self.varname = varname
def render(self, context):
pages = Paginator(self.items.resolve(context), self.page_size)
request = context['request']
page_num = int(request.GET.get('page', 1))
context[self.varname] = pages.page(page_num)
return ''
@register.tag
def pagify(parser, token):
"""
Usage:
{% pagify items by page_size as varname %}
"""
bits = token.contents.split()
if len(bits) != 6:
raise TemplateSyntaxError, 'pagify tag takes exactly 5 arguments'
if bits[2] != 'by':
raise TemplateSyntaxError, 'second argument to pagify tag must be "by"'
if bits[4] != 'as':
raise TemplateSyntaxError, 'fourth argument to pagify tag must be "as"'
return PagifyNode(bits[1], bits[3], bits[5])
```
To use it in the templates (assume we've passed in an un-paginated list called **items**):
```
{% load pagify %}
{% pagify items by 20 as page %}
{% for item in page %}
{{ item }}
{% endfor %}
```
The page\_size argument (the 20) can be a variable as well. The tag automatically detects `page=5` variables in the querystring. And if you ever need to get at the paginator that belong to the page (for a page count, for example), you can simply call:
```
{{ page.paginator.num_pages }}
``` | Pagination of Date-Based Generic Views in Django | [
"",
"python",
"django",
"pagination",
""
] |
I have a site that has an IE8-only problem:
The code is:
```
var w = window.open(urlstring, wname, wfeatures, 'false');
```
The error is:
> Message: Invalid argument.
> Line: 419
> Char: 5
> Code: 0
> URI: <http://HOSTNAME/js_context.js>
I have confirmed the line number of the code (the "Line" and "URI" are correct), and I understand in later versions of IE8, this is considered accurate.
I have checked all the incoming parameters in the call by dumping alerts, and they all look valid.
This problem does not happen on FF (probably 3).
UPDATE:
The problem appears to be in using assigning the result of window.open() when doing "var w". When I split the line into two statements it works in IE8.
UPDATE2:
Based on:
<http://javascript.crockford.com/code.html>
> When a function is to be invoked
> immediately, the entire invocation
> expression should be wrapped in parens
> so that it is clear that the value
> being produced is the result of the
> function and not the function itself.
This is not exactly what is going on here, but I found that applying the principle solved the problem, in IE8's compatability mode.
```
var w = (window.open(urlstring, wname, wfeatures, false));
``` | This is an old posting but maybe still useful for someone.
I had the same error message. In the end the problem was an invalid name for the second argument, i.e., I had a line like:
```
window.open('/somefile.html', 'a window title', 'width=300');
```
The problem was 'a window title' as it is not valid. It worked fine with the following line:
```
window.open('/somefile.html', '', 'width=300');
```
In fact, reading carefully I realized that Microsoft does not support a `name` as second argument. When you look at the [official documentation page](http://msdn.microsoft.com/en-us/library/ms536651%28v=vs.85%29.aspx), you see that Microsoft only allows the following arguments, If using that argument at all:
* \_blank
* \_media
* \_parent
* \_search
* \_self
* \_top | IE is picky about the window name argument. It doesn't like spaces, dashes, or other punctuation. | ie8 var w= window.open() - "Message: Invalid argument." | [
"",
"javascript",
"internet-explorer-8",
""
] |
I use git to interface with an SVN repository. I have several git branches for the different projects I work on.
Now, whenever I switch from one branch to another using 'git checkout ', all the compiled executables and object files from the previous branch are still there. What I would like to see is that switching from branch A to B results in a tree with all object files and binaries from the last time I worked on branch B.
Is there a way to handle this without creating multiple git repositories?
**Update:** I understand that executables and binaries should not end up in the repository. I'm a bit disappointed in the fact that all the branching stuff in git is useless to me, as it turns out I'll have to clone my proxy git repository for every branch I want to start. Something I already did for SVN and hoped to avoid with git. Of course, I don't have to do it, but it would result in me doing a new make most of the time after switching between branches (not fun). | What you want is a full context, not just the branch... which is *generally* out of scope for a version control tool. The best way to do that is to use multiple repositories.
Don't worry about the inefficiency of that though... Make your second repository a clone of the first. Git will automatically use links to avoid having multiple copies on disk.
**Here's a hack to give you want you want**
Since you have separate obj directories, you could modify your Makefiles to make the base location dynamic using something like this:
```
OBJBASE = `git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1\//'`
OBJDIR = "$(OBJBASE).obj"
# branch master: OBJBASE == "master/", OBJDIR == "master/.obj"
# non-git checkout: OBJBASE == "", OBJDIR == ".obj"
```
That will but your branch name into OBJBASE, which you can use to build your actual objdir location from. I'll leave it to you to modify it to fit your environment and make it friendly to non-git users of your Makefiles. | This is not git or svn specific - you should have your compiler and other tools direct the output of intermediate files like .o files to directories that are not under version control. | git and C++ workflow, how to handle object and archive files? | [
"",
"c++",
"git",
"workflow",
""
] |
I have a method with an `Object o` parameter.
In this method, I exactly know there is a `String` in "o" which is not null. There is no need to check, or do something else. I have to treat it exactly like a `String` object.
Just curious - what is cheaper - cast it to `String`, or use `Object.toString()`?
Or is it same by time-/cpu-/mem- price?
Update:
The method accepts `Object` because it's the implementation of an interface. There is no way to change the parameter type.
And it can't be `null` at all. I just wanted to say that I do not need to check it for null or emptyness. In my case, there is always a nonempty string. | **casting to a String is cheaper** since that doesn't require an external function call, just internal type checking. | I would use a cast. That validates your "knowledge" that it's a string. If for whatever reason you end up with a bug and someone passes in something other than a string, I think it would be better to throw an exception (which a cast will do) than continue to execute with flawed data. | (String) or .toString()? | [
"",
"java",
"casting",
""
] |
I am creating a RSS feed file for my application in which I want to remove HTML tags, which is done by `strip_tags`. But `strip_tags` is not removing HTML special code chars:
```
& ©
```
etc.
Please tell me any function which I can use to remove these special code chars from my string. | Either decode them using `html_entity_decode` or remove them using `preg_replace`:
```
$Content = preg_replace("/&#?[a-z0-9]+;/i","",$Content);
```
(From [here](http://www.webmasterworld.com/forum88/7046.htm))
EDIT: Alternative according to Jacco's comment
> might be nice to replace the '+' with
> {2,8} or something. This will limit
> the chance of replacing entire
> sentences when an unencoded '&' is
> present.
```
$Content = preg_replace("/&#?[a-z0-9]{2,8};/i","",$Content);
``` | Use [`html_entity_decode`](http://www.php.net/manual/en/function.html-entity-decode.php) to convert HTML entities.
You'll need to set charset to make it work correctly. | How to remove html special chars? | [
"",
"php",
"html-encode",
""
] |
I asked this question previously but the answers weren't what I was looking for.
I created a table in Asp.net without using code. It contains two columns.
YourUserId and FriendUserId
This is a many to many relationship.
Heres what I want:
There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:
Dave : Greg
Dave : Chris
Greg : Chris
Chris : Greg
is good
Dave : Greg
Dave : Greg
is not good.
I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.
If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.
Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?
I tried controling it with my sql insert statement but that did not work. This is what I tried.
INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])
That didn't work for some reason.
Thank you for your help! | You should create a compound primary key to prevent duplicate rows.
```
ALTER TABLE FriendRequests
ADD CONSTRAINT pk_FriendRequests PRIMARY KEY (UserID, FriendUserID)
```
Or select both columns in table designer and right click to set it as a key.
To prevent self-friendship, you'd create a `CHECK` constraint:
```
ALTER TABLE FriendRequests
ADD CONSTRAINT ck_FriendRequests_NoSelfFriends CHECK (UserID <> FriendUserID)
```
You can add the check constraint in the designer by right clicking anywhere in the table designer, clicking "Check constraints", clicking "add", and setting expression to `UserID <> FriendUserID`
You might want to look at [this question](https://stackoverflow.com/questions/669483/modeling-friends-and-followers-in-an-rdbms) | Sounds like you need a composite key to make both fields a single key. | Unique record in Asp.Net SQL | [
"",
"asp.net",
"sql",
"unique",
"record",
""
] |
Here are some typical answers(ranked in ascending order of corniness) I get from managers/bosses whenever I bring up the importance of having unit tests and code coverage as an integral part of the development cycle
1. "That is the job of QA, just focus on features and development"
2. "The application is not mission critical, if there are some bugs it's not the end of the world"
3. "We can't afford to spend time on unit testing"
4. "Try not to get too fancy"
In spite of having the best intentions of doing a good job, at the end of the day when time comes for the blame game, the burden finally falls on the developer.
It's all too often that I've seen that things break in production, some of which which could have been avoided by catching these bugs statically by running unit tests.
I just wanted to get a conversation going to see what peoples experiences have been and what is the best way to tackle this.
UPDATE: Thanks everyone for a lot of insightful advice. There are several answers that I wish I could select as the right answer. | Introducing unit tests into development process is like investment: you have to put some money up front to get profit later. Management should be more attentive to this analogy if you follow through with it: describe what investments are required and then lay down plan for profits.
For example:
Investments:
* time spend to implement test
infrastructure (no serious product
unit tests can be possible without
test-specific infrastructure code
that streamlines product specific
test patterns, test data
creation/removal, etc.);
* time spend on writing actual tests;
* time spend on reviewing and
supporting tests;
* etc.
Profits:
* no bug ever re-appears without a sign;
* no major features are released without unit tests passing;
* cycle development-qa-fix bugs is cut in half for majority of bugs: development-unit test-fix bugs;
* etc. | Most managers won't see the advantages of unit testing until they see it in action where it makes sense, so my advice, based on experience, is to take the ff steps:
1. **Apply unit tests to recurring bugs** - This is the best use case to prove the value of unit tests. When you have bugs that just appear and reappear every other build, the unit test will allow developers to see which changes caused the bugs, aside from alerting them in advance that a fix is in order. It's quite easy to demonstrate to management as well.
2. **Apply unit tests to regular bugs** - With the usefulness of unit tests now clearly demonstrated, several instances of recurring bugs disappearing in the long term should be enough to encourage everyone to use unit tests to evaluate *all* bugs, to prevent them from becoming recurring bugs.
3. **Apply unit tests to new functionality** - With unit tests making sure that old bugs don't reccur, and confirm that they are fixed in the first place, the next step would be to apply it to new functionality to ensure that bugs will be minimized. Make it clear that it is impossible to totally eliminate bugs.
4. **Apply full blown TDD** - The final step will be to apply unit testing even before coding, as a design tool that both helps in designing code and minimizing bugs.
Of course I'm not saying that this is easy -- what I had stated above is an oversimplification which even I struggle with everyday -- it's difficult to convince everyone.
If later you decide to move on to a different company, you may want to explicitly look for a company that practices TDD. | The Value of Unit Testing | [
"",
"c#",
".net",
"unit-testing",
""
] |
I don't want to tell the hard way that the internet is unavailable when I catch an exception from url.openStream().
Is there a simple way to tell if the computer is connected to the internet in Java?
In this scenario, "connected to the internet" means being able to download data from a specific url.
If I try to download from it and it is not available, then the program hangs for a bit. I dont want that hanging. Therefore, i need a fast way of querying whether the website is available or not. | The problem you are trying to avoid is waiting for for your http connection to determine that the URL you are trying to access is really unavailable. In order to achieve this you need to stop using url.openStream() which is a shortcut for openConnection().getInputStream() and get some finer control over your connection.
```
URLConnection conn = url.openConnection();
conn.setConnectTimeout(timeoutMs);
conn.setReadTimeout(timeoutMs);
in = conn.getInputStream();
```
This code will allow you to timeout the connection attempt if either the connection or the read exceeds the time you provide in the timeoutMs paramater. | Use
```
Process p1 = java.lang.Runtime.getRuntime().exec("ping www.google.com");
System.out.println(p1.waitFor());
// return code for p1 will be 0 if internet is connected, else it will be 1
``` | How do I test the availability of the internet in Java? | [
"",
"java",
""
] |
I'm using [CakePHP](http://en.wikipedia.org/wiki/CakePHP) 1.2 with Auth and ACL components.
In my user register action, the password is coming in unhashed. Specifically, this expression:
```
if ($this->data['User']['password'] !=
$this->Auth->password($this->data['User']['confirm_password']))
```
This is evaluating to true, even when I submit identical values for `password` and `confirm_password`. I know that password is unhashed because when I remove the call to `Auth->password`, the expression evaluates to false.
I expected the Auth module to automagically hash the password. What am I doing wrong?
Here is my view:
```
<?php
echo $form->create('User', array('action' => 'register'));
echo $form->input('email',
array('after' => $form->error(
'email_unique', 'This email is already registered.')));
echo $form->input('password');
echo $form->input('confirm_password', array('type' => 'password'));
echo $form->end('Register');
?>
```
Here is my register action from the user controller:
```
function register(){
if ($this->data) {
if ($this->data['User']['password'] !=
$this->Auth->password($this->data['User']['confirm_password'])) {
$this->Session->setFlash(__('Password and Confirm Password must match.', true));
$this->data['User']['password'] = '';
$this->data['User']['confirm_password'] = '';
}
else{
$this->User->create();
if ($this->User->save($this->data)){
$this->redirect(array('action' => 'index'), null, true);
}
else {
$this->data['User']['password'] = '';
$this->data['User']['confirm_password'] = '';
$this->Session->setFlash(__('Some problem saving your information.', true));
}
}
}
}
```
And here is my `appController` where I include the `Auth` and `Acl` modules:
```
class AppController extends Controller {
var $components = array('Acl', 'Auth');
function beforeFilter(){
if (isset($this->Auth)) {
$this->Auth->allow('display');
$this->Auth->fields =
array(
'username' => 'email',
'password' => 'password');
$this->Auth->authorize = 'actions';
}
}
}
```
What am I doing wrong? | CakePHP won't hash passwords unless username contains a submitted value. I'm replacing the username field with email. However, I remapped those fields by setting the Auth->fields array. However, I was doing that in the appController instead of userController. So moving this line:
```
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
```
out of appController into userController solved it.
Now the question becomes "Why can't I reset the Auth->fields in appController?" | You're probably overriding `AppController::beforeFilter()` with your `UsersController::beforeFilter()`.
To "fix" it, just put `parent::beforeFilter()` at the beginning of the function. | Why is the CakePHP authentication component not hashing my password? | [
"",
"php",
"authentication",
"cakephp",
"cakephp-1.2",
""
] |
Should static field initialization be completed before constructor is called?
The following program provides output that seems incorrect to me.
```
new A()
_A == null
static A()
new A()
_A == A
```
The code:
```
public class A
{
public static string _A = (new A()).I();
public A()
{
Console.WriteLine("new A()");
if (_A == null)
Console.WriteLine("_A == null");
else
Console.WriteLine("_A == " + _A);
}
static A()
{
Console.WriteLine("static A()");
}
public string I()
{
return "A";
}
}
class Program
{
static void Main(string[] args)
{
var a = new A();
}
}
``` | This is correct.
Your static initializers, then the static constructor is run before your standard constructor, but when it runs, it's using new A(), so passing through your non-static constructor path. This causes the messages you see.
Here is the full path of execution:
When you first call `var a = new A();` in your program, this is the first time A is accessed.
This will fire off the static initialization of `A._A`
At this point, A.\_A constructs with `_A = (new A()).I();`
This hits
```
Console.WriteLine("new A()");
if (_A == null)
Console.WriteLine("_A == null");
```
since at this point, \_A hasn't been set with the returned, constructed type (yet).
Next, the static constructor `A { static A(); }` is run. This prints the "static A()" message.
Finally, your original statement (`var a = new A();`) is executed, but at this point, the statics are constructed, so you get the final print. | One extra side note - the C# specification (I'm looking at 4.0, but it's there in 3.0 too) says in 10.5.5.1 Static Field Initialization:
> If a static constructor (§10.12)
> exists in the class, execution of the
> static field initializers occurs
> immediately prior to executing that
> static constructor. Otherwise, the
> static field initializers are executed
> at an implementation-dependent time
> prior to the first use of a static
> field of that class.
You have a static constructor, so the "Otherwise" clause does not apply. But I think it's relevant information to your question to know that if you don't have a static constructor, the static field initializers can be executed 'at an implementation-dependent time'. This could matter if your static field initializer is doing some type of data initialization or object creation which you rely on without accessing the static field itself.
It is esoteric, I guess, but I saw it happen today as the 'implementation-dependent time' appears to have changed between C# 3.0 and 4.0 - at least for the situation I was looking at. The easy solution of course is simple - just add a static constructor... | How does static field initialization work in C#? | [
"",
"c#",
"compiler-construction",
""
] |
I've been given an existing PHP application that was originally deployed on a LAMP host.
Because most of our team are .Net developers, our boss wants it deployed in a windows environment.
Is it madness to expect this to just work?
Here's some additional info of the LAMP host:
* Linux 2.4.32
* PHP 5.2.6
* No non-default modules | In my experience, it can be done and works fine.
The most important things I'd keep in mind are:
1. Use Apache on Windows, don't use IIS (even if it's possible)
2. Make sure you use unix style slashes for directories. Those work on both platforms.
3. Be very careful with case sensitivity. Since Windows is not case sensitive (though it is case preserving), if you include a file and spell it with the wrong case, it will work on Windows and fail on Linux. | Heck even just migrating from one hosted server to a different one usually requires SOME tweaking and adjustments. I don't imagine having to do it in a Windows environment would be much different. I was invloved in the migration of a large PHP app just last week and we (3 people) were able to get things going in about half a day. | Cross platform PHP caveats? | [
"",
"php",
"cross-platform",
""
] |
say I have a class:
```
class A
{
public:
A() {}
};
```
and a function:
```
void x(const A & s) {}
```
and I do:
```
x(A());
```
could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?
Thanks! | There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error. | Herb Sutter does a fine job explaining it here: <http://www.gotw.ca/gotw/081.htm> | rules with temporary objects and args by reference | [
"",
"c++",
"reference",
"object",
"temporary",
""
] |
I would like to upload files just like google mail does. I would want to use jQuery and PHP to do it is there anyway of getting the progressbar etc.?
Here I added a video of how google does it. <http://dl.getdropbox.com/u/5910/Jing/2009-04-02_1948.swf>
No flash, no perl or cgi please..
I guess I can live without the progressbar now I am actually searching for information about jquery plugins or just what things I would need to look at | It is weird that people say that gmail doesn't use flash, when you can plainly see the swf file in the gmail interface. Try right clicking on "Attach a file". It is what allows the multiple uploads at once among other things. | The easiest would be to use [SWFUpload](http://swfupload.org/), it's a small button written in Flash, with all the hooks to drive it in JS. Very easy to use and works well with PHP
but, if you really want it to be pure JS, you'll need some help from the server. specifically, you'll need to start the upload, and periodically query the server about how's it going. unfortunately, PHP upload handling doesn't get any notification until after the download finishes. you'd have to replace it with something else. there are a few pure JS uploaders that include sample Perl server code just because of that.
IOW: JS and PHP don't (fully) cut it. either add flash to the client, or a better upload handler at the server. | Gmail like file upload with jQuery | [
"",
"php",
"ajax",
"jquery",
""
] |
I keep getting a Base64 invalid character error even though I shouldn't.
The program takes an XML file and exports it to a document. If the user wants, it will compress the file as well. The compression works fine and returns a Base64 String which is encoded into UTF-8 and written to a file.
When its time to reload the document into the program I have to check whether its compressed or not, the code is simply:
```
byte[] gzBuffer = System.Convert.FromBase64String(text);
return "1F-8B-08" == BitConverter.ToString(new List<Byte>(gzBuffer).GetRange(4, 3).ToArray());
```
It checks the beginning of the string to see if it has GZips code in it.
Now the thing is, all my tests work. I take a string, compress it, decompress it, and compare it to the original. The problem is when I get the string returned from an ADO Recordset. The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything, even trimmed off it still throws). I even copy and pasted the entire string into a test method and compress/decompress that. Works fine.
The tests will pass but the code will fail using the exact same string? The only difference is instead of just declaring a regular string and passing it in I'm getting one returned from a recordset.
Any ideas on what am I doing wrong? | You say
> The string is exactly what was written
> to the file (with the addition of a
> "\0" at the end, but I don't think
> that even does anything).
In fact, it does do something (it causes your code to throw a `FormatException`:"Invalid character in a Base-64 string") because the [`Convert.FromBase64String`](http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx) does not consider "\0" to be a valid Base64 character.
```
byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
byte[] data2 = Convert.FromBase64String("AAAA"); // Works
```
**Solution: Get rid of the zero termination.** (Maybe call `.Trim("\0")`)
**Notes**:
The [MSDN docs for `Convert.FromBase64String`](http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx) say it will throw a `FormatException` when
> The length of s, ignoring white space
> characters, is not zero or a multiple
> of 4.
>
> -or-
>
> The format of s is invalid. s contains a non-base 64 character, more
> than two padding characters, or a
> non-white space character among the
> padding characters.
and that
> The base 64 digits in ascending order
> from zero are the uppercase characters
> 'A' to 'Z', lowercase characters 'a'
> to 'z', numerals '0' to '9', and the
> symbols '+' and '/'. | Whether null char is allowed or not really depends on base64 codec in question.
Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/
But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.
One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings. | Base64 String throwing invalid character error | [
"",
"c#",
"string",
"ado.net",
"base64",
"invalid-characters",
""
] |
I have a class with an indexer property, with a string key:
```
public class IndexerProvider {
public object this[string key] {
get
{
return ...
}
set
{
...
}
}
...
}
```
I bind to an instance of this class in WPF, using indexer notation:
```
<TextBox Text="{Binding [IndexerKeyThingy]}">
```
That works fine, but I want to raise a `PropertyChanged` event when one of the indexer values changes. I tried raising it with a property name of "[keyname]" (i.e. including [] around the name of the key), but that doesn't seem to work. I don't get binding errors in my output window whatsoever.
I can't use CollectionChangedEvent, because the index is not integer based. And technically, the object isn't a collection anyway.
Can I do this, and so, how? | According to [this blog entry](https://web.archive.org/web/20100127102448/http://blogs.msdn.com/xtof/archive/2007/09/28/binding-to-indexers.aspx), you have to use `"Item[]"`. Item being the name of the property generated by the compiler when using an indexer.
If you want to be explicit, you can decorate the indexer property with an [IndexerName](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.indexernameattribute.aspx) attribute.
That would make the code look like:
```
public class IndexerProvider : INotifyPropertyChanged {
[IndexerName ("Item")]
public object this [string key] {
get {
return ...;
}
set {
... = value;
FirePropertyChanged ("Item[]");
}
}
}
```
At least it makes the intent more clear. I don't suggest you change the indexer name though, if your buddy found the string `"Item[]"` hard coded, it probably means that WPF would not be able to deal with a different indexer name. | Additionaly, you can use
```
FirePropertyChanged ("Item[IndexerKeyThingy]");
```
To notify only controls bound to IndexerKeyThingy on your indexer. | PropertyChanged for indexer property | [
"",
"c#",
"wpf",
"data-binding",
"indexer",
""
] |
I am still learning C++, and I have never really created my own namespaces before. I was experimenting with them and while I got most things to work, there's one thing that I still can't seem to do. I would like to be able to call a static method within a class without typing something like `NameOfClass::method`. Here is what I thought the code should look like, but it fails to compile:
File `A.h`,
```
namespace Test
{
class A
{
public:
static int foo() { return 42; }
};
}
```
File `main.cpp`,
```
#include <iostream>
#include "A.h"
using namespace std;
using namespace Test::A;
int main()
{
cout << foo() << endl;
return 0;
}
```
The compiler gives me:
```
main.cpp:6: error: ‘A’ is not a namespace-name
main.cpp:6: error: expected namespace-name before ‘;’ token
main.cpp: In function ‘int main()’:
main.cpp:10: error: ‘foo’ was not declared in this scope
```
Is it possible to do what I am trying to do without typing `A::foo`? | There is no way around it you need to specify the class name for static methods.
```
using namespace Test;
```
Then:
```
int answerToEverything = A::foo();
``` | In C++, you /especially/ have to read the compiler error messages carefully.
Notice the first error was "error: ‘A’ is not a namespace-name". That's true, A is a classname.
```
using namespace Foo; // brings in all of foo;
using Bar::Baz // brings in only Baz from Bar
```
You want to write:
```
using Test::A;
```
That does two good things: it brings in A for you to use, and it doesn't bring in all the rest of Test, which is good too, because you should only bring in what you need, so as to not accidentally depend on something you don't realize you're depending upon.
However, as foo is static in A, you'll still have to refer to A::foo explicitly. (Unless you do something like writing a free function that forwards to A::foo; in general, this is a bad idea if you're only doing it to save some typing.)
Some may advise not using using declarations at all, instead fully qualifying all names.
But this is (to quote Stroustrup) "tedious and error prone", and it gets in the way of refactoring: say that you fully qualify every use of class FooMatic::Stack, and then management insists, just before you're about to go to production, that you use BarMatic's very similar Stack class, because barMatic just bought out your company.
Had you fully qualified everywhere, you'd be doing a lot of grepping, hoping your regex was right. If you used a using declaration, you can just make a fix to your (hopefully shared) header file. In this way, a using declaration is a lot like a "typedef int ourInt;" or a manifest constant or const: "const int FOO = 1;", in that it provides one place to change something that's referred to many places. Fully qualifying a namespace at every use takes away that benefit.
Conversely, had you used a using directive and brought in all of Namespace FooMatic, your grep might have been even harder, if say management insisted on BarMatic::Foo but you still had to use FooMatic:Baz, the BarMatic equivalent for Baz being for whatever reason unusable.
So bringing in one type (class, function, constant) at a time is generally the most flexible, the way to best protect yourself against inevitable but as yet unknown changes. As in most coding, you want to minimize tedious repetition while keeping sufficient granularity. | C++ using namespaces to avoid long paths | [
"",
"c++",
"namespaces",
"using",
""
] |
I am creating a subclass of Button and would like to add custom functionality to some of its events such as OnClick. Which is the more desirable way to do it? Do I override OnClick:
```
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
doStuff();
}
```
or should I instead link up the OnClick event to an event handler defined in my Button subclass through the designer?
```
class ButtonSubclass
{
public ButtonSubclass() : base()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.Click += new System.EventHandler(this.ButtonSubclass_Click);
}
}
```
**Edit**: I added minor visual changes (that may pass as rudimentary skinning) but most of the changes are in event handlers that I don't want to re-implement (copy-paste) on every form that reuses it. | If you're genuinely specializing the button, it makes sense to override `OnClick`. If you're only *actually* changing what happens when a button is clicked, I wouldn't subclass `Button` in the first place - I'd *just* add event handlers.
EDIT: Just to give a bit more of an idea - if you want to add similar event handlers for multiple buttons, it's easy enough to write a utility method to do that, and call it from multiple places. It doesn't require actual subclassing. That's not to say subclass *is* definitely wrong in your case, of course - just giving you extra options :) | Always override OnClick when inheriting. It gives you better performance. | Using event handlers vs overriding event-firing methods | [
"",
"c#",
".net",
"winforms",
""
] |
Our application often connects to a different kind of back-ends over web services, MQ, JDBC, proprietary (direct over socket) and other kinds of transport. We already have a number of implementations that let us connect from our application to these back-ends and while all of these implementations implement the common java interface, they do not share anything else.
We have realized that there are signification portions of code that are common for all of these particular connector implementations and we have decided to streamline the development of future connectors through one universal connector. This connector will be capable of formatting messages to a format expected by back-end and sending them using the available transport mechanism. For example, fixed-length message format over MQ or over a socket.
One of the dilemmas we are facing is the most appropriate technology for this kind of connector. So far, our connectors were basic java classes that implement the common java interface. Since we generally host our applications in some Java EE application server, it seems that Java Connector Architecture would be the most appropriate technology for this piece of software. However, implementing JCA compliant connector seems to be relatively complex. What are the palpable benefits of going with the standard – JCA and do benefits justify the additional effort? | Indeed JCA **seems** the most appropriate technology for you. Already excellent arguments have been made, namely the portability, standardised interface, the connection pooling and transaction support. And don't forget security.
With WebSphere Process server the adapters could be exposed as a SCA service which can have a lot of benefits if that's important for you.
Also some development tools have extensive support for developing and testing JCA connectors.
Another benefit is (experienced) Java EE Administrators and Java EE developers (should) know the standard so administration and development should be easy to streamline.
But in the end you should have to find reasons to implement JCA based on the scope of your project, the future plans you have for your project or maybe within the policy of your company. | Short answer: I see no benefit on selecting JCA over other technologies, I see it as a drawback since you need Java EE container.
Long answer:
I've been skeptic about these Java EE standards for some time now. I don't see a compelling *technical* reason to use a full featured Java EE server anymore, since there are better open source implementations for *every* feature offered. I've been bitten several times by implementation incompatibilities when moving to/from "enterprisey solutions".
The idea for JCA is surfacing here right now and I am pushing to try [apache camel](http://camel.apache.org) or [spring integration](http://www.springsource.org/spring-integration) instead. I am all for open source implementations that you can use everywhere. And there is a lot going on. Check [this list of components](http://camel.apache.org/components.html). Granted, maybe is smaller than whats already developed with JCA, but every bit is open sourced and it's all on one location. Also, I believe the documentation is simpler and more complete. The urge for integration calls for a powerful SPI with plenty of open source, real live examples, developed in the same fashion, and that can be found on the same place.
I am hating the negativity, but I don't like full featured application servers. For instance, I would go for tomcat and terracota *any day* over other "enterprisey" products, just as I would go with camel before JCA, until the need for JCA gets proven. I don't like the idea of the Java Committee to tell how I should develop my own applications because I don't trust them. I believe it is in my best interest when the piece of software can work just as easily on Java SE/RCP as in a Java EE environments or in a pure Servlet container. | What are the benefits of JCA? | [
"",
"java",
"jakarta-ee",
"backend",
"connector",
"jca",
""
] |
Given that there is a global javascript variable on my web page named myVar, how can I access the value of the variable myVar from within my flash movie using javascript?
I see plenty of examples of using external interface in order to execute javascript from actionscript, but I am unable to find examples of returning values back into the flash movie using actionscript.
Thanks in advance. I hope my question is clear enough. | ExternalInterface works by allowing JavaScript to invoke an ActionScript function in the movie, and vice-versa. You can optionally receive a return value back from the invoked function. Here's a very simple example:
JavaScript:
```
<script language="JavaScript">
function getMyVar()
{
return myVar;
}
</script>
```
Flash/AS:
```
import flash.external.ExternalInterface;
var result:string = ExternalInterface.call("getMyVar");
``` | You can also provide an anonymous function that returns your global variable value to the `ExternalInterface.call` method as follow:
```
ExternalInterface.call("function(){ return myGlobalVariable; }");
``` | how to read a global javascript variable from actionscript | [
"",
"javascript",
"actionscript",
"externalinterface",
""
] |
I am writing an installer for my web app and I struggle with the uninstaller part. Despite the fact that I created a custom action on Uninstall in my Application Setup Project, the InstallerClass is set to true, the method:
```
public override void Uninstall(IDictionary savedState)
{
//MessageBox.Show("Attach debugger!", "Viper.Setup");
Cleanup();
base.Uninstall(savedState);
}
```
on the installer class doesn't seem to be called. Any ideas what could be the reason?
EDIT: I also noticed that it not only doesn't run the Installer, but also doesn't delete my main dll file. To make it worse, when I install a new version after uninstalling the previous one, this dll is still the old one (even though installation and uninstallation were successful) | I stopped using these rubbish msi's and created a zip + cmd script instead. Strongly recommended, took me 10 times less to set up and actually works. | Did you include the output of your installer code in the Code Actions tab of the installer?
If that's not it...
I ran into a similar problem in the past and found I needed all 4 methods defined or the uninstall would not run. Add your code to the template below:
```
[RunInstaller(true)]
public class MyInstaller: Installer
{
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
}
}
```
Hope this helps! | Why is my Uninstall method not called from the msi? | [
"",
"c#",
".net",
"installation",
"windows-installer",
""
] |
I am trying to get a better understanding of the [jQuery.map](http://docs.jquery.com/Utilities/jQuery.map) function.
So in general terms .map takes a array and "maps" it to another array of items.
easy example:
```
$.map([0,1,2], function(n){
return n+4;
});
```
results in [4,5,6]
I think I understand what it does. I want to under why would someone need it. What is the practical use of this function? How are you using this in your code? | `$.map` is all about converting items in a set.
As far as the DOM, I often use it to quickly pluck out values from my elements:
```
var usernames = $('#user-list li label').map(function() {
return this.innerHTML;
})
```
The above converts the `<label>` elements inside a list of users to just the text contained therein. Then I can do:
```
alert('The following users are still logged in: ' + usernames.join(', '));
``` | Mapping has two main purposes: grabbing properties from an array of items, and converting each item into something else.
Suppose you have an array of objects representing users:
```
var users = [
{ id: 1, name: "RedWolves" },
{ id: 2, name: "Ron DeVera" },
{ id: 3, name: "Jon Skeet" }
];
```
Mapping is a convenient way to grab a certain property from each item. For instance, you can convert it into an array of user IDs:
```
var userIds = $.map(users, function(u) { return u.id; });
```
As another example, say you have a collection of elements:
```
var ths = $('table tr th');
```
If you want to store the contents of those table headers for later use, you can get an array of their HTML contents:
```
var contents = $.map(ths, function(th) { return th.html(); });
``` | jQuery.map - Practical uses for the function? | [
"",
"javascript",
"jquery",
""
] |
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().
Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:
```
for line in lines:
result = re.match ('/href="(.*)"/iU', line)
print result
```
This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.
Can someone give me a hint on this?
Thanks in advance | Well, just for completeness I will add here what I found to be the best answer, and I found it on the book Dive Into Python, from Mark Pilgrim.
Here follows the code to list all URL's from a webpage:
```
from sgmllib import SGMLParser
class URLLister(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.urls = []
def start_a(self, attrs):
href = [v for k, v in attrs if k=='href']
if href:
self.urls.extend(href)
import urllib, urllister
usock = urllib.urlopen("http://diveintopython.net/")
parser = urllister.URLLister()
parser.feed(usock.read())
usock.close()
parser.close()
for url in parser.urls: print url
```
Thanks for all the replies. | [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) can do this almost trivially:
```
from BeautifulSoup import BeautifulSoup as soup
html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>')
print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})]
``` | Getting the value of href attributes in all <a> tags on a html file with Python | [
"",
"python",
"html",
"regex",
"parsing",
""
] |
I am looking to build a PC box that can play up to 16 audio files(mp3/wav) out to 16 analog devices(think of it as 16 sets of speakers). There will be a one to one relationship for audio file to analog output. The solution that is being presented to be hardware wise is to use multiple sound cards, so my question is, is there a library available that will let me play an audio file to a specific sound card / channel? | Yes, the BASS library can do this.
<http://www.un4seen.com>
C# wrappers are also available, a commercial one:
[Bass.NET](http://bass.radio42.com/)
and an excellent alternative open source C# wrapper for Bass:
[ManagedBass](https://github.com/ManagedBass) by [Mathew Sachin](https://stackoverflow.com/users/5377194/mathew-sachin) | I found this one while I was looking as well.
<http://www.alvas.net/alvas.audio.aspx> | Multiple audio outputs in .Net | [
"",
"c#",
".net",
"audio",
""
] |
I have a byte array generated by a random number generator. I want to put this into the STL bitset.
Unfortunately, it looks like Bitset only supports the following constructors:
1. A string of 1's and 0's like "10101011"
2. An unsigned long. (my byte array will be longer)
The only solution I can think of now is to read the byte array bit by bit and make a string of 1's and 0's. Does anyone have a more efficient solution? | Something like this?
```
#include <bitset>
#include <climits>
template<size_t numBytes>
std::bitset<numBytes * CHAR_BIT> bytesToBitset(uint8_t *data)
{
std::bitset<numBytes * CHAR_BIT> b;
for(int i = 0; i < numBytes; ++i)
{
uint8_t cur = data[i];
int offset = i * CHAR_BIT;
for(int bit = 0; bit < CHAR_BIT; ++bit)
{
b[offset] = cur & 1;
++offset; // Move to next bit in b
cur >>= 1; // Move to next bit in array
}
}
return b;
}
```
And an example usage:
```
int main()
{
std::array<uint8_t, 4> bytes = { 0xDE, 0xAD, 0xBE, 0xEF };
auto bits = bytesToBitset<bytes.size()>(bytes.data());
std::cout << bits << std::endl;
}
``` | There's a 3rd constructor for `bitset<>` - it takes no parameters and sets all the bits to 0. I think you'll need to use that then walk through the array calling `set()` for each bit in the byte array that's a 1.
A bit brute-force, but it'll work. There will be a bit of complexity to convert the byte-index and bit offset within each byte to a bitset index, but it's nothing a little bit of thought (and maybe a run through under the debugger) won't solve. I think it's most likely simpler and more efficient than trying to run the array through a string conversion or a stream. | Convert Byte Array into Bitset | [
"",
"c++",
"byte",
"bitset",
""
] |
I want to make a text box in .NET "glow" yellow, and then "fade" to white (basically, by incrementally increasing the brightness). I think Stackoverflow does this after you've posted an answer. I know that increasing brightness is not all that simple (it's not just uniformly increasing/decreasing RGB), but I'm not sure how to do this.
Perfect color accuracy is not important for this. I am using C#, although VB examples would be just fine, too.
**Edit:** This is for Winforms. | This may be more than you need, here's the code for the class I use:
```
public class ControlColorAnimator
{
private const int INTERVAL = 100;
private readonly decimal _alphaIncrement;
private readonly decimal _blueIncrement;
private readonly Color _endColor;
private readonly decimal _greenIncrement;
private readonly int _iterations;
private readonly decimal _redIncrement;
private readonly Color _startColor;
private decimal _currentAlpha;
private decimal _currentBlueValue;
private decimal _currentGreenValue;
private decimal _currentRedValue;
private Timer _timer;
public ControlColorAnimator(TimeSpan duration, Color startColor, Color endColor)
{
_startColor = startColor;
_endColor = endColor;
resetColor();
_iterations = duration.Milliseconds / INTERVAL;
_alphaIncrement = ((decimal) startColor.A - endColor.A) / _iterations;
_redIncrement = ((decimal) startColor.R - endColor.R) / _iterations;
_greenIncrement = ((decimal) startColor.G - endColor.G) / _iterations;
_blueIncrement = ((decimal) startColor.B - endColor.B) / _iterations;
}
public Color CurrentColor
{
get
{
int alpha = Convert.ToInt32(_currentAlpha);
int red = Convert.ToInt32(_currentRedValue);
int green = Convert.ToInt32(_currentGreenValue);
int blue = Convert.ToInt32(_currentBlueValue);
return Color.FromArgb(alpha, red, green, blue);
}
}
public event EventHandler<DataEventArgs<Color>> ColorChanged;
public void Go()
{
disposeOfTheTimer();
OnColorChanged(_startColor);
resetColor();
int currentIteration = 0;
_timer = new Timer(delegate
{
if (currentIteration++ >= _iterations)
{
Stop();
return;
}
_currentAlpha -= _alphaIncrement;
_currentRedValue -= _redIncrement;
_currentGreenValue -= _greenIncrement;
_currentBlueValue -= _blueIncrement;
OnColorChanged(CurrentColor);
}, null, TimeSpan.FromMilliseconds(INTERVAL), TimeSpan.FromMilliseconds(INTERVAL));
}
public void Stop()
{
disposeOfTheTimer();
OnColorChanged(_endColor);
}
protected virtual void OnColorChanged(Color color)
{
if (ColorChanged == null) return;
ColorChanged(this, color);
}
private void disposeOfTheTimer()
{
Timer timer = _timer;
_timer = null;
if (timer != null) timer.Dispose();
}
private void resetColor()
{
_currentAlpha = _startColor.A;
_currentRedValue = _startColor.R;
_currentGreenValue = _startColor.G;
_currentBlueValue = _startColor.B;
}
}
```
This uses `DataEventArgs<T>` (shown below)
```
/// <summary>
/// Generic implementation of <see cref="EventArgs"/> that allows for a data element to be passed.
/// </summary>
/// <typeparam name="T">The type of data to contain.</typeparam>
[DebuggerDisplay("{Data}")]
public class DataEventArgs<T> : EventArgs
{
private T _data;
/// <summary>
/// Constructs a <see cref="DataEventArgs{T}"/>.
/// </summary>
/// <param name="data">The data to contain in the <see cref="DataEventArgs{T}"/></param>
[DebuggerHidden]
public DataEventArgs(T data)
{
_data = data;
}
/// <summary>
/// Gets the data for this <see cref="DataEventArgs{T}"/>.
/// </summary>
public virtual T Data
{
[DebuggerHidden]
get { return _data; }
[DebuggerHidden]
protected set { _data = value; }
}
[DebuggerHidden]
public static implicit operator DataEventArgs<T>(T data)
{
return new DataEventArgs<T>(data);
}
[DebuggerHidden]
public static implicit operator T(DataEventArgs<T> e)
{
return e.Data;
}
}
```
Use in your form like this:
```
private ControlColorAnimator _animator;
private void runColorLoop()
{
endCurrentAnimation();
startNewAnimation();
}
private void endCurrentAnimation()
{
ControlColorAnimator animator = _animator;
_animator = null;
if (animator != null)
{
animator.ColorChanged -= _animator_ColorChanged;
animator.Stop();
}
}
private void startNewAnimation()
{
_animator = new ControlColorAnimator(TimeSpan.FromSeconds(.6), Color.Yellow, BackColor);
_animator.ColorChanged += _animator_ColorChanged;
_animator.Go();
}
private void _animator_ColorChanged(object sender, DataEventArgs<Color> e)
{
invokeOnFormThread(delegate { setColor(e); });
}
private void setColor(Color color)
{
// code to set color of the controls goes here
}
private void invokeOnFormThread(MethodInvoker method)
{
if (IsHandleCreated)
Invoke(method);
else
method();
}
``` | Just interpolate between the colors based on the time.
If your orange color is (r1,g1,b1) and you wish to fade to a different color (r2,g2,b2), the formula for linear interpolation is (r1 + (r2-r1) \* t, g1 + (g2-g1) \* t, b1 + (b2-b1) \* t), where t is in the range of [0.0 1.0].
In your example, your first color is probably something like (255,200,0) and your second color would be (255,255,255).
If you wish for smoother transitions, look up different ways of interpolation. | Fade a color to white (increasing brightness) | [
"",
"c#",
".net",
"winforms",
"colors",
"interpolation",
""
] |
I have an interesting question about the way PHP evaluates boolean expressions. When you have, for example,
```
$expression = $expression1 and $expression2;
```
or
```
if ($expression1 and $expression2)
```
PHP first checks if `$expression1` evaluates to **`true`**. If this is not the case, then `$expression2` is simply skipped to avoid unnecessary calculations. In a script I am writing, I have:
```
if ($validator->valid("title") and $validator->valid("text"))
```
I need to have the second statement (`$validator->valid("text")`) evaluated even if the first one evaluates to false. I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you! | This is known as [short circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation), and to avoid it you need to do this, using a single `&`:
```
if($validator->valid("title") & $validator->valid("text")) {
}
```
Note that this is not using [logical operators](http://www.php.net/language.operators.logical) but actually [bitwise operators](http://www.php.net/manual/en/language.operators.bitwise.php):
> They're operators that act on the binary representations of numbers. They do not take logical values (i.e., "true" or "false") as arguments without first converting them to the numbers 1 and 0 respectively. Nor do they return logical values, but numbers. Sure, you can later treat those numbers as though they were logical values (in which case 0 is cast to "false" and anything else is cast to "true"), but that's a consequence of PHP's type casting rules, and nothing to do with the behavior of the operators.
As such, there is *some* debate as to whether it is good practice to use this side effect to circumvent short-circuit evaluation. I would personally at least put a comment that the & is intentional, but if you want to be as pure as possible you should evaluate whether they are valid first and then do the if. | ```
$isValidTitle = $validator->valid("title");
$isValidText = $validator->valid("text");
if($isValidTitle && $isValidText)
{
...
}
```
Will that suit? | How can I have PHP avoid lazy evaluation? | [
"",
"php",
"function",
"lazy-evaluation",
"boolean-logic",
""
] |
I want a thread to execute in the background every 500 milliseconds. To do that, I extended a Thread, implemented ActionListener and put the class that I extended into a Timer. The Timer calls run() every 500 milliseconds. However, my whole Swing GUI freezes up when this thread is downloading stuff from the Internet. I want it to run in the background, without freezing up the GUI while it waits for IO to finish. I also the downloader to finish downloading before we wait 500 milliseconds.
gogogo() is called to initialize the whole process:
```
public final class Downloader extends Thread implements ActionListener
{
public static void gogogo()
{
t= new Downloader();
new Timer(500, (ActionListener) t).start();
}
public void run()
{
doStuff(); //the code that i want repeatedly called
}
public void actionPerformed(ActionEvent e)
{
run();
}
}
``` | Just start the thread once, make it loop, and do `Thread.sleep(500L)` with each iteration. That probably makes more sense that starting a brand new thread every 500ms. No reason to incur the associated cost if you can avoid it. | Instead of using the swing timer try using the java util timer or the ScheduledExecutorService. the swing timers share a pre-existing timer thread and that may be causing the freezing.
A recommendation from the java tutorial:
> In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, pre-existing timer thread and the GUI-related task automatically executes on the event-dispatch thread. However, you might use a general-purpose timer if you don't plan on touching the GUI from the timer, or need to perform lengthy processing | How do you repeatedly call a Thread in Java? | [
"",
"java",
"multithreading",
""
] |
I'm pretty sure the answer is no, but thought I'd ask anyway.
If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:
```
var scriptName = ???
if (typeof jQuery !== "function") {
throw new Error(
"jQuery's script needs to be loaded before " +
scriptName + ". Check the <script> tag order.");
}
```
Probably more trouble than it's worth for dependency checking, but what the hell. | ```
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);
```
Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6
---
### See also: [How may I reference the script tag that loaded the currently-executing script?](https://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script) | I'm aware this is old but I have developed a better solution because all of the above didn't work for Async scripts. With some tweaking the following script can cover almost all use cases. Heres what worked for me:
```
function getScriptName() {
var error = new Error()
, source
, lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/)
, currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/);
if((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] != "")
return source[1];
else if((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1];
else if(error.fileName != undefined)
return error.fileName;
}
```
Not sure about support on Internet Explorer, but works fine in every other browser I tested on. | How might I get the script filename from within that script? | [
"",
"javascript",
"html",
""
] |
Is it possible to have Greasemonkey scripts run before *anything* else on the page?
I'm aware of `@run-at document-start`, but this appears to run immediately after the `<HTML>` tag. Normally this isn't a problem, but if the page is misformatted as in the example below, there doesn't seem to be anything I can do.
I'd appreciate any suggestions or ideas.
Thanks!
```
<script>alert('This is an annoying message.');</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
...etc...
``` | It's not possible, because HTML requres that scripts are executed *during* parsing or not at all, e.g. this is allowed:
```
<script> document.write('<!'+'--'); </script>
```
If browser goes past this script without executing it, it will see completely different document, therefore you can't analyze DOM of HTML document before scripts run.
Opera solves this problem in [UserJS](http://www.opera.com/browser/tutorials/userjs/specs/) by firing `BeforeScript` events, allowing UserJS to change/remove scripts at the very last moment. | Actually, `@run-at document-start` **does** pretty much run the GM script before anything from the page.
In your case, the following code will work in conjunction with `@run-at document-start`:
```
_oldAlert = alert;
unsafeWindow.alert = function () {};
/*-- Optionally, wait for the DOM, then set an onload handler to restore
alert().
*/
``` | How does one have Greasemonkey run before *anything* else in the page? | [
"",
"javascript",
"greasemonkey",
""
] |
Does anyone know what can cause this problem?
> PHP Fatal error: Cannot redeclare class | It means you've already created a class.
For instance:
```
class Foo {}
// some code here
class Foo {}
```
That second Foo would throw the error. | You have a class of the same name declared more than once. Maybe via multiple includes. When including other files you need to use something like
```
include_once "something.php";
```
to prevent multiple inclusions. It's very easy for this to happen, though not always obvious, since you could have a long chain of files being included by one another. | PHP Fatal error: Cannot redeclare class | [
"",
"php",
"class",
"fatal-error",
""
] |
Is there a way I can preserve the original order of attributes when processing XML with minidom?
Say I have: `<color red="255" green="255" blue="233" />`
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.
I am processing the file by looping through the elements returned by `elements = doc.getElementsByTagName('color')` and then I do assignments like this `e.attributes["red"].value = "233"`. | > Is there a way I can preserve the original order of attributes when processing XML with minidom?
With minidom no, the datatype used to store attributes is an unordered dictionary. [pxdom](http://www.doxdesk.com/software/py/pxdom.html) can do it, though it is considerably slower. | To keep the attribute order I made this slight modification in minidom:
```
from collections import OrderedDict
```
In the Element class :
```
__init__(...)
self._attrs = OrderedDict()
#self._attrs = {}
writexml(...)
#a_names.sort()
```
Now this will only work with Python 2.7+
And I'm not sure if it actually works => Use at your own risks...
And please note that you should not rely on attribute order:
*Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.* | Preserve order of attributes when modifying with minidom | [
"",
"python",
"xml",
"minidom",
""
] |
I am getting this error:
> type Bar does not implement interface IFoo
From this code:
```
public interface IFoo
{
void DoA();
void DoB();
}
public class Foo:IFoo
{
void IFoo.DoA()
{
}
void IFoo.DoB()
{
}
}
public class Bar:Foo
{
void IFoo.DoA()
{
base.doA();
}
void IFoo.DoB()
{
base.doB();
}
}
```
I am using C# 2.0.
What am I doing wrong? | I have run into this as well. what is 'worse', depending on how you look at it is you can't define the interface implementations to be virtual to be overridden in descendent classes. I have gotten into the habit of doing this:
```
public class Foo:IFoo
{
void IFoo.DoA()
{
DoACore();
}
void IFoo.DoB()
{
DoBCore();
}
protected virtual void DoACore()
{
}
protected virtual void DoBCore()
{
}
}
public class Bar:Foo
{ protected override void DoACore()
{
base.DoACore();
}
protected override void DoBCore()
{
base.DoBCore();
}
}
``` | ```
public class Bar : Foo, IFoo
{
// Your code
}
``` | Why am I getting an error in C# when mixing explicit implementation and polymorphism? | [
"",
"c#",
".net",
"design-patterns",
""
] |
I feel that I am not utilizing all the features of delegates/events available in .NET 3.5 and beyond. And more or less still using delegates power available in 2.0. I would appreciate if you tell me how delegates/events should be used now, tricks, short-cuts.
Thanks.
**EDIT**
***Jon suggested his publication on this subject, and I am posting here for easier navigations:***
A few of my articles which may be relevant:
* [Events](http://www.yoda.arachsys.com/csharp/events.html)
* [Delegates in C# 2.0](http://www.yoda.arachsys.com/csharp/csharp2/delegates.html)
* [Closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx)
* [C# 2 bluffers' guide](http://csharpindepth.com/Articles/General/BluffersGuide2.aspx)
* [C# 3 bluffers' guide](http://csharpindepth.com/Articles/General/BluffersGuide3.aspx)
My book, C# in Depth, has a whole chapter devoted to delegates (chapter 5). Unfortunately that's not one of the free ones :(
ps. I couldn't find a duplicate of this question but did look through many on this theme. | A few of my articles which may be relevant:
* [Events](http://pobox.com/~skeet/csharp/events.html)
* [Delegates in C# 2.0](http://pobox.com/~skeet/csharp/csharp2/delegates.html)
* [Closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx)
* [C# 2 bluffers' guide](http://csharpindepth.com/Articles/General/BluffersGuide2.aspx)
* [C# 3 bluffers' guide](http://csharpindepth.com/Articles/General/BluffersGuide3.aspx)
My book, [C# in Depth](http://manning.com/skeet), has a whole chapter devoted to delegates (chapter 5). Unfortunately that's not one of the free ones :(
The main changes in summary (as Jared said, these are language changes - .NET itself hasn't changed much beyond them becoming generic, and the framework supplying the handy `Func` and `Action` delegates):
C# 2:
* Method group conversions:
```
// Old:
button.Click += new EventHandler(HandleClick);
// New:
button.Click += HandleClick;
```
* Anonymous methods:
```
button.Click += delegate { Console.WriteLine("Click!"); };
```
* Covariance/contravariance:
```
EventHandler generalHandler = LogEvent;
button.Click += generalHandler;
button.KeyPress += generalHandler; // Event type is KeyPressEventHandler
```
C# 3:
* Lambda expressions:
```
button.Click += (sender, args) => Console.WriteLine("Click!");
```
or more importantly:
```
var people = list.Where(person => person.Name != "Jon")
.OrderBy(person => person.Age);
``` | Delegates didn't change at all 2.0 -> 3.5. What changed was a lot of items around them
1. The System.Core.dll (finally) added reusable delegates in the form of Func<> and Action<>
2. C# and VB gained a bit of a functional flavor with lambda expressions. This gave the languages very succinct syntax for expression a delegate operation. C# had anonymous methods in 2.0 but they just don't compare with the succint nature of lambda expressions
```
list.Where(x => x > 42);
```
3. LINQ in it's underpinnings exposes a series of APIs that operate purely on delegates.
So really delegetase haven't changed, just the uses. | What new functionality is available through delegates and events in C# 3? | [
"",
"c#",
".net",
"c#-3.0",
""
] |
I have a web application that I am working on(ASP.NET 2.0 & C#). In it, I have a gridview that gets data from an Oracle Database. Some of the data that I need to display is dates. But when the dates in my gridview show like this:
> 2009-04-02 00:00:00
I'd prefer they show without the time. I'm using the codebehind to get the data, so I cant alter the fields of the gridview manually. This is all the code for my gridview :
```
<asp:GridView ID="Grid" runat="server" EmptyDataText="There are no data records to display." ></asp:GridView>
```
How do I stop the time from displaying? | You can apply a `dataformatstring` in the `gridview` column to only show the date.
To get it to work you must make sure that `HTMLEncode` is set to `false`.
[More information](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx) | if you set your datasource programmatically (code behind), you can still have all your columns in the gridview (use asp:DataBoundColumn)
```
DataFormatString="{0:d}"
```
### EDIT
this code is for your aspx page, if you really want to stick your presentation logic in your code behind - you have 2 options:
1. format the Date on "RowDataBound" event
2. format the Date in your query - that way you won't have to deal with formatting in code at all | How can I stop the time from displaying in a GridView when displaying a date? | [
"",
"c#",
"asp.net",
"datetime",
"gridview",
""
] |
I'm wonder how people are kicking people out or blocking access to a site when you want to do an upgrade and you have users that are logged in.
My one thought is to just put a bool setting in a global file (such as the settings file) for whether or not the site is unavailable. True is available, while false is unavailable. When false, the next time the user attempts to access the site they will either be logged out or just presented with an unavailable message.
There are 2 issues I can see with this method:
1. If users are just finishing filling in a long form or writing a large portion of text (like a new question or answer on SO), as soon as they submit the form, they'd lose that information. (Can't always save it, because there maybe DB changes for that table or code may have changed already.)
2. Possible: On a busy site, editing the global file if it's more than a couple lines it might cause PHP parse errors if that page is loaded while it's partially uploaded or while saving. There might also be locking issues on the file, depending on the configuration.
Another option is to have a field in the database with the same setting. At the moment, I don't generally have a table for settings, so this would be the only thing in the table, but I could see it being faster as it avoids the second problem.
Is there something that you've used that worked well or any other ideas?
I'm working with LAMP. | You might want to utilize a webserver redirect. In case of Apache, a `.htaccess` file to redirect (or rewrite url) users to a static maintenance page:
```
RewriteRule ^updating.*$ $0 [NC,U,QSA,L]
RewriteRule .* /updating/ [NC,U,QSA,R=307,L]
```
In case you want to access the site yourself when in the maintenance mode, you can attach a specific and hopefully-unique string to the useragent header:
```
RewriteRule ^updating.*$ $0 [NC,U,QSA,L]
RewriteCond %{HTTP:User-Agent} !MY-CUSTOM-UA-STRING [NC]
RewriteRule .* /updating/ [NC,U,QSA,R=307,L]
```
Here's how to manipulate your user-agent in firefox:
Create a new `about:config` key named `general.useragent.extra.XYZ` and set it as **"MY-CUSTOM-UA-STRING"** or anything else you wish. Firefox will attach the string to the UA.
If using Chrome, try the new **Mobile Emulation** feature which allows you to modify the user-agent string directly from the devtools.
As you've mentioned yourself, an alternative solution could be setting of a config flag on the server side. Before making so, I suggest that you save all the user's ongoing operations on the site and let her resume them after the maintenance period. Also, let them know the exact time of maintenance beforehand. | Inform the users in advance that your site will have downtime at a specified time and then perform the upgrade at your least busy hours according to your log files. Weekends work great for upgrading if your site is business critical to your users. A little downtime on a Sunday morning at about 3am probably isn't going to anger too many users. Just make sure that you have everything you need in place before you do the upgrade so that you can minimize the downtime. You might even consider doing a dry run on a test server. | What is the best method for taking a site down and kicking out users to do an upgrade? | [
"",
"php",
"authentication",
""
] |
I don't use prefix while naming internal variables of a class (I know some do but I am not starting "why do you..." debate). I just prefer it that way. The problem is that sometimes same parameters are passed in contructor and I end up being confused how to name them. For example:
```
public class SampleClass
{
private int classId;
private string className;
public SampleClass (int XclassIdX, string XclassNameX) {
classId = XclassIdX;
className = XclassNameX;
}
}
```
How to name XclassIdX and XclassNameX?
One thing that can probably be done is:
```
public class SampleClass
{
private int classId;
private string className;
public SampleClass (int classId, string className) {
this.classId = classId;
this.className = className;
}
}
```
Just not sure whether this is a good idea or there are other more elgant ways? | I think the solution you're describing, where the constructor parameters are identically named and you prefix the class members with `this`, is just fine. It's clear, it's concise, and there is no confusion about what you meant. | I simply use the `this` approach; then all my variables and fields reflect their intent. Don't do the `X` thing - that is just ugly ;-p | How do you name constructor argument and member variables? | [
"",
"c#",
"naming-conventions",
""
] |
Unlike protected inheritance, C++ private inheritance found its way into mainstream C++ development. However, I still haven't found a good use for it.
When do you guys use it? | Note after answer acceptance: *This is NOT a complete answer. Read other answers like [here](https://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance/656235#656235) (conceptually) and **[here](https://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance/675451#675451)** (both theoretic and practic) if you are interested in the question. This is just a fancy trick that can be achieved with private inheritance. While it is* fancy *it is not the answer to the question.*
Besides the basic usage of just private inheritance shown in the C++ FAQ (linked in other's comments) you can use a combination of private and virtual inheritance to *seal* a class (in .NET terminology) or to make a class *final* (in Java terminology). This is not a common use, but anyway I found it interesting:
```
class ClassSealer {
private:
friend class Sealed;
ClassSealer() {}
};
class Sealed : private virtual ClassSealer
{
// ...
};
class FailsToDerive : public Sealed
{
// Cannot be instantiated
};
```
*Sealed* can be instantiated. It derives from *ClassSealer* and can call the private constructor directly as it is a friend.
*FailsToDerive* won't compile as it must call the *ClassSealer* constructor directly (virtual inheritance requirement), but it cannot as it is private in the *Sealed* class and in this case *FailsToDerive* is not a friend of *ClassSealer*.
---
**EDIT**
It was mentioned in the comments that this could not be made generic at the time using CRTP. The C++11 standard removes that limitation by providing a different syntax to befriend template arguments:
```
template <typename T>
class Seal {
friend T; // not: friend class T!!!
Seal() {}
};
class Sealed : private virtual Seal<Sealed> // ...
```
Of course this is all moot, since C++11 provides a `final` contextual keyword for exactly this purpose:
```
class Sealed final // ...
``` | I use it all the time. A few examples off the top of my head:
* When I want to expose some but not all of a base class's interface. Public inheritance would be a lie, as [Liskov substitutability](https://en.wikipedia.org/wiki/Liskov_substitution_principle) is broken, whereas composition would mean writing a bunch of forwarding functions.
* When I want to derive from a concrete class without a virtual destructor. Public inheritance would invite clients to delete through a pointer-to-base, invoking undefined behaviour.
A typical example is deriving privately from an STL container:
```
class MyVector : private vector<int>
{
public:
// Using declarations expose the few functions my clients need
// without a load of forwarding functions.
using vector<int>::push_back;
// etc...
};
```
* When implementing the Adapter Pattern, inheriting privately from the Adapted class saves having to forward to an enclosed instance.
* To implement a private interface. This comes up often with the Observer Pattern. Typically my Observer class, MyClass say, *subscribes itself* with some Subject. Then, only MyClass needs to do the MyClass -> Observer conversion. The rest of the system doesn't need to know about it, so private inheritance is indicated. | When should I use C++ private inheritance? | [
"",
"c++",
"oop",
""
] |
Why do I get a stack overflow error if I use the set accessor to change a static class member in C#?
I am not disputing this as a bug, I just want to know what exactly is going on in the internals of the machine. | You shouldn't; I expect you have something like:
```
private static int foo;
public static int Foo {
get {return foo;}
set {Foo = value;} // spot the typo!!! (should be foo)
}
```
Essentially, the `set` is:
```
static void set_Foo(int value) {
set_Foo(value);
}
```
so this is recursive, and will eventually consume up the stack (assuming no optimisations, etc).
It is impossible to diagnose more without a code sample. | I'm guessing you're doing something like this:
```
public class MyClass
{
public int TheInt
{
get
{
return TheInt;
}
set
{
TheInt = value; // assignment = recursion!
}
}
```
The problem is, in the set function for TheInt, you're assigning a value to TheInt which will result in a nested call to the set function. You get recursion, and then a stack overflow. | Why does setting a static method result in a stack overflow? | [
"",
"c#",
".net",
"static",
""
] |
I'm running SQuirreL SQL (2.6.8) on Max OS X.
I'm running out of heap space when trying to create a Table script.
How to configure SQuirreL SQL to start up with a higher JVM heap size? | Assuming you have the SQuirreL in your Dock you can do following:
2. Cmd-Click on the SQuirreL icon in the Dock, the Finder window will open showing the you the application.
3. Left-Click on the SQuirreL Application and choose "Show package contents"
4. Navigate into Contents folder and open Info.plist file
5. Change or add following to your Info.plist file:
> ```
> <key>Java</key>
> <dict>
> <key>VMOptions</key>
> <array>
> <string>-Xms128m</string>
> <string>-Xmx512m</string>
> </array>
> </dict>
> ```
Here you get 128M at the start time with maximal SQuirreL.
Save the Info.plist file and restart the application. | I'm running Linux, so you'll have to adapt this answer somewhat, but it should be applicable.
In the home directory that the installer jar creates, you'll find a file called "squirrel-sql.sh". The last line of this file is the java launch cmd. Not sure about the mac launch configuration, you might need to look for the file in this directory that contains this line. Mine reads
```
$JAVA -Xmx256m -cp $TMP_CP net.sourceforge.squirrel_sql.client.Main --log-config-file $SQUIRREL_SQL_HOME/log4j.properties --squirrel-home $SQUIRREL_SQL_HOME $1 $2 $3 $4 $5 $6 $7 $8 $9
```
The -Xmx256m configures the heap - it sets the max heap size to 256m. Just edit the file to read -Xmx512m or whatever. (for a list of the memory flags, type "java -X" at a command prompt). | Increasing Heap size for SQuirreL SQL on Max OS X | [
"",
"java",
"macos",
"squirrel-sql",
""
] |
We want to split a working application in two different `.war` files in order to be able to update one app without affecting the other. Each webapp will have different a UI, different users and different deploy schedule.
The easiest path seems to be sharing the same session, so if app A set `session.setAttribute("foo", "bar")` app B will be able to see it.
Is there a way to share the `HttpSession` state for both apps in the same Tomcat instance?
Our app is running on a dedicated Tomcat 5.5, there are no other apps running on the same tomcat instance, so any security concerns regarding the session sharing are not a problem. We're running multiple Tomcat instances, but the balancer is using sticky sessions.
If it's not possible or this *session sharing* is a really bad idea please leave a comment. | You should not share HttpSession; but you can share other objects. For example, you can [register an object via JNDI](http://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html) and access the same object in all your apps (databases use this to pool connections). | One thing to be aware of is that two web apps will use different classloaders. If you want to share objects, they need to use the same version of the class from the same classloader (or else you will get LinkageErrors). That means either putting them in a classloader shared by both web apps (system classpath for example) OR using serialization to effectively drain and reconstitute the object in the right classloader with the correct version of the class. | Any way to share session state between different applications in tomcat? | [
"",
"java",
"session",
"tomcat",
"jakarta-ee",
""
] |
I have created the following function for checking the connection status:
```
private void checkConnectionStatus() {
HttpClient httpClient = new DefaultHttpClient();
try {
String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/"
+ strSessionString + "/ConnectionStatus";
Log.d("phobos", "performing get " + url);
HttpGet method = new HttpGet(new URI(url));
HttpResponse response = httpClient.execute(method);
if (response != null) {
String result = getResponse(response.getEntity());
...
```
When I shut down the server for testing the execution waits a long time at line
```
HttpResponse response = httpClient.execute(method);
```
Does anyone know how to set the timeout in order to avoid waiting too long?
Thanks! | In my example, two timeouts are set. The connection timeout throws `java.net.SocketTimeoutException: Socket is not connected` and the socket timeout `java.net.SocketTimeoutException: The operation timed out`.
```
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
```
If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function **setParams()**.
```
httpClient.setParams(httpParameters);
``` | To set settings on the client:
```
AndroidHttpClient client = AndroidHttpClient.newInstance("Awesome User Agent V/1.0");
HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);
HttpConnectionParams.setSoTimeout(client.getParams(), 5000);
```
I've used this successfully on JellyBean, but should also work for older platforms ....
HTH | How to set HttpResponse timeout for Android in Java | [
"",
"java",
"android",
"timeout",
"httpresponse",
""
] |
I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have.
\*To clarify... I can get the totals of the roll1.roll\_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.
```
class Die():
def __init__(self, s = 6):
self.sides = s
def roll_die(self):
x = random.randint(1,self.sides)
return x
roll1 = Die() #Rolling die 1 with the default side of 6
roll2 = Die(4) #Rolling die 2 with 4 sides
roll3 = Die(12) #Rolling die 3 with 12 sides
print roll1.roll_die()
print roll2.roll_die()
print roll3.roll_die()
``` | I'm not sure exactly where you're confused. The simplest thing you need to do is separate the concept of a specific die you're going to roll (the object) with the action (rolling it). I would start here:
```
d6 = Die() #create die 1 with the default side of 6
d4 = Die(4) #create die 2 with 4 sides
d12 = Die(12) #create die 3 with 12 sides
roll1 = d6.roll_die()
roll2 = d4.roll_die()
roll3 = d12.roll_die()
print "%d\n%d\n%d\nsum = %d" % (roll1, roll2, roll3, roll1 + roll2 + roll3)
```
... and then get fancier with lists, etc. | You can store the results in a list:
```
rolls = [Die(n).roll_die() for n in (6, 4, 12)]
```
then you can show the individual results
```
>>> print rolls
[5, 2, 6]
```
or sum them
```
>>> print sum(rolls)
13
```
Or, instead, you could keep a running total:
```
total = 0
for n in (6, 4, 12):
value = Die(n).roll_die()
print "Rolled a", value
total += value
print "Total is", total
```
(edited to reflect the changes/clarifications to the question) | Understanding Python Class instances | [
"",
"python",
"class",
"sum",
""
] |
I'd like to have access to the `$HOME` environment variable in a C++ program that I'm writing. If I were writing code in C, I'd just use the `getenv()` function, but I was wondering if there was a better way to do it. Here's the code that I have so far:
```
std::string get_env_var( std::string const & key ) {
char * val;
val = getenv( key.c_str() );
std::string retval = "";
if (val != NULL) {
retval = val;
}
return retval;
}
```
Should I use `getenv()` to access environment variables in C++? Are there any problems that I'm likely to run into that I can avoid with a little bit of knowledge? | There is nothing wrong with using `getenv()` in C++. It is defined by `stdlib.h`, or if you prefer the standard library implementation, you can include `cstdlib` and access the function via the `std::` namespace (i.e., `std::getenv()`). Absolutely nothing wrong with this. In fact, if you are concerned about portability, either of these two versions is preferred.
If you are *not* concerned about portability and you are using managed C++, you can use the .NET equivalent - [`System::Environment::GetEnvironmentVariable()`](http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable.aspx). If you want the non-.NET equivalent for Windows, you can simply use the [`GetEnvironmentVariable()`](http://msdn.microsoft.com/en-us/library/ms683188(VS.85).aspx) Win32 function. | I would just refactor the code a little bit:
```
std::string getEnvVar( std::string const & key ) const
{
char * val = getenv( key.c_str() );
return val == NULL ? std::string("") : std::string(val);
}
``` | Accessing Environment Variables In C++ | [
"",
"c++",
"environment-variables",
""
] |
I am pretty new to php and could sure use some help understanding how to get my result the way I need it from a database query.
What I need is an associative array like this, 'bla'=>'bla'. What I am getting from my foreach loop is this from a print:
```
[0] => Array
(
[0] => test0
[name] => test0
[1] => 1
[customer_id] => 1
)
[1] => Array
(
[0] => test
[name] => test
[1] => 2
[customer_id] => 2
)
```
Here is my loop:
```
foreach($res as $key=>$val)
{
// have no idea..
}
```
Can someone please help me to format my results so that they are like 'index'=>'value'
Thanks for any help.
---
Here is a sample code that uses a foreach but yet pulls an association. I don't get it. I am thinking that my result set with the indexes are because I am not writing the loop correctly. Here is the code that uses the foreach
```
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
```
---
Here is the part of the database class that I am using to fetch the results.
```
$returnArray = array();
$i=0;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
if($row)
$returnArray[$i++] = $row;
}
mysql_free_result($result);
return $returnArray;
```
After using the code that was given to me to omit the index numbers, here is what I am now left with. Its close but not what I need.
Array
(
[id] => 1
[cust] => bobs auto
)
This is what the above line should read like
```
'1' => 'bobs auto'
```
What I am trying to do is to format the output for a JSON call for a suggestion box.
I cannot get this to work. Here is everything after my db connection.
```
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
$out[$key['id']] = $val['cust'];
}
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out_array as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
```
---
OK, I think I am coming down to the home stretch. I have what I need sort of. This is the code I have so far.
```
$out_array = array();
foreach($items as $key)
{
$out_array[$key] = $val;
//$out_array[$key['id']] = $key['cust'];
}
```
Notice that the commented line does not work, It outputs like the id twice but the line that isn't commented out works just fine. Here is the output from that.
```
Array
(
[8] =>
[FAT BURGER] =>
)
```
From this point, would I just use another foreach to iterate over the entire set of data? The array output you see above is from a print\_r.
---
This is what I now have and it returns the correct association however, I must comment out the strpos condition to get any results back and I don't know why. Am I correct in nesting these foreach loops like I have?
```
$out_array = array();
foreach($items as $key)
{
// $out_array[$key] = $val;
$out_array[$key['id']] = $key['cust'];
foreach ($out_array as $key=>$value)
{
if (strpos(strtolower($key), $q) !== false)
{
echo "$key|$value\n";
}
}
}
``` | Try something like this. It works by skipping the integer indices, and putting the non-integer indices into an output array.
```
$out_array = array();
foreach($res as $key=>$val) {
if(is_int($key)) {continue;}
$out_array[$key] = $val;
}
```
EDIT:
```
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
}
$out[$out_array['id']] = $out_array['cust'];
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
``` | So you don't want the numeric indexes in your array? You must be using [mysql\_fetch\_array()](http://php.net/mysql_fetch_array), which returns your results with both numeric and string keys. Use [mysql\_fetch\_assoc()](http://php.net/mysql_fetch_assoc) to get an array with only the string keys (the string being the column name). | php arrays. How to format for my result | [
"",
"php",
""
] |
How can I compare the types of two objects declared as type.
I want to know if two objects are of the same type or from the same base class.
Any help is appreciated.
e.g.
```
private bool AreSame(Type a, Type b) {
}
``` | Say `a` and `b` are the two objects. If you want to see if `a` and `b` are in the same inheritance hierarchy, then use **[`Type.IsAssignableFrom`](http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx)**:
```
var t = a.GetType();
var u = b.GetType();
if (t.IsAssignableFrom(u) || u.IsAssignableFrom(t)) {
// x.IsAssignableFrom(y) returns true if:
// (1) x and y are the same type
// (2) x and y are in the same inheritance hierarchy
// (3) y is implemented by x
// (4) y is a generic type parameter and one of its constraints is x
}
```
If you want to check if one is a base class of the other, then try **[`Type.IsSubclassOf`](http://msdn.microsoft.com/en-us/library/system.type.issubclassof.aspx)**.
If you know the specific base class, then just use the `is` keyword:
```
if (a is T && b is T) {
// Objects are both of type T.
}
```
Otherwise, you'll have to walk the inheritance hierarchy directly. | There's a bit of a problem with this idea, though, as every object (and, indeed, every type) DOES have a common base class, Object. What you need to define is how far up the chain of inheritance you want to go (whether it's they're either the same or they have the same immediate parent, or one is the immediate parent of the other, etc.) and do your checks that way. `IsAssignableFrom` is useful for determining if types are compatible with one another, but won't fully establish if they have the same parent (if that's what you're after).
If your strict criteria is that the function should return true if...
* The types are identical
* One type is the parent (immediate or otherwise) of the other
* The two types have the same immediate parent
You could use
```
private bool AreSame(Type a, Type b)
{
if(a == b) return true; // Either both are null or they are the same type
if(a == null || b == null) return false;
if(a.IsSubclassOf(b) || b.IsSubclassOf(a)) return true; // One inherits from the other
return a.BaseType == b.BaseType; // They have the same immediate parent
}
``` | C# Object Type Comparison | [
"",
"c#",
"types",
""
] |
I see so much code including stdafx.h. Say, I do **not** want pre-compiled headers. And I **will** include all the required system headers myself manually. In that case is there any other good reason I should be aware of where I require `stdafx.h`? | If you don't want to use precompiled headers, then there is no point to using a standard include file - this will slow down the build for every file that includes it and cause them to include extra stuff that they do not need. Get rid of it and just include the headers they need. | `stdafx.h` is just another header file. If you feel that you don't need it then feel free to not include it and remove it from the project.
However it's quite typical to have a file like stdafx.h exactly for precompiled headers to work and to not include all the stuff manually in each source file. | stdafx.h: When do I need it? | [
"",
"c++",
"visual-c++",
"header",
"precompiled-headers",
"stdafx.h",
""
] |
I have a web application that communicates between two different web applications (one receiver and one sender, the sender communicates with my application, and my application communicates with both).
A regular scenario is that the sender sends a HttpRequest to my application, and I receive it in an HttpHandler. This in turn sends the HttpContext to some businesslogic to do some plumbing.
After my business classes are finished storing data (some logging etc), I want to relay the same request with all the headers, form data etc to the receiver application. This must be sent from the class, and not the HttpHandler.
The question is really - how can I take a HttpContext object, and forward/relay the exact same request only modifying the URL from <http://myserver.com/> to <http://receiver.com>.
Any code examples in preferable c# would be great! | Actually, something like this worked well
```
HttpRequest original = context.Request;
HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create(newUrl);
newRequest .ContentType = original.ContentType;
newRequest .Method = original.HttpMethod;
newRequest .UserAgent = original.UserAgent;
byte[] originalStream = ReadToByteArray(original.InputStream, 1024);
Stream reqStream = newRequest .GetRequestStream();
reqStream.Write(originalStream, 0, originalStream.Length);
reqStream.Close();
newRequest .GetResponse();
```
edit: ReadToByteArray method just makes a byte array from the stream | I have an extension method on `HttpResponseBase` to copy an incoming request to an outgoing request.
Usage:
```
var externalRequest = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
this.Request.CopyTo(externalRequest);
var externalResponse = (HttpWebResponse)externalRequest.GetResponse();
```
Source:
```
/// <summary>
/// Copies all headers and content (except the URL) from an incoming to an outgoing
/// request.
/// </summary>
/// <param name="source">The request to copy from</param>
/// <param name="destination">The request to copy to</param>
public static void CopyTo(this HttpRequestBase source, HttpWebRequest destination)
{
source.InputStream.Position = 0;
destination.Method = source.HttpMethod;
// Copy unrestricted headers (including cookies, if any)
foreach (var headerKey in source.Headers.AllKeys)
{
switch (headerKey)
{
case "Connection":
case "Content-Length":
case "Date":
case "Expect":
case "Host":
case "If-Modified-Since":
case "Range":
case "Transfer-Encoding":
case "Proxy-Connection":
// Let IIS handle these
break;
case "Accept":
case "Content-Type":
case "Referer":
case "User-Agent":
// Restricted - copied below
break;
default:
destination.Headers[headerKey] = source.Headers[headerKey];
break;
}
}
// Copy restricted headers
if (source.AcceptTypes.Any())
{
destination.Accept = string.Join(",", source.AcceptTypes);
}
destination.ContentType = source.ContentType;
destination.Referer = source.UrlReferrer.AbsoluteUri;
destination.UserAgent = source.UserAgent;
// Copy content (if content body is allowed)
if (source.HttpMethod != "GET"
&& source.HttpMethod != "HEAD"
&& source.ContentLength > 0)
{
var destinationStream = destination.GetRequestStream();
source.InputStream.CopyTo(destinationStream);
destinationStream.Close();
}
}
``` | Relaying a request in asp.net (Forwarding a request) | [
"",
"c#",
".net",
"http",
"communication",
"forwarding",
""
] |
I'm sure I'm not the first person to need to do this, so I'm looking for the best way.
I've got a set of radio buttons with choices such as
* This Year
* Last Year
* This Month
* Last Month
* This Week
* Last Week
and I need to produce the proper relative date range from the current date (`DateTime.Now`).
For example if `Last Year` was selected and the current date was `4/2/09 14:45:32` I would need to return a start date of `1/1/08 00:00:00` and end date of `12/31/08 23:59:59`.
Any thoughts? | All of these have been tested using DateTime.Today, and work just like you asked for:
```
public struct DateRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
public static DateRange ThisYear(DateTime date)
{
DateRange range = new DateRange();
range.Start = new DateTime(date.Year, 1, 1);
range.End = range.Start.AddYears(1).AddSeconds(-1);
return range;
}
public static DateRange LastYear(DateTime date)
{
DateRange range = new DateRange();
range.Start = new DateTime(date.Year - 1, 1, 1);
range.End = range.Start.AddYears(1).AddSeconds(-1);
return range;
}
public static DateRange ThisMonth(DateTime date)
{
DateRange range = new DateRange();
range.Start = new DateTime(date.Year, date.Month, 1);
range.End = range.Start.AddMonths(1).AddSeconds(-1);
return range;
}
public static DateRange LastMonth(DateTime date)
{
DateRange range = new DateRange();
range.Start = (new DateTime(date.Year, date.Month, 1)).AddMonths(-1);
range.End = range.Start.AddMonths(1).AddSeconds(-1);
return range;
}
public static DateRange ThisWeek(DateTime date)
{
DateRange range = new DateRange();
range.Start = date.Date.AddDays(-(int)date.DayOfWeek);
range.End = range.Start.AddDays(7).AddSeconds(-1);
return range;
}
public static DateRange LastWeek(DateTime date)
{
DateRange range = ThisWeek(date);
range.Start = range.Start.AddDays(-7);
range.End = range.End.AddDays(-7);
return range;
}
``` | This year:
```
DateTime Today = DateTime.Today;
DateTime StartDate = new DateTime(Today.Year,1,1);
DateTime EndDate = StartDate.AddYears(1).AddSeconds(-1);
```
This month:
```
DateTime Today = DateTime.Today;
DateTime StartDate = new DateTime(Today.Year,Today.Month,1);
DateTime EndDate = StartDate.AddMonths(1).AddSeconds(-1);
```
This week:
```
DateTime Today = DateTime.Today;
DateTime StartDate = Today.AddDays(-((int) Today.DayOfWeek));
DateTime EndDate = StartDate.AddDays(7).AddSeconds(-1);
```
Last year / month / week are simple variations on above. **Edit:** *This week* assumes the week starts on Sunday. You would have to modify the code slightly if your weeks start on Monday. | What's the best way to produce a relative date range (This week, This year, Last month, etc) from a DateTime? | [
"",
"c#",
".net",
"datetime",
"relative-date",
""
] |
Does the using statement really call the close method when used with a database connection object? [The MSDN documentation](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) says it ensures that the Dispose method is called but makes no mention of close. I see posts on Stack Overflow where people say that it does both. Does someone have a concrete answer one way or another on this from Microsoft or other solid proof that it does? | Here is the "Dispose" method of the SqlConnection class:
```
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
```
As you can see, it does indeed call Close() | If you use a `using` statement the connection will be closed, it makes no sense that a object that implements IDisposable, will remain open after it is garbage collected...
But `Close()` and `Dispose()` aren't the same thing:
* `Dispose()` always calls `Close()` implicitly.
* `Dispose()` clears the ConnectionString, `Close()` doesn't.
* If you're going to re-open the connection again, you should `Close()` not `Dispose()`
And if you choose to use `Dispose()` don't call it direcly, the `using` statement it's the best way to do it. | Using statement and Close methods | [
"",
"c#",
".net",
""
] |
I've already asked 2 questions kind of related to this project, and i've reached this conclusion. Writing the size of the Struct to the file , and then reading it back is the best way to do this.
I'm creating a program for a homework assignment that will allow me to maintain inventory. I need to read / write multiple structs of the same type to a file.
The problem is... this is really complicated and i'm having trouble wrapping my head around the whole process. I've seen a bunch of examples and i'm trying to put it all together. I'm getting compile errors... and I have zero clue on how to fix them. If you could help me on this I would be so appreciative... thank you. I'm so lost right now...
\*\*\*\* HOPEFULLY THE LAST EDIT #3 \*\*\*\*\*\*\*\*\*\*\*\*\*
My Code:
```
// Project 5.cpp : main project file.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace System;
using namespace std;
#pragma hdrstop
int checkCommand (string line);
template<typename Template>
void readFromFile(Template&);
template<typename Template>
void writeToFile(Template&);
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
template<typename Template>
void readVector(ifstream& in, vector<Template>& vec);
struct InventoryItem {
string Item;
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
int dateAdded;
} ;
int main(void)
{
cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
vector<InventoryItem> structList;
ofstream out("data.dat");
writeVector( out, structList );
while (1)
{
string line = "";
cout << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-4: ";
getline(cin , line);
int rValue = checkCommand(line);
if (rValue == 1)
{
cout << "You've entered a invalid command! Try Again." << endl;
} else if (rValue == 2){
cout << "Error calling command!" << endl;
} else if (!rValue) {
break;
}
}
system("pause");
return 0;
}
int checkCommand (string line)
{
int intReturn = atoi(line.c_str());
int status = 3;
switch (intReturn)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
status = 0;
break;
default:
status = 1;
break;
}
return status;
}
template <typename Template>
void readFromFile(Template& t)
{
ifstream in("data.dat");
readVector(in, t); Need to figure out how to pass the vector structList via a Template
in.close();
}
template <typename Template>
void writeToFile(Template& t)
{
ofstream out("data.dat");
readVector(out, t); Need to figure out how to pass the vector structList via a Template
out.close();
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); ++i)
{
out << *i; // SUPER long compile error
}
}
template<typename T>
vector<T> readVector(ifstream &in)
{
size_t size;
in >> size;
vector<T> vec;
vec.reserve(size);
for(int i = 0; i < size; ++i)
{
T tmp;
in >> tmp;
vec.push_back(tmp);
}
return vec;
}
```
My Compile Errors:
```
1>.\Project 5.cpp(128) : error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const InventoryItem' (or there is no acceptable conversion)
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\ostream(653): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1> with
```
That is the only error i'm getting now. I see your code is SO Much better. My new compiler error is SUPER long. I've shown where it the error points to. Could you help me just one last time? | Your read and write functions are buggy. In particular, you should be doing something like this instead:
```
template<typename T>
void write(ofstream &out, const T &t)
{
out << T;
}
```
**OLD:** `bind1st` requires you do include `functional` for it to work:
```
#include <functional>
```
Instead of dealing with all these functions and such, though, it'd be better to rely on iterators:
```
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); ++i)
{
out << *i;
}
}
template<typename T>
vector<T> readVector(ifstream &in)
{
size_t size;
in >> size;
vector<T> vec;
vec.reserve(size);
for(int i = 0; i < size; ++i)
{
T tmp;
in >> tmp;
vec.push_back(tmp);
}
return vec;
}
```
You'd want functions to read and write your `InventoryItem` as well, probably:
```
ostream &operator<<(ostream &out, const InventoryItem &i)
{
out << i.Item << i.Description; // FIXME Read/write strings properly.
out << i.Quantity;
out << i.wholesaleCost << i.retailCost;
out << i.dateAdded;
}
istream &operator>>(istream &out, InventoryItem &i)
{
// Keep in same order as operator<<(ostream &, const InventoryItem &)!
in >> i.Item >> i.Description; // FIXME Read/write strings properly.
in >> i.Quantity;
in >> i.wholesaleCost >> i.retailCost;
in >> i.dateAdded;
}
``` | NOTE: This is not an answer to the compilation errors you are getting, but rather a broader view of the persistence problem you are handling.
Serialization and deserialization is not the simplest problem you can work on. My advice would be investing in learning libraries (boost::serialization) and using them. They have already worked out many of the problems you will face at one time or another. Plus they already have different output formats (binary, xml, json...)
The first thing you must decide, that is if you decide to go ahead and implement your own, is what will be the file format and whether it suits all your needs. Will it always be used in the same environment? Will the platform change (32/64bits)? You can decide to make it binary as it is the simplest, or make it readable for a human being. If you decide on XML, JSON or any other more complex formats, just forget it and use a library.
The simplest solution is working on a binary file and it is also the solution that will give you a smallest file. On the other hand, it is quite sensible to architecture changes (say you migrate from a 32 to a 64 bit architecture/OS)
After deciding the format you will need to work on the extra information that is not part of your objects now but needs to be inserted into the file for later retrieval. Then start working (and testing) from the smallest parts to more complex elements.
Another advice would be to start working with the simplest most defined part and build from there on. Start avoiding templates as much as possible, and once you have it clear and working for a given data type, work on how to generalize it for any other type.
Disclaimer: I have written the code directly on the browser, so there could be some errors, typos or just about anything :)
**Text**
The first simple approach is just writting a textual representation of the text. The advantage is that it is portable and shorter in code (if not simpler) than the binary approach. The resulting files will be bigger but user readable.
At this point you need to know how reading text works with iostreams. Particularly, whenever you try to read a string the system will read characters until it reaches a separator. This means that the following code:
```
std::string str;
std::cin >> str;
```
will only read up to the first space, tab or end of line. When reading numbers (ints as an example) the system will read all valid digits up to the first non-valid digit. That is:
```
int i;
std::cin >> i;
```
with input 12345a will consume all characters up to 'a'. You need to know this because that will influence the way you persist data for later retrieval.
```
// input: "This is a long Description"
std::string str;
std::cin >> str; // Will read 'This' but ignore the rest
int a = 1;
int b = 2;
std::cout << a << b; // will produce '12'
// input: 12
int read;
std::cint >> read; // will read 12, not 1
```
So you pretty much need separators to insert in the output and to parse the input. For sample purposes I will select the '|' character. It must be a character that does not appear in the text fields.
It will also be a good idea to not only separate elements but also add some extra info (size of the vector). For the elements in the vector you can decide to use a different separator. If you want to be able to read the file manually you can use '\n' so that each item is in its own line
```
namespace textual {
std::ostream & operator<<( std::ostream& o, InventoryItem const & data )
{
return o << data.Item << "|" << data.Description << "|" << data.Quantity
<< "|" << data. ...;
}
std::ostream & operator<<( std::ostream & o, std::vector<InventoryItem> const & v )
{
o << v.size() << std::endl;
for ( int i = 0; i < v.size(); ++i ) {
o << v[i] << std::endl; // will call the above defined operator<<
}
}
}
```
For reading, you will need to split the input by '\n' to get each element and then with '|' to parse the InventoryItem:
```
namespace textual {
template <typename T>
void parse( std::string const & str, T & data )
{
std::istringstream st( str ); // Create a stream with the string
st >> data; // use operator>>( std::istream
}
std::istream & operator>>( std::istream & i, InventoryItem & data )
{
getline( i, data.Item, '|' );
getline( i, data.Description, '|' );
std::string tmp;
getline( i, tmp, '|' ); // Quantity in text
parse( tmp, data.Quantity );
getline( i, tmp, '|' ); // wholesaleCost in text
parse( tmp, data. wholesaleCost );
// ...
return i;
}
std::istream & operator>>( std::istream & i, std::vector<InventoryItem> & data )
{
int size;
std::string tmp;
getline( i, tmp ); // size line, without last parameter getline splits by lines
parse( tmp, size ); // obtain size as string
for ( int i = 0; i < size; ++i )
{
InventoryItem data;
getline( i, tmp ); // read an inventory line
parse( tmp, data );
}
return i;
}
}
```
In the vector reading function I have used getline + parse to read the integer. That is to guarantee that the next getline() will actually read the first InventoryItem and not the trailing '\n' after the size.
The most important piece of code there is the 'parse' template that is able to convert from a string to any type that has the insertion operator defined. It can be used to read primitive types, library types (string, for example), and user types that have the operator defined. We use it to simplify the rest of the code quite a bit.
**Binary**
For a binary format, (ignoring architecture, this will be a pain in the ass if you migrate) the simplest way I can think of is writing the number of elemements in the vector as a size\_t (whatever the size is in your implementation), followed by all the elements. Each element will printout the binary representation of each of its members. For basic types as int, it will just output the binary format of the int. For strings we will resort to writting a size\_t number with the number of characters in the string followed by the contents of the string.
```
namespace binary
{
void write( std::ofstream & o, std::string const & str )
{
int size = str.size();
o.write( &size, sizeof(int) ); // write the size
o.write( str.c_str(), size ); // write the contents
}
template <typename T>
void write_pod( std::ofstream & o, T data ) // will work only with POD data and not arrays
{
o.write( &data, sizeof( data ) );
}
void write( std::ofstream & o, InventoryItem const & data )
{
write( o, data.Item );
write( o, data.Description );
write_pod( o, data.Quantity );
write_pod( o, data. ...
}
void write( std::ofstream & o, std::vector<InventoryItem> const & v )
{
int size = v.size();
o.write( &size, sizeof( size ) ); // could use the template: write_pod( o, size )
for ( int i = 0; i < v.size(); ++i ) {
write( o, v[ i ] );
}
}
}
```
I have selected a different name for the template that writes basic types than the functions that write strings or InventoryItems. The reason is that we don't want to later on by mistake use the template to write a complex type (i.e. UserInfo containing strings) that will store an erroneous representation in disk.
Retrieval from disk should be fairly similar:
```
namespace binary {
template <typename T>
void read_pod( std::istream & i, T& data)
{
i.read( &data, sizeof(data) );
}
void read( std::istream & i, std::string & str )
{
int size;
read_pod( i, size );
char* buffer = new char[size+1]; // create a temporary buffer and read into it
i.read( buffer, size );
buffer[size] = 0;
str = buffer;
delete [] buffer;
}
void read( std::istream & i, InventoryItem & data )
{
read( i, data.Item );
read( i, data.Description );
read( i, data.Quantity );
read( i, ...
}
void read( std::istream & i, std::vector< InventoryItem > & v )
{
v.clear(); // clear the vector in case it is not empty
int size;
read_pod( i, size );
for ( int i = 0; i < size; ++i )
{
InventoryItem item;
read( i, item );
v.push_back( item );
}
}
}
```
For using this approach, the std::istream and std::ostream must be opened in binary mode.
```
int main()
{
std::ifstream persisted( "file.bin", ios:in|ios::binary );
std::vector<InventoryItem> v;
binary::read( persisted, v );
// work on data
std::ofstream persist( "output.bin", ios::out|ios::binary );
binary::write( persist, v );
}
```
All error checking is left as an exercise for the reader :)
If you have any question on any part of the code, just ask. | Compile errors while read/write size of multiple structs to file | [
"",
"c++",
"serialization",
"struct",
"compiler-errors",
""
] |
I was looking for a rule of thumb for allocating objects on stack or heap in C++. I have found many discussions here on SO. Many people said, it's about the lifetime of an object. If you need more lifetime than the scope of the function, put it in the heap. That makes perfect sense.
But what made me confusing is, many people said, allocate objects to stack if they are small. If objects are big, put it to heap. But none of them said how to identify an object is big or not?
I have the following questions,
1. How to identify an object is big or not?
2. What will be the stack maximum size? Each OS will have different stack size?
3. I have a wrapper class which wraps `vector<string>`. It will have around 100 items. Will it make a stack overflow if I allocate this class to a stack? I tried this, but it worked perfectly. Not sure I am doing something wrong. | Well firstly vectors (and all the STL container classes) always allocate from the heap so you don't have to worry about that. For any container with a variable size it's pretty much impossible to use the stack.
If you think about how stack allocation works (at compile time, basically by incrementing a pointer for each object) then it should be clear that vector memory comes from the heap.
```
std::vector<int> myInts;
std::string myString;
SomeOther Class;
// this memory must come from the heap, there's no way it
// can now be allocated on the stack since there are other
// objects and these parameters could be variable
myString = "Some String";
myInts.reserve(256);
```
Unless you are in a recursive function you can place several kilobytes of data on the stack without much worry. Stack-sizes are controlled by the program (not the OS) and the default tends to range from 32kb - 1mb. Most desktop software comes in at the 1mb range.
Individual objects are almost never a concern. In general they will either be small enough for the stack, or will allocate internally from the heap.
If objects are local to a function put them on the stack. If not put them on the heap.
Use the heap for large buffers you allocate for loading/sorting/manipulating data. | According to [MSDN](http://msdn.microsoft.com/en-us/library/tdkhxaks(VS.80).aspx) stack size defaults to 1mb. (This is for Msdev obviously).
As you can see from the article, you can modify the stack size at compile time with the /F flag.
I think your first guideline for stack vs heap usage is pretty accurate, with the qualification that if you temporary scope variable is bigger than a mb, stick it on the heap (and probably ask why you are allocating so much memory for a short period of time in the first place). | How to identify if an object should be on the stack or not? | [
"",
"c++",
"stack",
"heap-memory",
"stack-size",
""
] |
I just switched to start using a CDN for external images/static files for my site and I wanted to know how I could build a backup in case this CDN failed. Is there a way to reference an external link in an HTML/JavaScript file that would let you specify a fallback location for that file if it is unavailable in the first external host? | This first answer may not work in all browsers. You could just have some/remote/script.js set some variable "loaded=true" and then check it in the next script block.
```
<script>
loaded=false
</script>
<script src="some/remote/script.js"></script>
<script>
if(loaded==false){
//do what you want here if it didn't load
}
</script>
``` | There's a good article on this here: <http://happyworm.com/blog/2010/01/28/a-simple-and-robust-cdn-failover-for-jquery-14-in-one-line/>
This came in handy for me on a site using the Microsoft Ajax CDN to get jquery. We had a few customers whose machines did not trust the SSL certificate from the CDN when we used jquery on HTTPS pages. A local fallback is a good way to fix that problem.
We determined whether or not to inject the fallback by checking a variable the the script would have otherwise added to the global namespace. e.g.
```
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<script type="text/javascript">
//<![CDATA[
if (typeof jQuery == 'undefined') {document.write(unescape("%3Cscript src='/Scripts/jquery.min.js' type='text/javascript' %3E%3C/script%3E"));}
//]]>
</script>
``` | Is there a way to try and load a file in HTML/JavaScript and have a fallback if it doesn't load? | [
"",
"javascript",
"html",
""
] |
I'm working with an old SQL 2000 database and I don't have a whole lot of SQL experience under my belt. When a new row is added to one of my tables I need to assign a default time value based off of a column for work category.
For example, work category A would assign a time value of 1 hour, category B would be 2 hours, etc...
It should only set the value if the user does not manually enter the time it took them to do the work. I thought about doing this with a default constraint but I don't think that will work if the default value has a dependency.
What would be the best way to do this? | I would use a trigger on Insert.
Just check to see if a value has been assigned, and if not, go grab the correct one and use it. | Use a trigger as suggested by Stephen Wrighton:
```
CREATE TRIGGER [myTable_TriggerName] ON dbo.myTable FOR INSERT
AS
SET NOCOUNT ON
UPDATE myTable
SET
timeValue = '2 hours' -- assuming string values
where ID in (
select ID
from INSERTED
where
timeValue = ''
AND workCategory = 'A'
)
``` | How to set a default value for one column in SQL based on another column | [
"",
"sql",
""
] |
I have a huge set of log lines and I need to parse each line (so efficiency
is very important).
Each log line is of the form
cust\_name time\_start time\_end (IP or URL )\*
So ip address, time, time and a possibly empty list of ip addresses or urls separated by semicolons. If there is only ip or url in the last list there is no separator. If there
is more than 1, then they are separated by semicolons.
I need a way to parse this line and read it into a data structure. time\_start or
time\_end could be either system time or GMT. cust\_name could also have multiple strings
separated by spaces.
I can do this by reading character by character and essentially writing my own parser.
Is there a better way to do this ? | Maybe Boost RegExp lib will help you.
<http://www.boost.org/doc/libs/1_38_0/libs/regex/doc/html/index.html> | I've had success with [Boost Tokenizer](http://www.boost.org/doc/libs/1_37_0/libs/tokenizer/index.html) for this sort of thing. It helps you break an input stream into tokens with custom separators between the tokens. | Parsing a string in C++ | [
"",
"c++",
"parsing",
"logging",
"text-parsing",
""
] |
Using Informix, I've created a tempory table which I am trying to populate from a select statement. After this, I want to do an update, to populate more fields in the tempory table.
So I'm doing something like;
```
create temp table _results (group_ser int, item_ser int, restype char(4));
insert into _results (group_ser, item_ser)
select
group_ser, item_ser, null
from
sometable
```
But you can't select null.
For example;
```
select first 1 current from systables
```
works but
```
select first 1 null from systables
```
fails!
(Don't get me started on why I can't just do a SQL Server like "select current" with no table specified!) | [This page](http://www.geocities.com/SiliconValley/Bridge/4578/faq.html) says the reason you can't do that is because "NULL" doesn't have a type. So, the workaround is to create a sproc that simply returns NULL in the type you want.
That sounds like a pretty bad solution to me though. Maybe you could create a variable in your script, set it to null, then select that variable instead? Something like this:
```
DEFINE dummy INT;
LET dummy = NULL;
SELECT group_ser, item_ser, dummy
FROM sometable
``` | You don't have to write a stored procedure; you simply have to tell IDS what type the NULL is. Assuming you are not using IDS 7.31 (which does not support any cast notation), you can write:
```
SELECT NULL::INTEGER FROM dual;
SELECT CAST(NULL AS INTEGER) FROM dual;
```
And, if you don't have `dual` as a table (you probably don't), you can do one of a few things:
```
CREATE SYNONYM dual FOR sysmaster:"informix".sysdual;
```
The 'sysdual' table was added relatively recently (IDS 11.10, IIRC), so if you are using an older version, it won't exist. The following works with any version of IDS - it's what I use.
```
-- @(#)$Id: dual.sql,v 2.1 2004/11/01 18:16:32 jleffler Exp $
-- Create table DUAL - structurally equivalent to Oracle's similarly named table.
-- It contains one row of data.
CREATE TABLE dual
(
dummy CHAR(1) DEFAULT 'x' NOT NULL CHECK (dummy = 'x') PRIMARY KEY
) EXTENT SIZE 8 NEXT SIZE 8;
INSERT INTO dual VALUES('x');
REVOKE ALL ON dual FROM PUBLIC;
GRANT SELECT ON dual TO PUBLIC;
```
Idiomatically, if you are going to SELECT from Systables to get a single row, you should include '`WHERE tabid = 1`'; this is the entry for Systables itself, and if it is missing, the fact that your SELECT statement does return any data is the least of your troubles. (I've never seen that as an error, though.) | Informix: Select null problem | [
"",
"sql",
"select",
"informix",
""
] |
I'm trying to embed a Java Applet using the <OBJECT> tag, which is the XHTML Strict way of doing it.
After browsing lots of sites, I tried [this example](http://ww2.cs.fsu.edu/%7Esteele/XHTML/appletObject.html) which seems to work pretty well:
```
<!--[if !IE]> Firefox and others will use outer object -->
<object classid="java:Sample2.class"
type="application/x-java-applet"
archive="Sample2.jar"
height="300" width="450" >
<!-- Konqueror browser needs the following param -->
<param name="archive" value="Sample2.jar" />
<!--<![endif]-->
<!-- MSIE (Microsoft Internet Explorer) will use inner object -->
<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
codebase="http://java.sun.com/update/1.5.0/jinstall-1_5_0-windows-i586.cab"
height="300" width="450" >
<param name="code" value="Sample2" />
<param name="archive" value="Sample2.jar" />
<strong>
This browser does not have a Java Plug-in.
<br />
<a href="http://java.sun.com/products/plugin/downloads/index.html">
Get the latest Java Plug-in here.
</a>
</strong>
</object>
<!--[if !IE]> close outer object -->
</object>
<!--<![endif]-->
```
I downloaded that Sample2.jar and works perfectly on localhost.
Now, I replaced Sample2.class for the one I need to use (ar.uba.exactas.infovis.ivides.Scatterplot.class) and using my own JAR files (archive="piccolo.jar piccolox.jar netscape.jar scatterplot.jar"):
```
<!--[if !IE]> Firefox and others will use outer object -->
<object
classid="java:ar.uba.exactas.infovis.ivides.Scatterplot.class"
type="application/x-java-applet"
archive="piccolo.jar piccolox.jar netscape.jar scatterplot.jar"
height="300" width="450" >
<!-- Konqueror browser needs the following param -->
<param name="archive" value="piccolo.jar piccolox.jar netscape.jar scatterplot.jar" />
<!--<![endif]-->
<!-- MSIE (Microsoft Internet Explorer) will use inner object -->
<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
codebase="http://java.sun.com/update/1.5.0/jinstall-1_5_0-windows-i586.cab"
height="300" width="450" >
<param name="code" value="ar.uba.exactas.infovis.ivides.Scatterplot" />
<param name="archive" value="piccolo.jar piccolox.jar netscape.jar scatterplot.jar" />
<strong>
This browser does not have a Java Plug-in.
<br />
<a href="http://java.sun.com/products/plugin/downloads/index.html">
Get the latest Java Plug-in here.
</a>
</strong>
</object>
<!--[if !IE]> close outer object -->
</object>
<!--<![endif]-->
```
After doing so, I'm gettin this log dump:
```
java.lang.ClassNotFoundException: ar.uba.exactas.infovis.ivides.Scatterplot.class
at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: open HTTP connection failed:http://localhost/infovisUBA/2008-2C/tpfinal/bin/ar/uba/exactas/infovis/ivides/Scatterplot/class.class
at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
... 7 more
Excepción: java.lang.ClassNotFoundException: ar.uba.exactas.infovis.ivides.Scatterplot.class
```
The only difference I see is that I'm using a class inside a package.
Also, please note I did make this work using the <APPLET> tag, but I cannot make it with <OBJECT>.
Any clue? | Well, this was a hard one...
Struggled a lot of time but finally found that the problem was Opera itself. I was using an alpha version which had this bug. Now it works great! | Have you by any chance written this:
```
<param name="code"
value="ar.uba.exactas.infovis.ivides.Scatterplot.class" />
<param name="archive"
value="piccolo.jar piccolox.jar netscape.jar scatterplot.jar" />
```
instead of:
```
<param name="code"
value="ar.uba.exactas.infovis.ivides.Scatterplot" />
<param name="archive"
value="piccolo.jar piccolox.jar netscape.jar scatterplot.jar" />
```
The difference is the lack of ".class" at the end of the code value. Judging by the example, it should be at the end of the `classid` attribute, but not at the end of the value for the `code` param.
That's what the stack trace suggests to me:
```
Excepción: java.lang.ClassNotFoundException:
ar.uba.exactas.infovis.ivides.Scatterplot.class
```
I wouldn't expect to see the ".class" at the end of the class name. | ClassNotFoundException in Java Applet using <object> tag | [
"",
"java",
"xhtml",
"applet",
""
] |
Is there anyway I can get the name of class property `IntProperty`?
```
public class ClassName
{
public static int IntProperty { get { return 0; } }
}
//something like below but I want to get the string of "IntProperty"
ClassName.IntProperty.GetType().Name
```
Basically what I want to do is to dynamically save property name string into the database, and later on retrieve it from the database and invoke the property dynamically.
Seems like what I am looking for is similar to duck typing I think.
Thanks!
UPDATED:
This is the actual code. This is more like a workflow kind of thing. But each task is defined as property of a class (class is used to group tasks).
```
public class ApplicationTask
{
public static Task<string> SendIncompleteNotification
{
get
{
return new Task<string>
(
a => Console.WriteLine("Sample Task")
, "This is a sample task which does nothing."
);
}
}
}
```
So, the code will be able to retrieve the full name of the class and property something like: `namespace.ApplicationTask.SendIncompleteNotification` and save this into the database. Later on, the code will read the string and dynamically create the task and pass it into another to execute. | The result of `ClassName.IntProperty` is just an integer value. As soon as it's executed and the result is returned, there's no trace of it having come from `IntProperty`.
If you're using .NET 3.5 you can use an expression tree instead, usually created via a lambda expression:
```
Expression<Func<int>> exp = () => ClassName.IntProperty;
```
You can then compile and execute the expression *and* separately find out what it's doing (retrieving `IntProperty` in this case). I'm not really sure whether this is suitable for what you want to do though.
If you *do* work out how to save the property name in the database, then `GetProperty` is the way to go on the retrieval front.
Perhaps if you could give more context in the question in terms of how you want to use this, we could help more. You've shown just an expression - if you could show it in terms of where you'd be using it, that would be great.
EDIT: You've expanded the property, but not how it's being called. Do you *need* to call it directly, rather than just fetching the list of properties using `Type.GetProperties` and storing the list of property names in the database?
Again, if you could show the code which *calls* the property, and how you want it to interact with the database, we may be able to make more progress. | With C#6.0 you can get it by
```
nameof(ClassName.IntProperty)
``` | How to get name of a class property? | [
"",
"c#",
"reflection",
"properties",
"gettype",
""
] |
I am trying to create a class that doesn't re-create an object with the same input parameters. When I try to instantiate a class with the same parameters that were used to create an already-existing object, I just want my new class to return a pointer to the already-created (expensively-created) object. This is what I have tried so far:
```
class myobject0(object):
# At first, I didn't realize that even already-instantiated
# objects had their __init__ called again
instances = {}
def __new__(cls,x):
if x not in cls.instances.keys():
cls.instances[x] = object.__new__(cls,x)
return cls.instances[x]
def __init__(self,x):
print 'doing something expensive'
class myobject1(object):
# I tried to override the existing object's __init__
# but it didnt work.
instances = {}
def __new__(cls,x):
if x not in cls.instances.keys():
cls.instances[x] = object.__new__(cls,x)
else:
cls.instances[x].__init__ = lambda x: None
return cls.instances[x]
def __init__(self,x):
print 'doing something expensive'
class myobject2(object):
# does what I want but is ugly
instances = {}
def __new__(cls,x):
if x not in cls.instances.keys():
cls.instances[x] = object.__new__(cls,x)
cls.instances[x]._is_new = 1
else:
cls.instances[x]._is_new = 0
return cls.instances[x]
def __init__(self,x):
if self._is_new:
print 'doing something expensive'
```
This is my first venture into overriding `__new__` and I'm convinced I'm not going about it the right way. Set me straight, please. | First, use Upper Case Class Names in Python.
Second, use a **Factory** design pattern to solve this problem.
```
class MyObject( object ):
def __init__( self, args ):
pass # Something Expensive
class MyObjectFactory( object ):
def __init__( self ):
self.pool = {}
def makeMyObject( self, args ):
if args not in self.pool:
self.pool[args] = MyObject( args )
return self.pool[args]
```
This is much simpler than fooling around with new and having class level pools of objects. | Here's a class decorator to make a class a multiton:
```
def multiton(cls):
instances = {}
def getinstance(id):
if id not in instances:
instances[id] = cls(id)
return instances[id]
return getinstance
```
(This is a slight variant of the singleton decorator from PEP 318.)
Then, to make your class a multiton, use the decorator:
```
@multiton
class MyObject( object ):
def __init__( self, arg):
self.id = arg
# other expensive stuff
```
Now, if you instantiate MyObject with the same id, you get the same instance:
```
a = MyObject(1)
b = MyObject(2)
c = MyObject(2)
a is b # False
b is c # True
``` | How to create a class that doesn't re-create an object with identical input parameters | [
"",
"python",
"multiton",
""
] |
Platform: .NET Framework 3.5 SP1 on x32
Are there any performance issues regarding leaving an empty statement (";", by itself) in code?
And to be marked as an answer would you also teach a man (me? and other people reading this) to fish? Meaning, how to figure out there is a performance issue with it? | 1) Use a tool like ildasm or .NET Reflector to look inside the assembly that is generated and see what IL instructions are associated with the ";" empty statement (if any at all; they might get optimized away into nothing.)
2) Use a profiler to run a huge loop with a bunch of ";"s included inside other code, and then try it without the ";"s and see if there's a difference.
(Without doing either of these I'd bet quite a lot that it's optimized away and produces no IL (or some kind of no-op instruction -- pardon my IL ignorance.)) | The empty statement yields the nop IL code, so you can have as many as you like as they are removed by the JIT compiler. | Performance issues with empty ";" statement in C# | [
"",
"c#",
"performance",
""
] |
MSDN says that a class that would be 16 bytes or less would be better handled as a struct [[citation]](http://msdn.microsoft.com/en-us/library/ah19swz4(VS.71).aspx).
Why is that?
Does that mean that if a struct is over 16 bytes it's less efficient than a class or is it the same?
How do you determine if your class is under 16 bytes?
What restricts a struct from acting like a class? (besides disallowing parameterless constructors) | There are a couple different answers to this question, and it is a bit subjective, but some reasons I can think of are:
* `struct`s are value-type, `class`es are reference type. If you're using 16 bytes for total storage, it's probably not worth it to create memory references (4 to 8 bytes) for each one.
* When you have really small objects, they can often be pushed onto the IL stack, instead of references to the objects. This can really speed up some code, as you're eliminating a memory dereference on the callee side.
* There is a bit of extra "fluff" associated with classes in IL, and if your data structure is very small, none of this fluff would be used anyway, so it's just extra junk you don't need.
The most important difference between a `struct` and a `class`, though, is that `struct`s are value type and `class`es are reference type. | By "efficient", they're probably talking about the amount of memory it takes to represent the class or struct.
On the 32-bit platform, allocating an object requires a minimum of 16 bytes. On a 64-bit platform, the minimum object size is 24 bytes. So, if you're looking at it purely from the amount of memory used, a struct that contains less than 16 bytes of data will be "better" than the corresponding class.
But the amount of memory used is not the whole story. Value types (structs) are fundamentally different than reference types (classes). Structs can be inconvenient to work with, and can actually cause performance problems if you're not careful.
The real answer, of course, is to use whichever works best in your situation. In most cases, you'll be much better off using classes. | Questions about Structs | [
"",
"c#",
"class",
"struct",
"language-specifications",
""
] |
A simple Python IRC client library that supports SSL? | [Twisted](http://twistedmatrix.com/trac/wiki/TwistedWords) has an IRC client (in twisted.words), and it supports SSL.
There is an [example in the documentation](http://twistedmatrix.com/projects/words/documentation/examples/ircLogBot.py), just remember to do `reactor.connectSSL` instead of `reactor.connectTCP`.
If you don't want Twisted, there is also the [Python IRC library](http://python-irclib.sourceforge.net/), which I notice has SSL support in the latest release. | How simple? Chatzilla supports SSL and as any Mozilla Platform applications, allows using Python. <https://developer.mozilla.org/En/Python>
On second thought, that probably is a total overkill. A second on Ali's answer, Twisted will do. | A simple Python IRC client library that supports SSL? | [
"",
"python",
"irc",
""
] |
When I create a new entry in my MySQL database, I'd like the query to return the id of the table that was just created. If it cannot do this, is there another way to find out the this id? The reason I want to do this is so I can link a new row to the row that spawned it (and there's no guarantee that they're consecutive) | You mean last autoincrement id?
```
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
``` | You want [`mysql_insert_id()`](https://www.php.net/manual/en/function.mysql-insert-id.php) | Is there a way to return the id of a row that was just created in MySQL with PHP? | [
"",
"php",
"mysql",
""
] |
I'm new to Regular Expressions and things like that. I have only few knowledge and I think my current problem is about them.
I have a webpage, that contains text. I want to get links from the webpage that are only in `SPAN`s that have `class="img"`.
I go through those steps.
1. grab all the `SPAN`s tagged with the "img" class (this is the hard step that I'm looking for)
2. move those `SPAN`s to a new variable
3. Parse the variable to get an array with the links (Each `SPAN` has only 1 link, so this will be easy)
I'm using PHP, but any other language doesn't matter, I'm looking how to deal with the first step. Any one have a suggestion?
Thanks :D | Use PHPs [DOMDocument](http://php.net/manual/en/class.domdocument.php)-class in combination with the [DOMXPath](http://php.net/manual/en/class.domxpath.php)-class to navigate to the elements you need, like this:
```` ```
<?php
$dom = new DOMDocument();
$dom->loadHTML(file_get_contents('http://foo.bar'));
$xpath = new DOMXPath($dom);
``` ````
$elements = $xpath->query("/html/body//span[@class='img']//a");
foreach ($elements as $a)
{
echo $a->getAttribute('href'), "\n";
}
[You can learn more about the XPath Language on the W3C page.](http://www.w3.org/TR/xpath) | A pattern like `<span.* class="img".*>([^<]*)</span>` should work fine., assuming your code looks something like
```
<span class="img">http://www.img.com/img.jpg</span>
<span alt="yada" class="img">animage.png</span>
<span alt="yada" class="img" title="still works">link.txt</span>
<span>not an img class</span>
<?php
$pattern = '@<span.* class="img".*>([^<]*)</span>@i';
//$subject = html code above
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>
``` | How to lookup a url on a page | [
"",
"php",
"url",
"lookup",
""
] |
I'm building a UI for a program, and I can't figure out why my progress bar won't become visible after the convert button is clicked.
```
private void convertButton_Click(object sender, EventArgs e)
{
toolStripProgressBar.Visible = true;
...
toolStripProgressBar.Visible = false;
}
```
I ran into a similar problem with tkinter in Python, and I had to call a function to update the idle tasks. Is there a way to do this with windows forms without using threads?
Edit: On a side note, this is a progress bar in a toolStrip that also contains a label that gets updated with status bar text. Is there any way to get the label on the left side and the progress bar on the other instead of right next to each other on the left? | Well, there *is* a way to do this without using threads (`Application.DoEvents`) but I *strongly* recommend against you using it. Re-entrancy is nasty, and you really don't want the UI thread tied up at all.
Use [`BackgroundWorker`](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) instead - it's easy, and it's pretty much *designed* for progress bars. It takes the hassle out of using a separate thread and reporting progress back to the UI thread. No need for `Control.Invoke` etc - it takes care of that for you.
There are [lots of tutorials for `BackgroundWorker`](http://www.google.com/search?q=backgroundworker%2Btutorial) - it shouldn't take you too long to get going with it. | Per the question you asked for the way to do this WITHOUT threads, that is to do it with Application.DoEvents();. (Just add that call right after setting the progress bar as visible.)
Now I do agree with Jon Skeet though that BackgroundWorker is a better way of doing this, but it does use a separate thread. | C# Winforms How to update toolStrip in function | [
"",
"c#",
"winforms",
"visible",
"toolstrip",
""
] |
I thought I understood C# regular expressions, but clearly it's not the case. I need some help devising an expression that would find everything from START|BEGIN until )). Expression can be multi line.
Ex.
```
START( FTP_STATE, XXX(
VAL( FTP_INITIAL_STATE, 0 )
VAL( FTP_INBOUND, 1 )
AL( FTP_OUTBOUND, 2 )
))
/**************************************************************/
BEGIN( FTP_TIMER_MODE, YYY(
VAL( FTP_REMOVE_TIMER, 0 )
VAL( FTP_NOT_REMOVE_TIMER, 1 )
))
/**************************************************************/
```
Any help greatly appreciated | Try this:
```
(?:START|BEGIN)(?:[^)]+|\)[^)])+\)\)
```
To explain it:
* **`(?:START|BEGIN)`** Start with either `START` or `BEGIN`.
* **`(?:[^)]+|\)[^)])+`** After that either any character other than a `)` (`[^)]+`) or a `)` that is followed by any character other than `)` (`\)[^)]`) may follow. (So there is no way to match `))` with this expression.)
* **`\)\)`** Finally the `))`.
I hope this will reduce backtracking. | It is straight forward; START or BEGIN, then any number of any symbol but non greedy and finaly the two closing parenthesis. .\*? takes any number of any symbol, but as few as possible. To match over more then one line the single line option (?s) must be enabled (Thanks Alan M. for pointing that out.)
```
(?s)(START|BEGIN).*?\)\)
``` | How to find this using Regular Expression? | [
"",
"c#",
".net",
"regex",
""
] |
I would like to display what version my App is in on the UI. It looks like I set that in *Properties --> Application --> Assembler Information*.
* Is that correct?
* Do I manually increment that upon
releases?
* How do I access that
programmatically?
Thanks! | Yes, the assembly version is set that way. To display it in the UI, you can retrieve it with:
```
Assembly.GetExecutingAssembly().GetName().Version.ToString();
``` | For an example of how to read more info, simply add the standard AboutBox to a (dummy) project, and look at the source. Some of those elements are more readily available as Application properties though. | Access Version Info for Project | [
"",
"c#",
"winforms",
".net-3.5",
"versioning",
""
] |
I am developing a Java web application that bases it behavior through large XML configuration files that are loaded from a web service. As these files are not actually required until a particular section of the application is accessed, they are loaded lazily. When one of these files are required, a query is sent to the webservice to retrieve the corresponding file. As some of the configuration files are likely to be used much, much more often than others I'd like to setup some kind of caching (with maybe a 1 hour expiration time) to avoid requesting the same file over and over.
The files returned by the web service are the same for all users across all sessions. I do not use JSP, JSF or any other fancy framework, just plain servlets.
My question is, what is considered a best practice to implement such a global, static cache within a java Web application? Is a singleton class appropriate, or will there be weird behaviors due to the J2EE containers? Should I expose something somewhere through JNDI? What shall I do so that my cache doesn't get screwed in clustered environments (it's OK, but not necessary, to have one cache per clustered server)?
Given the informations above, Would it be a correct implementation to put an object responsible for caching as a ServletContext attribute?
Note: I do not want to load all of them at startup and be done with it because that would
1). overload the webservice whenever my application starts up
2). The files might change while my application is running, so I would have to requery them anyway
3). I would still need a globally accessible cache, so my question still holds
Update: Using a caching proxy (such as squid) may be a good idea, but each request to the webservice will send rather large XML query in the post Data, which may be different each time. Only the web application really knows that two different calls to the webservice are actually equivalent.
Thanks for your help | Your question contains several separate questions together. Let's start slowly. ServletContext is good place where you can store handle to your cache. But you pay by having cache per server instance. It should be no problem. If you want to register cache in wider range consider registering it into JNDI.
The problem with caching. Basically, you are retrieving xml via webservice. If you are accesing this webservice via HTTP you can install simple HTTP proxy server on your side which handle caching of xml. The next step will be caching of resolved xml in some sort of local object cache. This cache can exists per server without any problem. In this second case the EHCache will do perfect job. In this case the chain of processing will be like this `Client - http request -> servlet -> look into local cache - if not cached -> look into http proxy (xml files) -> do proxy job (http to webservice)`.
Pros:
* Local cache per server instance, which contains only objects from requested xmls
* One http proxy running on same hardware as our webapp.
* Possibility to scale webapp without adding new http proxies for xml files.
Cons:
* Next level of infrastructure
* +1 point of failure (http proxy)
* More complicated deployment
Update: don't forget to always send HTTP HEAD request into proxy to ensure that cache is up to date. | Here's an example of caching with EhCache. This code is used in several projects to implement ad hoc caching.
**1) Put your cache in the global context. (Don't forget to add the listener in WEB.XML).**
```
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
public class InitializationListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("dbCache", 100, false, true, 86400,86400);
singletonManager.addCache(memoryOnlyCache);
cache = singletonManager.getCache("dbCache");
ctx.setAttribute("dbCache", cache );
}
}
```
**2) Retrieve the cache instance when you need it. i.e. from a servlet:**
`cache = (Cache) this.getContext().getAttribute("dbCache");`
**3) Query the cache just before you do an expensive operation.**
```
Element e = getCache().get(key);
if (e != null) {
result = e.getObjectValue(); // get object from cache
} else {
// Write code to create the object you need to cache, then store it in the cache.
Element resultCacheElement = new Element(key, result);
cache.put(resultCacheElement);
}
```
**4) Also don't forget to invalidate cached objects when appropriate.**
You can find more samples [here](http://ehcache.sourceforge.net/samples.html) | Java Web Application: How to implement caching techniques? | [
"",
"java",
"servlets",
"caching",
"jakarta-ee",
""
] |
I've Inheritted a large Java Web project which I've got to make some modifications to, I'm a fairly competent Java Programmer when it comes the the basics but I've never done any JSP programming or EJB programming before. I remember vauguely doing some servlet programming 5 or so years ago in university, but I'm assuming that everything has changed since then.
I'd planned on getting myself up to speed this weekend, but I don't know where to start.
What would be a good learning trail to get me from Zero to proverbial Hero? or at least to a level of competency which will let me be able to read the JSP servlet and EJB code and understand how it works well enough to modify it and deploy it? | Ofcaurse it depends a lot on what project you inherited and when it was written.
Also what technologies are used?
The best resource on starting J2EE development I think it's the [Java Passion site](http://www.javapassion.com/j2ee/). | The online tutorial on netbeans.org are very good. I recommend to download the NetBeans 6.5 IDE (free) and walk through the J2EE tutorials.
The tutorials are very well written, and introduce the basic elements of enterprise and web development. They also require very little time to complete.
<http://www.netbeans.org/kb/> | Learning Trail for Java Web Development? | [
"",
"java",
"jsp",
""
] |
I'm trying to write a method that will calculate if two circles are overlapping. I've come up with the following and I'm just curious to know if there is anyway it could be optimised further.
```
private static boolean isCollision(Point2D p1, float r1, Point2D p2, float r2)
{
float a,dx, dy;
a = (r1+r2) * (r1+r2);
dx = (float) (p1.getX() - p2.getX());
dy = (float) (p1.getY() - p2.getY());
if (a > (dx*dx) + (dy*dy))
{
return true;
}
return false;
}
``` | Hmm. That looks pretty good as far as the math goes. Some minor points on how to make the Java side of it faster and terser:
* If you used doubles instead of floats for the radii, you wouldn't have to down-cast the doubles to floats.
* If you specifically ask for Point2D.Double parameters, you can use their x and y public fields instead of using the getters.
* Also, why the `if (foo) { return true; } else { return false; }?` Just do `return foo;`!
An improved version, then:
```
private static boolean isCollision(Point2D.Double p1, double r1, Point2D.Double p2, double r2)
{
final double a = r1 + r2;
final double dx = p1.x - p2.x;
final double dy = p1.y - p2.y;
return a * a > (dx * dx + dy * dy);
}
```
(Note that if your code is entirely float-based, you can do the same thing with `Point2D.Float` and `float`s.) | Overlap or intersect?
If intersect, don't forget about the case where the circles don't intersect because they are inside each other.
If it's overlap, I don't really see how you could optimize further; you're comparing the point distances to the sum of the radii, using distance squared to avoid taking a square root. Doesn't seem like there's any fat left to trim. | Fast circle collision detection | [
"",
"java",
"optimization",
"collision-detection",
"performance",
"geometry",
""
] |
I have a `string` which needs a decimal place inserted to give a precision of 2.
```
3000 => 30.00
300 => 3.00
30 => .30
``` | Given a string input, convert to integer, divide by 100.0 and use String.Format() to make it display two decimal places.
```
String.Format("{0,0:N2}", Int32.Parse(input) / 100.0)
```
Smarter and without converting back and forth - pad the string with zeros to at least two characters and then insert a point two characters from the right.
```
String paddedInput = input.PadLeft(2, '0')
padedInput.Insert(paddedInput.Length - 2, ".")
```
Pad to a length of three to get a leading zero. Pad to precision + 1 in the extension metheod to get a leading zero.
And as an extension method, just for kicks.
```
public static class StringExtension
{
public static String InsertDecimal(this String @this, Int32 precision)
{
String padded = @this.PadLeft(precision, '0');
return padded.Insert(padded.Length - precision, ".");
}
}
// Usage
"3000".InsertDecimal(2);
```
Note: PadLeft() is correct.
```
PadLeft() '3' => '03' => '.03'
PadRight() '3' => '30' => '.30'
``` | Use tryParse to avoid exceptions.
```
int val;
if (int.Parse(input, out val)) {
String.Format("{0,0:N2}", val / 100.0);
}
``` | Most efficient way to convert a string to 2 decimal places in C# | [
"",
"c#",
"string",
""
] |
In Oracle SQL there is a feature to order as follow:
```
order by decode("carrot" = 2
,"banana" = 1
,"apple" = 3)
```
What is the best way to implement this in python?
I want to be able to order a dict by its keys. And that order isn't necessarily alphabetically or anything - I determine the order. | You can't order a dict per se, but you can convert it to a list of (key, value) tuples, and you can sort that.
You use the .items() method to do that. For example,
```
>>> {'a': 1, 'b': 2}
{'a': 1, 'b': 2}
>>> {'a': 1, 'b': 2}.items()
[('a', 1), ('b', 2)]
```
Most efficient way to sort that is to use a key function. using cmp is less efficient because it has to be called for every pair of items, where using key it only needs to be called once for every item. Just specify a callable that will transform the item according to how it should be sorted:
```
sorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]])
```
The above defines a dict that specifies the custom order of the keys that you want, and the lambda returns that value for each key in the old dict. | Use the `key` named keyword argument of `sorted()`.
```
#set up the order you want the keys to appear here
order = ["banana", "carrot", "apple"]
# this uses the order list to sort the actual keys.
sorted(keys, key=order.index)
```
For higher performance than `list.index`, you could use `dict.get` instead.
```
#this builds a dictionary to lookup the desired ordering
order = dict((key, idx) for idx, key in enumerate(["banana", "carrot", "apple"]))
# this uses the order dict to sort the actual keys.
sorted(keys, key=order.get)
``` | python: arbitrary order by | [
"",
"python",
"sql-order-by",
""
] |
I am looking for a way to communicate with RS232 serial COM port on windows. I have found 2 solutions on the net, [one](http://www.easyvitools.com/phpserial/index.html) which is not totally free (introduces deliberate delays on the function) and [another](http://www.phpclasses.org/browse/package/3679.html) with limited capability on Windows. The latter can only write to a COM port on Windows, not read.
I can't look at the code of the first solution since it is compiled into a .dll (makes sense, otherwise people can just edit the delay and not purchase it...) and the second one seems only to use fopen() to open the port and later fwrite() to it for writing, just like one would do to a stream. But apparently freading it returns nothing.
I know it's possible as the first solution did it, although it does require Apache to use php-cgi module instead of php5module.
Any ideas? | Every solution above is either inefficient or too much work.
You can just use the [PHP-DIO library](http://php.net/manual/en/book.dio.php) (dio\_fcntl, dio\_open, dio\_read, dio\_write, dio\_seek, ...). It's also in [the PHP manual's entry for DIO](https://www.php.net/manual/en/book.dio.php):
This PECL package isn't available by default. To get it for Windows if you have PHP 5.2.x greater than 5.2.6, you can download it as part of a ZIP:
* [Thread-safe (for Apache)](http://museum.php.net/php5/pecl-5.2.6-Win32.zip)
* [Non-thread-safe (for IIS)](http://museum.php.net/php5/pecl-5.2.6-nts-Win32.zip)
Both of these links were found in <http://www.deveblog.com/index.php/download-pecl-extensions-for-windows/>
[Here is the build from Linux](http://pecl.php.net/package/dio), just get it and do the phpize/configure/make/make install thing.
I don't know whether it should be used in an Apache session, but go for it. | You need to set up the com port using a DOS-like command.
For example, the following line executes the command through php:
```
$output = `mode COM1: BAUD=115200 PARITY=N data=8 stop=1 XON=off TO=on`;
```
To display the results you can use:
```
echo "$output";
```
Create the resource id:
```
$fp = fopen('COM1', 'r+');
if (!$fp)
{
echo "Port not accessible";
}
else
{
echo "Port COM1 opened successfully";
}
```
Write to port:
```
$writtenBytes = fputs($fp, "Hello");
echo"Bytes written to port: $writtenBytes";
```
Read from port:
```
$buffer = fgets($fp);
echo "Read from buffer: $buffer";
```
Maybe someone can help me with the `fgets` problem. It stacks there for exactly one minute if `TO=on`, or stacks there forever if `TO=off`. It seems to be a "`MODE COM`" option so maybe a DOS expert can help.
Perhaps instead of `fgets`, one should use `fgetc`, since `fgets` capture through to the `newline`, while `fgetc` captures a single character. If a new line isn't encountered, it may block until there is one or until the buffer is flushed. The one minute delay may be windows flushing its buffer on an interval. | Serial comm with PHP on Windows | [
"",
"php",
"serial-port",
"communication",
""
] |
This question is mainly geared towards Zend in PHP, although it certainly applies to other languages and frameworks, so I welcome everyone's opinion.
I've only recently been using the Zend framework, and while it's not perfect, I have had a pretty good time with it. One thing that drives me crazy, however, is that most of the examples I see of people using Zend do the v[alidation in special form objects](http://framework.zend.com/manual/en/zend.form.advanced.html), rather than in the model. I think this is bad practice because data can enter into the system in other ways beyond form input, which means that either validators have to be bent and twisted to validate other input, or validation must be done in a second place, and logic duplicated.
I've found some other posts and blogs out there with people who feel the same way I do, but the developers of Zend made this choice for a reason, and other people seem to use it without issue, so I wanted to get some feedback from the community here.
As I said, this mainly applies to Zend, although I think it's important to look at the issue as a whole, rather than working within the confines of the Zend framework, since Zend was designed so that you could use as much, or as little, as you wished. | This is a non-zend specfic answer, however I believe that the model should be responsible for the validity of its own data. If this is the case then the validation belongs in the model, however this may not always be achievable and it may be necessary to perform validation in the view, however I think this should be in addition to the validation performed in the model not a replacement for it.
The problem with only having validation in the view is that at some point you will probably want another view on your data. Your site may become popular and customers are asking for XML based APIs to generate their own views. Do you then rely on the customer to validate the data?
Even if you do not have to provide APIs some customers may want customized views that are sufficiently different to warrant a completely different version of the page, again you now have validation in the views duplicated.
I think the ideal scenario is to have your model do the validation but to make the results of the validation available for the view to read and render the page again with the validation results displayed.
I think it is perfectly reasonable to have the view doing validation if you want to instantly display validation data back to the user etc but the final decision on data validity should rest with the model. | Perhaps you should have a look at [Using Zend\_Form in Your Models](http://weierophinney.net/matthew/archives/200-Using-Zend_Form-in-Your-Models.html) by [Matthew Weier O'Phinney](http://weierophinney.net/matthew/) - one of the lead-developers of the Zend Framework - for his view on exactly this question. | Should validation be done in Form objects, or the model? | [
"",
"php",
"zend-framework",
"validation",
"zend-validate",
""
] |
In a TC++ compiler, the binary representation of **5** is **(00000000000000101)**.
I know that negative numbers are stored as 2's complement, thus **-5** in binary is **(111111111111011)**. The most significant bit (sign bit) is 1 which tells that it is a negative number.
So how does the compiler know that it is **-5**? If we interpret the binary value given above **(111111111111011)** as an unsigned number, it will turn out completely different?
Also, why is the 1's compliment of **5** **-6 (1111111111111010)**? | **The compiler doesn't know**. If you cast `-5` to `unsigned int` you'll get `32763`. | The compiler knows because this is the convention the CPU uses natively. Your computer has a CPU that stores negative numbers in two's complement notation, so the compiler follows suit. If your CPU supported one's complement notation, the compiler would use that (as is the case with IEEE floats, incidentally).
The Wikipedia article on the topic explains how [two's complement](http://en.wikipedia.org/wiki/Two%27s%5Fcomplement) notation works. | Two's complement binary form | [
"",
"c++",
"binary",
"twos-complement",
""
] |
I am working with HTML which has javascript links like below:
```
<a href="javascript:openExternalLink(5542, true, 'http://www.websitedomain.com')">Links Text Here</a>
```
I need to replace these with standard anchor tags like so:
```
<a href="http://www.websitedomain.com">Links Text Here</a>
```
What would be the best solution to achive this in Jython?
Thanks
Eef | The best way would probably be to use regular expressions. | ```
var i= 0, A= document.links, who, url;
while(A[i]){
who= A[i++];
url= who.href || '';
if(url.indexOf('javascript:openExternalLink')== 0){
who.href= url.substring(url.indexOf("'"), url.lastIndexOf("'")+1);
}
}
``` | Convert JavaScript links to standard links | [
"",
"javascript",
"dom",
"jython",
""
] |
I'm using PIL
```
im = Image.open(teh_file)
if im:
colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color
red = colors[0] # and so on, some operations on color data
```
The problem is, on a few (very few, particulary don't know why those exactly, simple jpegs) I get 'unsubscriptable object' on line "colors[0]". Tried:
```
if colors:
```
gets true and goes on.
```
if len(colors):
```
gives 'len() of unsized object'
1. What condition should I apply not to get this exception?
2. What's the cause of the problem? | From the PIL docs:
```
getpixel
im.getpixel(xy) => value or tuple
Returns the pixel at the given position. If the image is a multi-layer image, this method returns a tuple.
```
So it seems that some of your images are multilayer, and some are single-layer. | As noted in another answer, `getpixel` returns either a single value, or a tuple. You could check the type and do the appropriate action in the following ways:
```
if isinstance(colors, tuple):
color = colors[0]
else:
color = colors
# Do other stuff
```
or:
```
try:
color = colors[0]
except: # Whatever the exception is - IndexError or whatever
color = colors
# Do other stuff
```
The second way is probably more Pythonic. | unsubscriptable object | [
"",
"python",
"image",
"image-processing",
"colors",
"python-imaging-library",
""
] |
I'm working on a Django site that has multiple sections and subsections. I'd like to have several depths of template inheritance: a base template for the whole site, one base template for each section that inherits from the root base template, and so on. Here's a simplified version of my desired directory structure:
```
base.html
section1/
base.html
section2/
base.html
section3/
base.html
```
What I would desire is for all the files under `section1/` to contain something like `{% extends "base.html" %}`, meaning they would extend `section1/base.html`. `section1/base.html` would contain something like `{% extends "../base.html" %}`, meaning that it would extend the root-level base file. However, I couldn't find anything in the documentation suggesting this was possible, and I couldn't get Django to distinguish between `"../base.html"` and `"base.html"`. (`{% extends "../base.html" %}` throws an error.) I suppose one workaround would be to rename all base files `base_SECTIONNAME.html`, and update all the files that inherit from them, but I am concerned that this might become difficult to maintain as my site becomes bigger and sections change names, etc. I would prefer a solution that takes advantage of the natural hierarchy specified by directories and subdirectories.
Any ideas? | May be I oversee something, but all you want can be accomplished with the django template system. All extends calls are relative to template directories.
1. In order for all base.html files in subdirectories to extend base.html, you just have to put a `{% extends "base.html" %}` into the files. section1/base.html would would look like that.
`{% extends "base.html" %}`
`{# ... rest of your code ...#}`
2. Now, to get the files from section1 to extend *section1/base.html* you just have to put `{% extends "section1/base.html" %}` at the top of them. Same for section2, section3 and so on.
It is just that simple, but might not totally obvious in the documentation.
I hope, I understood your question. | The accepted answer will work, but I do recommend using variable names to keep track of section structure. My personal preference would be a [context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#writing-your-own-context-processors). If, for example, your site's section organization is transparently reflected in the url, try something like:
```
# It may be convenient to make this function live in or near your url conf.
def convert_url_path_to_folder_path(path):
# fill in the magic here
def sub_folder_available(request):
folder = convert_url_path_to_folder_path(request.path)
return {'subsection': folder, 'local_base':folder+'/base.html'}
```
Then in your template, just call
```
{% extends local_base %}
```
There are probably a dozen other ways to do this, but the main thing is to think about avoiding hard-coding the folder name into the template. This will get you a lot of mileage, especially since you can just drag and drop template between sections if they happen to be similar enough. Another thing you might add insert is:
```
def sub_folder_available(request):
folder = convert_url_path_to_folder_path(request.path)
# Check if local base exists:
if os.access(folder+'/base.html',os.F_OK):
base = folder+'/base.html'
else:
# revert to your global base
base = 'base.html'
return {'subsection': folder, 'base':base}
```
The nice advantage of this strategy is of course that you can get a fly-weight section up and running without any local base template at all. | Django: specifying a base template by directory | [
"",
"python",
"django",
"django-templates",
""
] |
Ideally I would have a "isActive" field in the table to indicate if a record is active, but it would involve changes in multiple stored procedures to make the field do what it is meant to do.
I came up with a dirty trick, and kind of tempted to carry it out. Since the result set is generated by a few joins, I was thinking of slightly changing the foreign key in one of the tables by appending an "\*", "x", or whatever symbol that doesn't usually end up in a key.
Is there anything I should be afraid of? | One way to have a "not active" state without changing all the other stored procedures is to MOVE the record to a "non active" table while the record is not active. | > Is there anything I should be afraid of?
Is having an inconsistent data with discrepancy with unreadable data caused by appending special character an issue?
If this issue is to crop up some later time, I think it is time to refactor your stored procedures or tables. | Quick & Dirty Way of Disabling a Particular Foreign Key | [
"",
"sql",
""
] |
We are creating a unix timestamp with the mktime method giving following attributes:
```
print_r(mktime(0,0,0,3,1,2009));
print_r(mktime(null,null,null,3,1,2009) / 60 / 60 / 24) . "days");`
```
this creates a result of
```
1235862000
14303.958333333 days
```
this should be 14304 days. The problem in this case is the winter hour.
You can use the is\_dst parameter, and when we use 0 (default -1) this sometimes works correctly giving 14304 days as a result.
But sometimes this gives following problem:
> Strict Standards: mktime() [function.mktime]:The is\_dst parameter is deprecated
i have no idea what it means and what i can do about it. Any idea someone? because the winter hour is causing terrible head ache.... | Use [gmmktime](http://www.php.net/manual/en/function.gmmktime.php). | ```
date("I", time());
```
Will give you 1 if its daylight savings and 0 if its not. | how to get the correct timestamp with the is_dst parameter in PHP? | [
"",
"php",
"datetime",
"mktime",
""
] |
I am upgrading a Windows Client application that was earlier .NET 1.1. The previous developer handwrote many solutions that can be done automatically with the newer versions of .NET. Since I am relatively fresh to .NET and do not have the complete overview of the features I am asking here.
What is the most notable classes and syntax features provided in later .NET versions that is likely to swap out handwritten code with features from the library? | Biggest changes off the top of my head:
* Use generic collections instead of ArrayList, Hashtable etc.
* For C# 3.5, use LINQ instead of manually filtering/projecting
* Use generic delegates instead of having to declare your own all the time
* Use anonymous methods instead of creating a one line method used to create a delegate in one place
* Use BackgroundWorker for WinForms background tasks
Generics is the most wide-reaching change in my view. | Personally, I would leave any 1.1 code that works fine when compiled with 2.0/3.5. Unless you have the time, anything you rewrite you'll have to test again, and you still may introduce new bugs that your testing can't find.
Things that I'd look to use for future versions though, would be generics and LINQ. Generics with .NET 2, and LINQ with .NET 3.5. | Upgrading Code from .Net 1.1 to 2.0/3.5 (C#) | [
"",
"c#",
".net",
""
] |
I want to add a breakpoint condition to my code in VC++ Express 2005, so that the breakpoint only triggers if a local variable meets a specified criteria. e.g.
```
bool my_test(UIDList test_list) {
foo(test_list);
bar(test_list); // I have a breakpoint here, but only want it to trigger if test_list.Length() > 0
print(test_list);
}
```
Having right-clicked on my breakpoint and selected "Condition..." I have found a dialog that appears to do what I want, however anything I try typing into the text field results in the following error:
> Unable to evaluate the breakpoint
> condition: CX0052: Error: member
> function not present
I tried the help documentation, but I couldn't find my answer. I'm hoping someone experienced in VC++ might be able to point me in the right direction...
I have previously tried upgrading to a more recent version of VC++ Express, but the project did not import cleanly. Due to the complexity of the project and my current time scales I can't consider upgrading as a solution at this point. | use the DebugBreak(); function:
```
bool my_test(UIDList test_list) {
foo(test_list);
if (bar(test_list) /* or whatever check :) */) // I have a breakpoint here, but only want it to trigger if test_list.Length() > 0
DebugBreak();
}
print(test_list);
}
```
Or you can always use assert(expression)
```
bool my_test(UIDList test_list) {
foo(test_list);
bar(test_list);
assert(test_list.Length() > 0); // will break here
print(test_list);
}
``` | VS does have some micro-evaluation engines- in variable watch windows, immediate window, break point conditions etc. I could never find decent documentation on them. As far as i can tell they are picky about methods they're willing to call, **but** they're also insensitive to access limitations.
So, you can probably rephrase your condition from
```
test_list.Length() > 0
```
to something like
```
test_list.m_nLength > 0
```
(or whatever your private length var is).
(EDIT) Just found [this msdn page](http://msdn.microsoft.com/en-us/library/e0ysa1hs(VS.80).aspx) explaining what expressions the debugger can and can't handle. So first, [indeed](http://msdn.microsoft.com/en-us/library/0888kc6a(VS.80).aspx) -
> 'The debugger can access all class
> members regardless of access control.
> You can examine any class object
> member, including base classes and
> embedded member objects.'
And second, my guess regarding the failure to evaluate 'Length()' - it was probably inlined:
> 'A debugger expression cannot call an
> intrinsic or inlined function unless
> the function appears at least once as
> a normal function.' | How to add a conditional breakpoint in Visual C++ | [
"",
"c++",
"debugging",
"visual-c++",
"visual-studio-2005",
"breakpoints",
""
] |
I have a very large Java app. It runs on Tomcat and is your typical Spring/Hibernate webapp. It is also an extremely large Java program. It's easy for me to test the performance of database queries, since I can run those separately, but I have no idea to look for Java bottlenecks on a stack like this. I tried Eclipse's TPTP profiler, but it really didn't seem to like my program, and I suspect that it is because my program is too large. Does anyone have any advice on profiling a large webapp? | The [Visual VM](https://visualvm.dev.java.net/) profiler that now comes with the JDK can be attached to running processes and may at least give an initial overview of the performance. It is based on the Netbeans profiler. | I have used YourKit to profile applications with an 8 GB heap and it worked quite well. | How can I profile a very large Java webapp? | [
"",
"java",
"web-applications",
"profiling",
""
] |
I have a website (Flash) localized into a dozen of languages and I want to auto-define a default value depending on the user's browser settings in order to minimize the steps to access the content.
FYI, I cannot use server scripts due to proxy restrictions, so I guess JavaScript or ActionScript would be appropriate to solve the problem.
**Questions:**
1. What would be the best method to 'guess' the user's locale?
2. Are there any existing simple classes/functions that could help me out (no complex localization bundles)? Especially to reduce all possible languages to a smaller number (the translations I have) in a smart way.
3. To which point can I trust such a solution?
4. Any other workarounds or suggestions? | The proper way is to look at the HTTP [Accept-Language](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4) header sent to the server. This contains the ordered, weighted list of languages the user has configured their browser to prefer.
Unfortunately this header is not available for reading inside JavaScript; all you get is [`navigator.language`](https://developer.mozilla.org/docs/Web/API/NavigatorLanguage/language), which tells you what localised version of the web browser was installed. This is not necessarily the same thing as the user's preferred language(s). On IE you instead get `systemLanguage` (OS installed language), `browserLanguage` (same as `language`) and `userLanguage` (user configured OS region), which are all similarly unhelpful.
If I had to choose between those properties, I'd sniff for `userLanguage` first, falling back to `language` and only after that (if those didn't match any available language) looking at `browserLanguage` and finally `systemLanguage`.
If you can put a server-side script somewhere else on the net that simply reads the Accept-Language header and spits it back out as a JavaScript file with the header value in the string, eg.:
```
var acceptLanguage= 'en-gb,en;q=0.7,de;q=0.3';
```
then you could include a <script src> pointing at that external service in the HTML, and use JavaScript to parse the language header. I don't know of any existing library code to do this, though, since Accept-Language parsing is almost always done on the server side.
Whatever you end up doing, you certainly need a user override because it will always guess wrong for some people. Often it's easiest to put the language setting in the URL (eg. http://www.example.com/en/site vs http://www.example.com/de/site), and let the user click links between the two. Sometimes you do want a single URL for both language versions, in which case you have to store the setting in cookies, but this may confuse user agents with no support for cookies and search engines. | On Chrome and Firefox 32+, [`Navigator.languages`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages) contains an array of locales in order of user preference, and is more accurate than `navigator.language`, however, to make it backward-compatible (Tested Chrome / IE / Firefox / Safari), then use this:
```
function getLang() {
if (navigator.languages != undefined)
return navigator.languages[0];
return navigator.language;
}
``` | How can I determine a user's locale within the browser? | [
"",
"javascript",
"flash",
"browser",
"localization",
""
] |
How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?
```
a = str(52500)
b = str(5)
lengthDiff = len(a) - len(b)
formatted = '%s/%s' % (' '*lengthDiff + b, a)
# formatted looks like:' 5/52500'
``` | [Format operator](http://docs.python.org/library/stdtypes.html#string-formatting):
```
>>> "%10d" % 5
' 5'
>>>
```
Using `*` spec, the field length can be an argument:
```
>>> "%*d" % (10,5)
' 5'
>>>
``` | You can just use the `%*d` formatter to give a width. `int(math.ceil(math.log(x, 10)))` will give you the number of digits. The `*` modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing `'%*d'` % (width, num)` you can specify the width AND render the number without any further python string manipulation.
Here is a solution using math.log to ascertain the length of the 'outof' number.
```
import math
num = 5
outof = 52500
formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)
```
Another solution involves casting the outof number as a string and using len(), you can do that if you prefer:
```
num = 5
outof = 52500
formatted = '%*d/%d' % (len(str(outof)), num, outof)
``` | Format a number as a string | [
"",
"python",
"string",
"integer",
"format",
""
] |
I know C,C++,COBOL.
Now I am trying to learn C# and I want to do some hobby projects with C#.
So can you suggest where do I start from.
I searched on google but I want to start from a book which gives me more practice problems for a new comer to .net
Can anybody suggest a great book online which I should really start from? | I have referred several books and this book is great.
You may download it from [Professional C#, Third Edition](http://www.flazx.com/ebook1039.php)
This is also a good book. Didn't read the whole book but i had a look few months back
[Sams Teach youe self C# in 24 hours](http://www.flazx.com/ebook10401.php) | I recommend you to start with basic video tutorials first you can find more than source for videos like [this](http://www.learncsharp.com).
Then after you finish the basic features and main differences you can go in depth
by reading more detailed books like [CLR via C#](http://www.microsoft.com/learning/en/us/Books/6522.aspx) | What is the best way to start C# for a C, COBOL programmer? | [
"",
"c#",
""
] |
For 2 owners the answer is easy - use a slider with one owner on the left, the other on the right, and slide to control the percentage of each.
How do I do it with 3 or more owners?
Specifically I'm talking about Java Swing-based GUI, but am mainly looking for the design idea.
Thanks! | Create a triangle control, where you can move a single point around. If it's in one of the corners it means 100% to that corner. If it's in the middle it means 33% to each. | How about a pie chart where you have one segment per owner and the user can directly manipulate (drag with the mouse) the boundaries between segments or select a segment and type its percentage.
Alternatively you could extend the slider to have more nobs on it, so for splitting between 3 people it'd look like this:
```
|-------O-----O-----------|
``` | I need to represent allocation of 100% of some resource between 3 owners in GUI - any recommendations? | [
"",
"java",
"swing",
"user-interface",
""
] |
I see this kind of thing sometimes:
```
(k for k in (j for j in (i for i in xrange(10))))
```
Now this really bends my brain, and I would rather it wasn't presented in this way.
Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?
**Edit:** Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant. | Check [PEP 202](http://www.python.org/dev/peps/pep-0202/) which was where list comprehensions syntax was introduced to the language.
For understanding your example, there is a simple rule from Guido himself:
* The form [... for x... for y...] nests, with the last index
varying fastest, just like nested for loops.
Also from PEP 202, which serves to answer your question:
```
Rationale
List comprehensions provide a more concise way to create lists in
situations where map() and filter() and/or nested loops would
currently be used.
```
If you had a situation like that, you could find it to be more elegant. IMHO, though, multiple nested list comprehensions may be less clear in your code than nested for loops, since `for` loops are easily parsed visually. | If you're worried about too much complexity on one line, you could split it:
```
(k for k in
(j for j in
(i for i in xrange(10))))
```
I've always found line continuations to look a little weird in Python, but this does make it easier to see what each one is looping over. Since an extra assignment/lookup is not going to make or break anything, you could also write it like this:
```
gen1 = (i for i in xrange(10))
gen2 = (j for j in gen1)
gen3 = (k for k in gen2)
```
In practice, I don't think I've ever nested a comprehension more than 2-deep, and at that point it was still pretty easy to understand. | Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant? | [
"",
"python",
"list-comprehension",
"generator-expression",
""
] |
I'm trying to Mock the IUnityContainer using Moq 3.0
I'm getting a BadImageFormatException, but not when debugging. From the looks of it I'm not the only one that's ran into this problem.
[here](http://www.nabble.com/BadImageFormatException,-but-not-when-debugging-td18742529.html)
And its a registered issue for Moq
[here](http://code.google.com/p/moq/issues/detail?id=87)
I'm just curious if anyone has found a solution... closest I've found is a nice solution that uses RhinoMock by Roy Osherove
[here](http://weblogs.asp.net/rosherove/archive/2008/04/14/creating-a-automockingcontainer-with-microsoft-unity-pretty-darn-simple.aspx)
but I really like Moq! So I don't really want to have to switch to Rhino Mock but I will if I must
Thanks in advance! | You don't.
The only reason to mock the container is if you're passing it around. That's an anti-pattern.
Instead you want to compose the entire object graph at the application's entry point, or [Composition Root](http://blog.ploeh.dk/2011/07/28/CompositionRoot/).
If you need to create instances on the fly, use [Automatic Factories](https://www.devtrends.co.uk/blog/using-unitys-automatic-factories-to-lazy-load-expensive-dependencies).
For your tests, you can either construct the object under test and pass mock objects to the constructor or create a new container in the test and register mock objects with it. | Do you need a full-blown mock object? Could you get by with simply implementing a Fake? I.e., implementing a test instantiation of the IUnityContainer interface and overriding the method that you need to interact with?
I've fallen into the trap more than once in thinking that since I have a mock object library, I should use it for isolating every dependency in my system. More often than not, doing something simpler gets me the results I want with much lower frustration levels. | How do you Mock IUnityContainer? | [
"",
"c#",
"tdd",
"mocking",
"moq",
"unity-container",
""
] |
Does anyone have a "hello world" sample or tutorial for creating an Eclipse plugin fragment?
I have a working host plugin that, for the sake of simplicity, is just this...
```
public void start(BundleContext context) throws Exception {
System.out.println("Hello....");
super.start(context);
plugin = this;
}
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye...");
plugin = null;
super.stop(context);
}
```
Simple enough and works. Now I want to add a fragment to that host, which seems not as simple as creating a plugin host. I just don't see how to create a fragment project and add logic to it. Let's say I just want to do something simple and have the fragment to print a "Hello2" at `start()` and "Goodbye2" at `stop()`. Can someone give me a working example? | 1. *Eclipse* -> *File* -> *New...* -> *Fragment project* -> set the host plugin (which is either in your workspace or in plugins in target platform).
2. Open *Plugin manifest editor* (you can do it by clicking on `build.properties`, `manifest.mf` or `fragment.xml` - if there is no such a file, create it by hand)
3. In tab *Extentions* click *Add..* and add `org.eclipse.ui.startup` and browse class which implements `org.eclipse.ui.IStartup` class.
4. Create this class and implement it. You need to implement method `earlyStartup()` which is entry point to the fragment.
*Note: The lines below are just example. I didn't test it so there might be errors...*
All you need is this (this is project structure / directory structure):
* **Fragment-Project** - root dir
+ /**META-INF**
- **MANIFEST.MF**
+ /**src** (which is source directory)
- **FragmentStartClass.java** (which implement org.eclipse.ui.IStartup interface and earlyStartup method)
+ **build.properties**
+ **fragment.xml**
**META-INF/MANIFEST.MF** content:
```
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: FragmentProject
Bundle-SymbolicName: FragmentProject;singleton:=true
Bundle-Version: 1.0.0
Bundle-ClassPath: src/,.
Fragment-Host: *HostPluginProjectSymbolicName*;bundle-version="1.0.0"
Bundle-RequiredExecutionEnvironment: J2SE-1.5
Require-Bundle:
```
**build.properties** content:
```
source.. = src,\
output.. = bin/
bin.includes = META-INF/,
.,
fragment.xml
```
**fragment.xml** content:
```
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<fragment>
<extension
point="org.eclipse.ui.startup">
<startup
class="FragmentStartClass">
</startup>
</extension>
</fragment>
```
**FragmentStartClass.java** content:
```
import org.eclipse.ui.IStartup;
public class FragmentStartClass implements IStartup {
public void earlyStartup() {
System.out.println("Hello World From Fragment!");
}
}
``` | Well, first off what are you trying to accomplish? Are you sure fragments are the solution?
Fragments are simply additions to an existing plugin. There is no Bundle-Activator to "startup" the fragment. You just gain the additional resources in the fragment. You could use an extension point to inform the host that some particular functionality was extended by a present fragment. Think of it as merging the two at runtime.
See [this note](http://wiki.eclipse.org/FAQ_What_is_a_plug-in_fragment%3F) from the [Eclipse Wiki](http://wiki.eclipse.org). | Eclipse Plugin Fragment | [
"",
"java",
"eclipse",
"plugins",
""
] |
I have a significant codebase written in MFC and am tasked with creating a port for Mac OS X. I know that I'm going to have to roll up my sleeves at some point and do alot of grunt work to get everything working correctly, but are there any tools out there that might get me partway? | I'm working on one.
From the GUI point of view, the new version of [AppMaker](http://www.aussiedesignedsoftware.com/AppMakerX.html) is based around an import/generate model. Most of commercial work I've done with AppMaker has been the other way, porting Macintosh applications to Windows. However, there's no reason why the same principles can't be applied in reverse.
AppMaker v2 had a very good importer for PowerPlant UI resources and traditional Mac dialogs. As it is only able to run on Classic, that code base has been discarded (you really don't want to know) and the final generator languge I wrote for AppMaker v2 is an XML exporter which dumps the entire object model to an extended XAML.
I already have a XAML UI generator and am currently working on a Cocoa xib generator - one of the reasons for going to WWDC in June. The focus at this time is on import/generator suites before returning my attention to a GUI editor.
I wrote [PP2MFC](http://www.oofile.com.au/pp2mfc/crossplatform.html) to allow PowerPlant applications to be compiled for Windows - a cross-platform solution needed because no other framework or cross-platform tool at the time (1997) would perform well enough for the hardware requirements. I've since discussed an opposite program with someone I could chase up and I'm sure an MFC portability layer could be created to map to Cocoa objects. Whilst many developers have a poor opinion of MFC's message-map architecture, the heavily macro-based API sits on top of a reasonably clean OO framework.
This is the kind of project where you need to think about long-term maintainability - do you want something which ends up as large chunks of MFC code working with Cocoa or do you want to migrate to an idiomatic Cocoa program.
Any further discussion should probably be taken off SO - contact me at dent at oofile.com.au but I'm happy to debate technicalities and feasibility on here. The combination of code generation and skinny framework adaptor layers works better than most people expect. | Honestly, the models are so different that I suspect you're going to need to do a nearly complete re-code at least of most of the UI parts. | Is there some sort of tool or helper to port an MFC/C++ app to OS X/Cocoa? | [
"",
"c++",
"macos",
"mfc",
""
] |
I'm writing messages to a Message Queue in C# as follows:
```
queue.Send(new Message("message"));
```
I'm trying to read the messages as follows:
```
Messages messages = queue.GetAllMessages();
foreach(Message m in messages)
{
String message = m.Body;
//do something with string
}
```
However I'm getting an error message which says: "Cannot find a formatter capable of reading this message."
What am I doing wrong? | I solved the problem by adding a formatter to each message. Adding a formatter to the queue didn't work.
```
Messages messages = queue.GetAllMessages();
foreach(Message m in messages)
{
m.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
String message = m.Body;
//do something with string
}
``` | Or you can use
```
message.Formatter =
new System.Messaging.XmlMessageFormatter(new Type[1] { typeof(string) });
``` | Message Queue Error: cannot find a formatter capable of reading message | [
"",
"c#",
"message-queue",
""
] |
```
function Foo(f) {
var f = f;
}
```
Here inside the function, variable `f` is local to the `Foo` (it has a function scope), but why is the variable `f` in the argument list not in conflict? Maybe because it is bound inside the `Foo.arguments` object?
In other languages we cannot declare an argument variable with the same name as a local variable.
How is this name ambiguity resolved? Or, How do you reference each of the two distinct `f` variables later in the method? | JavaScript does a couple of things that aren't obviously intuitive - the one you're interested in is called "hoisting" - JS moves var declarations to the top of a function, where they serve the sole purpose of reserving this variable name as a local variable in the function's scope. Sometimes, this leads to [lots of weirdness](http://calculist.blogspot.com/2005/12/dynamic-scope.html). If the variable name is already reserved as a local variable (e.g. it's an argument) the var declaration gets dropped entirely.
Another unintuitive part of JS is how it deals with argument variables and the `arguments` object (which are a bit special, as Hippo showed). That's not necessarily what you're interested in, though - what's important for your example is that arguments also declare that variable name as local to the function.
The result of all this is that when you have a `var f` as well as an argument name `f`, the `var f' gets dropped, and your example is equivalent to:
```
function Foo(f) {
f = f;
}
```
You can see this in Hippo's example, because:
```
function foo(f) {
console.log(f); // --> 11
console.log(arguments); // --> array [11]
var f = 10;
console.log(f); // --> 10
console.log(arguments); // --> [10] (!!!)
}
```
Is equivalent to:
```
function foo(f) {
var f;
console.log(f); // --> 11
console.log(arguments); // --> array [11]
f = 10;
console.log(f); // --> 10
console.log(arguments); // --> [10] (!!!)
}
```
Is equivalent to:
```
function foo(f) {
console.log(f); // --> 11
console.log(arguments); // --> array [11]
f = 10;
console.log(f); // --> 10
console.log(arguments); // --> [10] (!!!)
}
```
For more details, read up section *10.1.3 - Variable Instantiation* (bottom of p.37) in [ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm), the JS specification. | There is no way to solve this problem, except renaming one of them, or storing the value in another variable.
```
function foo(f) {
console.log(f); // --> 11
console.log(arguments); // --> array [11]
var f=10;
console.log(f); // --> 10
console.log(arguments); //even this is now array [10]
}
foo(11);
``` | function arguments | [
"",
"javascript",
"scope",
""
] |
Architecture ARM9. Programming Language C.
We have a third-party stack and one of the calls takes a pointer(`pBuffer`) to a memory location. Within the stack, they are free to move around the pointer passed and access it as they wish. Unfortunately, they offset the passed in pointer and passed it into a another function that tried to do this from an **odd/unalighed** memory location
```
((uint16 *)pBuffer)[index] = value;
```
where `value` is of type `uint16` and `index` is bounds checked and indexes `pBuffer`. This causes a unaligned memory access exception. `pBuffer` points to `char *` on the heap.
As mentioned, even though we can peek into the third-party stack, we can not update the code officially. So we notify the provider and they provide the update in the next release.
I want to understand if there is a work around for this. How do I perform the above assignment without violating the unaligned access? What is the best approach to resolving such problems. | Copy the value byte by byte. Cast it to a (unsigned) char pointer, and then copy a byte at a time.
It's not pretty, but it doesn't sound like you have many options. | There are three possibilities, and I cannot determine from your question so far which is the case.
Case 1: The index is always odd. Solution: memmove() pBuffer over 1 bytes
Case 2: The index is sometimes odd, and you can predict up front when it will be. Solution: memmove() pBuffer over 1 byte when you know index will be odd.
Case 3: The index is sometimes odd, and you cannot predict when it will be. This is unfortunate, because the code *will* fault. | What is the workaround for unaligned memory access exception on ARM9 using C? | [
"",
"c++",
"c",
"embedded",
"arm",
""
] |
Im working with file systems and I have a List<> of file objects that have the file path as a property. Basically I need to create a treeview in .NET but im struggling to think of the best way to go about doing this as I need to create a tree structure from a list like:
```
C:/WINDOWS/Temp/ErrorLog.txt
C:/Program Files/FileZilla/GPL.html
C:/Documents and Settings/Administrator/ntuser.dat.LOG
```
etc....
The list is not structured at all and I cant make any changes to the current object structure.
I'm working in C#.
Many thanks for all who contribute | If you wanted to stick with the strings something like this would work...
```
TreeNode root = new TreeNode();
TreeNode node = root;
treeView1.Nodes.Add(root);
foreach (string filePath in myList) // myList is your list of paths
{
node = root;
foreach (string pathBits in filePath.Split('/'))
{
node = AddNode(node, pathBits);
}
}
private TreeNode AddNode(TreeNode node, string key)
{
if (node.Nodes.ContainsKey(key))
{
return node.Nodes[key];
}
else
{
return node.Nodes.Add(key, key);
}
}
``` | I would turn the string into a FileInfo.
Once you have the [FileInfo](http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx) object, you can use the Directory property to retrieve the [DirectoryInfo](http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx) for each path.
Once you have the DirectoryInfo for the path, it's easy to "walk up" the Parent reference in DirectoryInfo to turn each path into a list of directories + filename - ie:
```
{"C:","Windows","Temp","ErrorLog.txt"}
```
This should be fairly straightforward to insert into your treeview. Just look for each section of the path in turn, and if it doesn't exist, add it.... | File System TreeView | [
"",
"c#",
"file",
"treeview",
"path",
"system",
""
] |
I wish to create a background process and I have been told these are usually written in C or something of that sort. I have recently found out PHP can be used to create a daemon and I was hoping to get some advice if I should make use of PHP in this way.
Here are my requirements for a daemon.
* Continuously check if a row has been
added to MySQL database table
* Run FFmpeg commands on what was
retrieved from database
* Insert output into MySQL table
I am not sure what else I can offer to help make this decision. Just to add, I have not done C before. Only Java and PHP and basic bash scripting.
Does it even make that much of a performance difference?
Please allow for my ignorance, I am learning! :)
Thanks all | As others have noted, various versions of PHP have issues with their garbage collectors. Of course, if you know that your version does not have such issues, you eliminate that problem. The point is, you **don't** know (for sure) until you write the daemon and run it through valgrind to see if the installed PHP leaks or not on any given machine. So on that hand, you may write it just to discover that what Zend thinks is fixed might still be buggy, or you are dealing with a slightly older version of PHP or some extension. Icky.
The other problem is somewhat buggy signals. In my experience, signal handlers are not always entered correctly with PHP, especially when the signal is queued instead of merged. That may not be an issue for you, i.e. if you just need to handle SIGINT/SIGUSR1/SIGUSR2/SIGHUP.
So, I suggest:
If the daemon is simple, go ahead and use PHP. If it looks like its going to get rather complex, or allocate lots of memory, you might consider writing it in C after prototyping it in PHP.
I am a pretty die hard C person. However, I see nothing wrong with hammering out something quick using PHP (beyond the cases that I explained). I also see nothing wrong with using PHP to prototype something that may or may not be later rewritten in C. For instance, handling database stuff is going to be much simpler if you use PHP, versus managing callbacks using other interfaces in C. So in that instance, for a 'one off', you will surely get it done much faster. | I would be inclined to perform this task with a cron job, rather than polling the database in a daemon.
It's likely that your FFmpeg command will take a while to do it's thing, right? In that case, is it *really* necessary to be constantly polling the database? Wouldn't a cronjob running each minute (or every five, ten or twenty minutes for that matter) be a simpler way to achieve the same thing? | Is it wise to use PHP for a daemon? | [
"",
"php",
"c",
"linux",
"daemon",
""
] |
Is there a way to print out a function's parameter list?
For example:
```
def func(a, b, c):
pass
print_func_parametes(func)
```
Which will produce something like:
```
["a", "b", "c"]
``` | Use the inspect module.
```
>>> import inspect
>>> inspect.getargspec(func)
(['a', 'b', 'c'], None, None, None)
```
The first part of returned tuple is what you're looking for. | Read the source. Seriously. Python programs and libraries are provided as source. You can read the source. | Print out list of function parameters in Python | [
"",
"python",
""
] |
I have a JTree implementation for directories in the file system. The problem I have is that when a directory is removed or renamed, the tree still shows the directory in it's parent. The parent tree seems not to be updated for any changes once a node has been expanded.
The model I have written does not cache (I have commented out what limited caching it did have) - it's like the JTree itself has cached the node.
The code (the model is a nested subclass):
```
public class FileSystemTree
extends JTree
{
// *****************************************************************************
// INSTANCE CREATE/DELETE
// *****************************************************************************
public FileSystemTree() {
this(new Model(null,null,null));
}
public FileSystemTree(String startPath) {
this(new Model(startPath,null,null));
}
public FileSystemTree(FileSelector inc, FileSelector exc) {
this(new Model(null,inc,exc));
}
public FileSystemTree(String startPath, FileSelector inc, FileSelector exc) {
this(new Model(startPath,inc,exc));
}
private FileSystemTree(Model model) {
super(model);
//setLargeModel(true);
setRootVisible(false);
setShowsRootHandles(true);
putClientProperty("JTree.lineStyle","Angled");
}
// *****************************************************************************
// INSTANCE METHODS - ACCESSORS
// *****************************************************************************
public Object getRoot() {
return getModel().getRoot();
}
// *****************************************************************************
// INSTANCE METHODS
// *****************************************************************************
public String convertValueToText(Object value,boolean selected,boolean expanded,boolean leaf,int row,boolean hasFocus) {
File fil=(File)value;
return (fil.getName().length()!=0 ? fil.getName() : fil.getPath());
}
// *****************************************************************************
// STATIC NESTED CLASSES - SUPPORTING MODEL
// *****************************************************************************
static class Model
extends Object
implements TreeModel, FilenameFilter
{
private File root; // tree root
//ivate Map cache; // caches child counts for directories
private File[] fsRoots; // copy of file system roots
private FileSelector include; // inclusion selector
private FileSelector exclude; // exclusion selector
private java.util.List listeners=new ArrayList();
public Model(String roo, FileSelector inc, FileSelector exc) {
super();
root=(roo==null ? DRIVES : new File(roo));
//cache=new HashMap();
fsRoots=(root==DRIVES ? rootList() : null);
include=inc;
exclude=exc;
}
// *****************************************************************************
// METHODS - MODEL
// *****************************************************************************
public Object getRoot() {
return root;
}
public Object getChild(Object parent, int index) {
File dir=(File)parent;
if(dir==DRIVES) {
File[] chl=fsRoots; //rootList();
return (index<chl.length ? chl[index] : null);
}
else {
String[] chl=dirList(dir);
return (index<chl.length ? new File(dir,chl[index]) : null);
}
}
public int getChildCount(Object parent) {
File dir=(File)parent;
//Integer cch=(Integer)cache.get(dir);
//if(cch!=null) {
// return cch.intValue();
// }
if(dir==DRIVES) {
return fsRoots.length; //rootList().length;
}
else if(dir.isDirectory()) {
return dirList(dir).length;
}
else {
return 0;
}
}
public boolean isLeaf(Object node) {
return((File)node).isFile();
}
public void valueForPathChanged(TreePath path, Object newValue) {
}
public int getIndexOfChild(Object parent, Object child) {
File dir=(File)parent;
File fse=(File)child;
if(dir==DRIVES) {
File[] ca=fsRoots; //rootList();
for(int xa=0; xa<ca.length; xa++) {
if(fse.equals(ca[xa])) { return xa; }
}
}
else {
String[] ca=dirList(dir);
for(int xa=0; xa<ca.length; ++xa) {
if(fse.getName().equals(ca[xa])) { return xa; }
}
}
return -1;
}
private File[] rootList() {
File[] lst=File.listRoots();
if(lst==null) { lst=new File[0]; }
//cache.put(DRIVES,new Integer(lst.length));
return lst;
}
private String[] dirList(File dir) {
String[] lst=dir.list(this);
if(lst==null) { lst=new String[0]; }
//cache.put(dir,new Integer(lst.length));
return lst;
}
// *****************************************************************************
// METHODS - FILENAME FILTER
// *****************************************************************************
public boolean accept(File dir, String nam) {
return ((include==null || include.accept(dir,nam)) && (exclude==null || !exclude.accept(dir,nam)));
}
// *****************************************************************************
// METHODS - LISTENER
// *****************************************************************************
public void addTreeModelListener(TreeModelListener listener) {
if(listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
}
public void removeTreeModelListener(TreeModelListener listener) {
if(listener != null) {
listeners.remove(listener);
}
}
public void fireTreeNodesChanged(TreeModelEvent evt) {
Iterator itr=listeners.iterator();
while(itr.hasNext()) {
TreeModelListener listener=(TreeModelListener)itr.next();
listener.treeNodesChanged(evt);
}
}
public void fireTreeNodesInserted(TreeModelEvent evt) {
Iterator itr=listeners.iterator();
while(itr.hasNext()) {
TreeModelListener listener=(TreeModelListener)itr.next();
listener.treeNodesInserted(evt);
}
}
public void fireTreeNodesRemoved(TreeModelEvent evt) {
Iterator itr=listeners.iterator();
while(itr.hasNext()) {
TreeModelListener listener=(TreeModelListener)itr.next();
listener.treeNodesRemoved(evt);
}
}
public void fireTreeStructureChanged(TreeModelEvent evt) {
Iterator itr=listeners.iterator();
while(itr.hasNext()) {
TreeModelListener listener=(TreeModelListener)itr.next();
listener.treeStructureChanged(evt);
}
}
} // END INNER CLASS
// *****************************************************************************
// STATIC PROPERTIES
// *****************************************************************************
static private final File DRIVES=new File("*DRIVES"); // marker for listing file system drives
} // END PUBLIC CLASS
``` | The model is responsible for notifying the listeners of any modification in the tree structure. The tree will not refresh itself in absence of such a notification. | You could write some background thread that looks for changes in the filesystem and fire some model modification events if you detect that the directories have changed. | Can I stop JTree caching nodes (in a file system tree)? | [
"",
"java",
"filesystems",
"jtree",
""
] |
I have been using JDOM library to read and write XML files through Java Servlets.
Problem is that when I send many requests using AJAX to my servlets which read and write data in XML files, many times it fails displaying error: Premature end of file. How can I synchronize all these read/writes to files or is there any other way to prevent these problem? Let me know if more details are required.
Will use of threads do any good in this situation?
Thanks a lot! | Two possible solutions are:
* Write your files to thename.xml.part and then once done/closed to a rename to thename.xml, which makes the write closer to being atomic -- the reader can't read it until it's surely done so long as it is looking for ".xml" files only.
* or, use a Database, atomicity is what they do. | I have faced such type of problem but exactly not the same. I am sharing my experience about this error. Please, sorry for any inconvenience.
**I have faced the following problem**
1. I have to form a xml file with dynamic variable data. And post that xml to a URL by PostMethod in java.
2. Normally It works. But when dynamic variable data is null. Then it shows the “Premature end of file".
**Solution:**
1. Just checking the variable is null or not. And it works for me. | "Premature end of file" error when Java read and writes XML data files | [
"",
"java",
"xml",
"servlets",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.