Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm new to the Entities Framework, and am just starting to play around with it in my free time. One of the major questions I have is regarding how to handle ObjectContexts.
Which is generally preferred/recommended of these:
**This**
```
public class DataAccess{
MyDbContext m_Context;
public DataAccess(){
m_Context = new MyDbContext();
}
public IEnumerable<SomeItem> GetSomeItems(){
return m_Context.SomeItems;
}
public void DeleteSomeItem(SomeItem item){
m_Context.DeleteObject(item);
m_Context.SaveChanges();
}
}
```
**Or this?**
```
public class DataAccess{
public DataAccess(){ }
public IEnumerable<SomeItem> GetSomeItems(){
MyDbContext context = new DbContext();
return context.SomeItems;
}
public void DeleteSomeItem(SomeItem item){
MyDbContext context = new DbContext();
context.DeleteObject(item);
context.SaveChanges();
}
}
``` | The ObjectContext is meant to be the "Unit of Work".
Essentially what this means is that for each "Operation" (eg: each web-page request) there should be a new ObjectContext instance. Within that operation, the same ObjectContext should be re-used.
This makes sense when you think about it, as transactions and change submission are all tied to the ObjectContext instance.
If you're not writing a web-app, and are instead writing a WPF or windows forms application, it gets a bit more complex, as you don't have the tight "request" scope that a web-page-load gives you, but you get the idea.
PS: In either of your examples, the lifetime of the ObjectContext will either be global, or transient. In both situations, it should NOT live inside the DataAccess class - it should be passed in as a dependency | If you keep the same context for a **long-running** process running **lots queries** against it, linq-to-sql (I didn't test against linq to entities, but I guess that's the same problem) gets VERY slow (1 query a second after some 1000 simple queries). Renewing the context on a regular basis fixes this issue, and doesn't cost so much.
What happens is that the context keeps track of every query you do on it, so if it's not reset in a way, it gets really fat... Other issue is then the memory it takes.
So it mainly depends on the way your application is working, and if you new up a DataAccess instance regularly or if you keep it the same all along.
Hope this helps.
Stéphane | Reuseable ObjectContext or new ObjectContext for each set of operations? | [
"",
"c#",
"linq-to-entities",
"data-access-layer",
"objectcontext",
""
] |
I have the following table lookup table in OLTP
```
CREATE TABLE TransactionState
(
TransactionStateId INT IDENTITY (1, 1) NOT NULL,
TransactionStateName VarChar (100)
)
```
When this comes into my OLAP, I change the structure as follows:
```
CREATE TABLE TransactionState
(
TransactionStateId INT NOT NULL, /* not an IDENTITY column in OLAP */
TransactionStateName VarChar (100) NOT NULL,
StartDateTime DateTime NOT NULL,
EndDateTime NULL
)
```
My question is regarding the TransactionStateId column. Over time, I may have duplicate TransactionStateId values in my OLAP, but with the combination of StartDateTime and EndDateTime, they would be unique.
I have seen samples of Type-2 Dimensions where an OriginalTransactionStateId is added and the incoming TransactionStateId is mapped to it, plus a new TransactionStateId IDENTITY field becomes the PK and is used for the joins.
```
CREATE TABLE TransactionState
(
TransactionStateId INT IDENTITY (1, 1) NOT NULL,
OriginalTransactionStateId INT NOT NULL, /* not an IDENTITY column in OLAP */
TransactionStateName VarChar (100) NOT NULL,
StartDateTime DateTime NOT NULL,
EndDateTime NULL
)
```
Should I go with bachellorete #2 or bachellorete #3? | By this phrase:
> With the combination of `StartDateTime` and `EndDateTime`, they would be unique.
you mean that they never overlap or that they satisfy the database `UNIQUE` constraint?
If the former, then you can use the `StartDateTime` in joins, but note that it may be inefficient, since it will use a `"<="` condition instead of `"="`.
If the latter, then just use a fake identity.
Databases in general do not allow an efficient algorithm for this query:
```
SELECT *
FROM TransactionState
WHERE @value BETWEEN StartDateTime AND EndDateTime
```
, unless you do arcane tricks with `SPATIAL` data.
That's why you'll have to use this condition in a `JOIN`:
```
SELECT *
FROM factTable
CROSS APPLY
(
SELECT TOP 1 *
FROM TransactionState
WHERE StartDateTime <= factDateTime
ORDER BY
StartDateTime DESC
)
```
, which will deprive the optimizer of possibility to use `HASH JOIN`, which is most efficient for such queries in many cases.
See this article for more details on this approach:
* [**Converting currencies**](http://explainextended.com/2009/05/27/converting-currencies/)
Rewriting the query so that it can use `HASH JOIN` resulted in `600%` times performance gain, though it's only possible if your datetimes have accuracy of a day or lower (or a hash table will grow very large).
Since your time component is stripped of your `StartDateTime` and `EndDateTime`, you can create a `CTE` like this:
```
WITH cal AS
(
SELECT CAST('2009-01-01' AS DATE) AS cdate
UNION ALL
SELECT DATEADD(day, 1, cdate)
FROM cal
WHERE cdate <= '2009-03-01'
),
state AS
(
SELECT cdate, ts.*
FROM cal
CROSS APPLY
(
SELECT TOP 1 *
FROM TransactionState
WHERE StartDateTime <= cdate
ORDER BY
StartDateTime DESC
) ts
WHERE ts.EndDateTime >= cdate
)
SELECT *
FROM factTable
JOIN state
ON cdate = DATE(factDate)
```
If your date ranges span more than `100` dates, adjust `MAXRECURSION` option on `CTE`. | Please be aware that `IDENTITY(1,1)` is a declaration for auto-generating values in that column. This is different than `PRIMARY KEY`, which is a declaration that makes a column into a primary key clustered index. These two declarations mean different things and there are performance implications if you don't say `PRIMARY KEY`. | Type II dimension joins | [
"",
"sql",
"sql-server",
"data-warehouse",
"dimensions",
"type-2-dimension",
""
] |
I have some c++ code I'm using for testing in which the first line is a call to dlopen in an attempt to load my shared object. Upon hitting this line I get the following error:
```
Terminate called after throwing an instance of std::bad_alloc:
what() : St9bad_alloc
```
I've upped the memory (free -m now reports that I have ~120 MB free when my exe is loaded in gdb) and I still get the same message.
Anyone any ideas on what else could be causing this & what I can do to resolve it? | Take a look at the [C++ dlopen mini HOWTO](http://tldp.org/HOWTO/C++-dlopen/), hope that helps. | My guess is that dlopen has nothing to do with it. dlopen() is a C language function and it can't throw an exception. What can actually throw it is initialization functions in your shared objects, for example, the expressions you assign to your static objects. For example, if you write this in the shared object you're loading, it might crash with bad\_alloc:
```
// dso.cpp start
#include <dso.h>
Object* instance = new Object();
// the rest of the file
```
But dlopen stuff is totally irrelevant, I suppose. | Error on dlopen: St9bad_alloc | [
"",
"c++",
"dlopen",
"shared-objects",
""
] |
how can I specify a blacklist for a CharField. However I want the blacklist to be effective in the Django admin panel aswell...otherwise I would just validate it in the view.
By blacklist I mean values that can't be used. I also set unique for the value but I would like to disable a few strings aswell.
Thanks,
Max | I would override the model's save() method and the to be inserted value against a blacklist before calling the parent class' save() method.
Something like that (simplified):
```
class BlackListModel(models.Model):
blacklist = ['a', 'b', 'c']
# your model fields definitions...
def save(self, *args, **kwargs):
if self.blacklist_field in self.blacklist:
raise Exception("Attempting to save a blacklisted value!")
return super(BlackListModel, self).save(*args, **kwargs)
```
That way it works in all of your applications. | Since we're a few years later, you should write a custom blacklist validator:
```
from django.db import models
from django.core.exceptions import ValidationError
def validate_blacklist(value):
if value in ['a', 'b', 'c']:
raise ValidationError(
"'a', 'b' and 'c' are prohibited!",
params={'value': value},
)
class MyModel(models.Model):
even_field = models.CharField(max_length=200, validators=[validate_even])
```
See: [Django Validators](https://docs.djangoproject.com/en/dev/ref/validators/) for full documentation. | Django CharField limitations | [
"",
"python",
"django",
""
] |
I'm very poor with regexps but this should be very simple for someone who knows regexps.
Basically I will have a string like this:
```
<if>abc <else>xyz
```
I would like a regexp so if the string contains `<if> <else>`, it splits the string into two parts and returns the two strings after `<if>` and `<else>`. In the above example it might return an array with the first element being `abc`, second `xyz`. I'm open to approaches not using regexps too.
Any thoughts? | ```
// $subject is you variable containing string you want to run regex on
$result = preg_match('/<if>(.*)<else>(.*)/i', $subject, $matches);
// $matches[0] has the full matched text
// $matches[1] has if part
// $matches[2] has else part
```
The `/i` at the end makes the search case sensitive to allow both `<if><else>` and `<IF> <elSE>` | Regular Expressions will work for this in simple cases. For more complicated cases (where nesting occurs), you may find it easier to parse the string and use a simple stack to grab the data you need. | Splitting a string containing <if> <else> with regexps | [
"",
"php",
"regex",
"string",
""
] |
```
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Python 2.5.2 (r252:60911, Aug 8 2009, 17:18:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> import operator
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named operator
``` | Module `operator` should come from file `operator.so`, presumably in `/usr/local/lib/lib-dynload` in your case since that seems to be where you've installed things. So what .so files are in that directory?
Assuming operator.so is indeed missing (i.e., assuming it's not some trivial case of wrong permissions on some directory or file) the best way to "get it back" is no doubt, as a comment already suggested, to reinstall Python 2.5 (assuming you need that release e.g. to work with app engine) from either an official Python package at python.org, or an official CentOS 5.3 one (if one exists -- I believe CentOS 5.3 uses Python 2.4 as the official /usr/bin/python but there may be RPMs to place 2.5 somewhere else). | I renamed the /usr/local/bin/python file and the error went away.
I suspect this was an old version of python because I have a file python2.7 in the same directory. | python2.5 says platform dependent libraries not found | [
"",
"python",
"configuration",
""
] |
**Edit:** I've edited the sample to better resemble the problem I have, now the function depends on a regular parameter (and not only on template parameters) which means that the computations **can't** be made at compile time.
---
I wrote some code with a hand written [typelist](http://www.ddj.com/cpp/184403813) and now we've started using [boost](http://www.boost.org) and I'm trying to move it to the `mpl` library.
I can't seem to find any decent documentation for `mpl::list` and I'm even failing to port the code to `boost::mpl`. I've got the feeling that even when (if?) I do succeed in porting the code it will still not be idiomatic. Can' you please let me know how the following should be written with `boost` (note that this is not the actual code, it's a contrived simplification).
**Original code** [(codepad.org paste)](http://codepad.org/0unH4XxA)
```
class nil {};
template <class Head, class Tail = nil>
struct type_list {
typedef Head head;
typedef Tail tail;
};
template <class List>
struct foo;
template <class Head, class Tail>
struct foo<type_list<Head, Tail> >{
template <class T>
static void* bar(T* obj, size_t size)
{
if (sizeof(Head) == size)
return reinterpret_cast<Head*>(obj);
// Otherwise check the rest of the list
return foo<Tail>::bar(obj, size);
}
};
template <>
struct foo<nil>
{
template <class T>
static void* bar(T*, size_t) { return NULL; }
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<type_list<char, type_list<bool,
type_list<double, type_list<long> > > >
>::bar(&n, 4);
std::cout<< p << std::endl;
}
```
**Failed Attempt to use Boost** [(codepad.org paste)](http://codepad.org/rXj1Aq2u)
```
#include <boost/mpl/list.hpp>
template <class List>
struct foo{
template <class T>
static void* bar(T* obj, size_t size)
{
typedef typename boost::mpl::front<List>::type type;
if (sizeof(type) == size)
return reinterpret_cast<type*>(obj);
// Otherwise check the rest of the list
return foo<typename List::next>::bar(obj, size);
}
};
template <>
struct foo<boost::mpl::list0<boost::mpl::na> >
{
template <class T>
static void* bar(T*)
{
return NULL;
}
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<boost::mpl::list<char, bool, double, long> >::bar(&n, 4);
std::cout << p << std::endl;
}
``` | Use [`boost::mpl::fold`](http://www.boost.org/doc/libs/1_39_0/libs/mpl/doc/refmanual/fold.html) like this:
```
#include <boost/mpl/list.hpp>
#include <boost/mpl/fold.hpp>
#include <iostream>
using namespace boost::mpl;
// Initial state:
struct foo_start {
template <typename T>
static void * bar( T *, size_t ) { return 0; }
};
// Folding Step: add This to Prev
template <typename Prev, typename This>
struct foo_iteration {
struct type {
template <typename T>
static void * bar( T * obj, size_t size ) {
if ( sizeof(This) == size )
return reinterpret_cast<This*>(obj);
else
return Prev::bar( obj, size );
}
};
};
// foo is just calling mpl::fold now:
template <typename List>
struct foo : fold< List, foo_start, foo_iteration<_,_> >::type {};
int main() {
int n = 3;
void * p = foo< list<char, bool, double, long> >::bar( &n, 4 );
std::cout << p << std::endl;
}
```
Prints `0` here, but then I'm on amd64, so I need to change the `4` to an `8`, and get something non-zero.
HTH | The MPL is ill-suited for mixed compile-time / run-time operations.
The only operation allowed at runtime on MPL sequences is 'for\_each'. For all other situations you should roll your own.
So you should effectively consider that MPL types are not meant to be instanciated.
However, there are other facilities in Boost for such a thing.
The old: Boost.Tuple
The new: Boost.Fusion > <http://spirit.sourceforge.net/dl_more/fusion_v2/libs/fusion/doc/html/index.html>
Boost.Fusion is a bit more complex (it integrates the concept of views, for example), but would be far better suited to your example.
It does not mean that you should not use the MPL. On the contrary, it is explicitly stated in the Boost.Fusion reference document that one should use MPL algorithms for compile-time computations, and then build the Boost.Fusion container only at the moment you cross the compile-time / runtime boundary (even though Boost.Fusion container are supposed to work with MPL algorithms).
So, keep your mpl implementation transform the resulting list to a Boost.Fusion sequence.
Then instantiate the sequence and make use of all the Boost.Fusion facilities. | What's the idiomatic way to traverse a boost::mpl::list? | [
"",
"c++",
"boost",
"metaprogramming",
"boost-mpl",
""
] |
I have installed wampserver on my pc. I unzipped the cake php installation files in the "www" folder of wampserver. Now, when I try to run- "<http://localhost/cakephp>", I get a whole list of errors along with the cake php getting started page. Here are some of the errors:
```
Deprecated: Assigning the return value of new by reference is deprecated in
D:\wamp\www\cakephp\cake\libs\inflector.php on line 131
Deprecated: Assigning the return value of new by reference is deprecated in
D:\wamp\www\cakephp\cake\libs\configure.php on line 136
Deprecated: Assigning the return value of new by reference is deprecated in
D:\wamp\www\cakephp\cake\libs\configure.php on line 226
Deprecated: Assigning the return value of new by reference is deprecated in
D:\wamp\www\cakephp\cake\libs\configure.php on line 906
```
How do I fix this? I got similar errors for codeignite. | Which version of PHP are you running ?
To get E\_DEPRECATED errors, it must be PHP 5.3 (which is quite recent) -- and I think the last version of WampServer uses this one.
See :
* [Predefined Constants](http://php.net/manual/en/errorfunc.constants.php)
* [PHP 5.3.0 Release Announcement](http://fr3.php.net/releases/5_3_0.php)
As it's pretty recent and brought lots of new stuff, you might run into some kind of troubels (you actually did) with PHP 5.3.... Especially if the software you used is not compatible with it yet.
You might want to downgrade to the previous version of WampServer...
Or you could try lowering the [error\_reporting](http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) level (see also [`error_reporting`](http://php.net/manual/en/function.error-reporting.php)), to not get those warnings.
But if you are getting those, you'll probably run into other problems as well...
Actually, after a rapid search into CakePHP's Trac, I found at least those :
* [Ticket #6026 : php 5.3 needs `error_reporting(E_ALL & ~E_DEPRECATED);`](https://trac.cakephp.org/ticket/6026)
* [Ticket #6500 : PHP 5.3 incompatibility](https://trac.cakephp.org/ticket/6500)
None of those is solved... So it seems CakePHP is really not ready for PHP 5.3... *(It's probably not the only Framework in this situation btw -- Zend Framework v 1.9 which went out couple of days ago is the first version that officially supports PHP 5.3, for instance)*
If you want to work with CakePHP, so, you'll probably have to use PHP 5.2.x (like 5.2.9 or 5.2.10).
You're actually [not the only one](http://www.google.fr/search?hl=fr&client=firefox-a&rls=com.ubuntu%3Aen-US%3Aunofficial&hs=C7I&q=cakephp+%22php+5.3%22&btnG=Rechercher&meta=) in your situation, it seems... Too bad, as there are pretty nice things in PHP 5.3... | I am also having the same problem.....I downgraded wamp5 2 to wamp 1.6.0...Now its working perfect | Problem installing cake php | [
"",
"php",
"cakephp",
""
] |
I suppose this is more of a public rant, but why can't I get c# to infer my Id's type?
```
public EntityT Get<EntityT>(IdT id) where EntityT : EntityObject<IdT>
```
and a defined EntityObject with a Guid as an Id as follows:
```
public Foo : EntityObject<Guid>
```
Inheriting from the abstract EntityObject class defined as follows:
```
public abstract class EntityObject<IdT>
{
public IdT id { get; set; }
}
```
Usage of the get method would be as follows:
```
IRepository repository = new Repository();
var hydratedFoo = repository.Get<Foo>(someGuidId);
```
*edited to provide further clarification.* | It's hard to say given that you've only given two declarations, not how you're using them. Is IdT another type parameter somewhere? (If it were `TId`, that would suggest it is - but the fact that you're using `EntityT` for another type parameter, contrary to conventions, suggests that maybe `IdT` is as well...)
Now, assuming `IdT` is actually `Guid` in your case, how should the compiler work out that you mean `Foo`? There could be other types deriving from `EntityObject<Guid>`.
In short, you haven't given us enough information to tell anything for sure, but it sounds like you're basically making unreasonable demands on the compiler.
EDIT: Okay, here's my guess at what you have, using normal naming conventions:
```
public interface IRepository
{
TEntity Get<TEntity, TId>(TId id) where TEntity : EntityObject<TId>
}
public abstract class EntityObject<TId>
{
public IdT id { get; set; }
}
public class Foo : EntityObject<Guid> {}
```
You want to do:
```
IRepository repository = GetRepositoryFromSomewhere();
Foo foo = repository.Get<Foo>(someGuid);
```
Whereas currently you have to do:
```
Foo foo = repository.Get<Foo, Guid>(someGuid);
```
Yes, the compiler is making it *very slightly* harder for you than necessary. A whole 6 extra characters, for the sake of keeping the language simpler and the rules of type inference easier to understand.
Basically type inference is an all or nothing affair - either *all* type parameters are inferred or none of them is. That keeps it simple as you don't need to work out which ones are being specified and which aren't. That's part of the problem, and the other part is that you can only express constraints on the type parameters of the method - you can't have:
```
class Repository<TEntity>
{
TEntity Get<TId>(TId id) where TEntity : EntityObject<TId>
}
```
because that's constraining `TEntity`, not `TId`. Again, this sort of thing makes type inference simpler.
Now you *could* potentially write:
```
Foo foo = repository.Get(someGuid).For<Foo>();
```
with an appropriate `Get` method and an extra interface. I think I'd personally prefer to just use `Get<Foo, Guid>` though. | If your method signature looked like this:
```
public TEntity Get<TEntity, TId>(TId id) where TEntity : EntityObject<TId>
```
The compiler would have something to work with...
You then call get with something like:
EDIT (I was wrong): Product p = Get(id);
```
Product p = Get<Product, Guid>(id);
```
Jon's nailed this answer with his post up top so I'll shut up and crawl back in my hole. | Inference from Generic Type Question | [
"",
"c#",
"generics",
"types",
"inference",
""
] |
Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python? | I would recommend using the [FFTW](http://www.fftw.org) library ("the fastest Fourier transform in the West"). The [FFTW download page](http://www.fftw.org/download.html) states that Python wrappers exist, but the link is broken. A Google search turned up [Python FFTW](http://developer.berlios.de/projects/pyfftw/), which provides Python bindings to FFTW3. | I would recommend numpy library, I not sure if it's the fastest implementation that exist but but surely it's one of best scientific module on the "market". | What is the recommended Python module for fast Fourier transforms (FFT)? | [
"",
"python",
"benchmarking",
"fft",
""
] |
Aside from the framework, is jQuery worth using rather than creating your own javascript? I've always debated if the framework was better to use than to create your own calls. Are their disadvantages of using it?
Sorry for beginner question, I'm trying to feel out if it would be better to use this and create some of the ajaxish workings of my site rather than develop it from scratch.
Are there other frameworks out there that would be better to use to create an ajaxish website? | Yes, jQuery is worth it. I speak as someone who resisted using any library for a long time, then finally saw the light.
I do recommend that you build some hand-rolled Ajax interactions before you dive into using jQuery for Ajax, so that you understand exactly what is happening with Ajax. Once that's achieved, though, let the library do the dirty work. | jQuery (and most other framework) are for making difficult things simple. It keeps you from having to write cross-browser compatabile code. It keeps you from having to write recursive methods to update multiple dom-elements. It basically cuts your development time down substantially, and saves you a lot of frustration.
**Stackoverflow Archive:**
* [Which Javascript framework (jQuery vs Dojo vs … )?](https://stackoverflow.com/questions/394601/which-javascript-framework-jquery-vs-dojo-vs)
Great discussion (with lots of involvement) over various javascript frameworks. It will benefit you to browse this in depth, or even at a cursory level.
* [When should I use a javascript framework library?](https://stackoverflow.com/questions/863603/when-should-i-use-a-javascript-framework-library)
* [Which Javascript Framework is the simplest and most powerful?](https://stackoverflow.com/questions/139723/which-javascript-framework-is-the-simplest-and-most-powerful)
* [What JavaScript library would you choose for a new project and why?](https://stackoverflow.com/questions/913/what-javascript-library-would-you-choose-for-a-new-project-and-why)
* [Which Javascript Ajax Framework is most powerful and very lightweight?](https://stackoverflow.com/questions/217781/which-javascript-ajax-framework-is-most-powerful-and-very-lightweight)
* [Which javascript framework can be used for all browsers?](https://stackoverflow.com/questions/1108441/javascript-framework) | Is it worth it to use jQuery for Ajax instead of building your own JavaScript? | [
"",
"javascript",
"jquery",
"ajax",
""
] |
What does `nonlocal` do in Python 3.x?
---
To close debugging questions where OP needs `nonlocal` and doesn't realize it, please use [Is it possible to modify variable in python that is in outer, but not global, scope?](https://stackoverflow.com/questions/8447947) instead.
Although Python 2 is [officially unsupported as of January 1, 2020](https://www.python.org/doc/sunset-python-2/), if for some reason you are forced to maintain a Python 2.x codebase and need an equivalent to `nonlocal`, see [nonlocal keyword in Python 2.x](https://stackoverflow.com/questions/3190706). | Compare this, without using `nonlocal`:
```
x = 0
def outer():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 1
# global: 0
```
To this, using **`nonlocal`**, where `inner()`'s `x` is now also `outer()`'s `x`:
```
x = 0
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 2
# global: 0
```
If we were to use **`global`**, it would bind `x` to the properly "global" value:
```
x = 0
def outer():
x = 1
def inner():
global x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 1
# global: 2
``` | In short, it lets you assign values to a variable in an outer (but non-global) scope. See [PEP 3104](http://www.python.org/dev/peps/pep-3104/) for all the gory details. | What does "nonlocal" do in Python 3? | [
"",
"python",
"closures",
"global",
"nested-function",
"python-nonlocal",
""
] |
As a Java newbie I'm wondering: of all the languages in the world, why is Java frequently used for enterprise applications? What makes it that way compared to the other languages? Will it continue to be this way in the upcoming years?
I'd appreciate your insights. Thanks in advance :) | One word: libraries. Java has an vast array of excellent libraries for solving most of the common problems one needs to solve when developing enterprise applications. In many cases, there is more than one good choice for addressing a particular need, and oftentimes those libraries are free and open source under a business-friendly license.
Some have argued that there are, in fact, too many choices in the Java ecosystem, and that developing enterprise software in Java requires developers to make a large number of decisions that can have far-reaching impact on the end product for better or worse. This has probably helped propel the popularity of alternatives like .NET, which has a reputation of offering fewer choices, but with the benefits of a more well-integrated application stack and tools set. What direction you choose depends, I guess, on whether you place more value on "freedom of choice" or "freedom from choice". | There are lots of reasons a large company (the type to go for enterprise solutions) would pick Java. Note I'm not saying all these reasons are correct or valid. But the relevant point is that they appear valid to a CTO at MegaCorp.
**Learning Curve**
Java is a simple language without much of the flexibility of other members of the C family, this cuts both ways, but it is seen as a straightforward language for use by an army of programmers. Enterprise projects tend to involve large numbers of developers (rightly or wrongly) and it is much easier to get a developer to a minimum level of competence in Java than C++. You also have a whole generation of graduates who have probably been largely schooled in Java.
**Choice**
Java has a vast array of libraries, frameworks, tools and IDEs, and server providers. To an enterprise its good to have choice, even if that's just for use as a bargaining chip when negotiating price. The language lends itself to code quality tools that allow enforcement of corporate standards (and as mentioned there are a lot of those tools).
**Platform Independence**
Java is write once, run (well, debug) everywhere. Sun has actively encouraged open standards that allow multiple vendors to implement their solutions. These standards give the customer the comfort that they can migrate from one vendor to another if a given vendor goes under or starts charging more. Of course the reality is that each vendor does their best to provide some "added value" features that tie the customer to them quite nicely.
**Maturity**
Its been around a long time, running a lot of servers. If your web application needs to be "6 sigma" or similar and you are the MegaCorp CTO, you are not going to look that kindly on Joe the developer wanting to do it in RoR.
**Timing/Marketing**
Java came out when programming was moving towards the web. It was positioned cleverly and got a strong position early in web development. Because of the open standards, there are some very big companies producing these platforms and they market Java pretty hard to sell those platforms.
**Inertia**
Large corporations move forward at a glacial pace (a lot are still using Java 1.4 five years after 5 was released), so once they've picked Java, it takes a massive investment to move to another platform. With each day that goes by they're cranking out more Java that would need to be migrated. Most of these companies are not primarily coding shops, so it is a very hard sell to convince the business to spend a few tens of millions rewriting their entire code base for no immediate business benefit. | Why is Java frequently used for enterprise applications? | [
"",
"java",
"jakarta-ee",
""
] |
I have weird issue with CodeIgniter,
here is a start part of my controller
```
class Home extends Controller
{
/**
* Constructor
*/
public function __construct() {
parent::Controller();
}
...
```
everything is working fine at localhost, but when I try same at server, I come cross with an error like below:
> Parse error: syntax error, unexpected
> T\_STRING, expecting T\_OLD\_FUNCTION or
> T\_FUNCTION or T\_VAR or '}' in
> /home3/blabla/public\_html/blablabla/applications/frontend/controllers/home.php
> on line 22
I researched and people say it is about PHP4.. it should be PHP5. but my server has PHP5 on. what can be the reason?
appreciate helps! thanks a lot! | I'm so sorry! I dont know how come, but Bluehost info panel says PHP 5 is active. and i just believed that. when I make a php\_info(); page just in case, i saw actually it is php 4 :/
I updated server for PHP5 and now everything is fine.
I'm sorry for messing. and thanks all you for great support!!! | It really sounds like the interpreter is stumbling on the `public` keyword which it doesn't expect, which is an indication of/problem with the site running on PHP4.
Make sure you're echoing the PHP version in the site itself, not just looking it up in some control panel.
Check if there are any `.htaccess` directives that may change the default handler to PHP4.
Sometimes the host may default to PHP4 for `.php` files and PHP5 only for `.php5` files. | __construct() { issue for PHP4 and PHP5. maybe an another reason | [
"",
"php",
"codeigniter",
"php4",
""
] |
How do Concepts (ie those recently dropped from the C++0x standard) differ from Interfaces in languages such as Java? | Concepts are for compile-time polymorphism, That means parametric generic code. Interfaces are for run-time polymorphism.
You have to implement an interface as you implement a Concept. The difference is that you don't have to explicitly say that you are implementing a Concept. If the required interface is matched then no problems. In the case of interfaces, even if you implemented **all** the required functions, you have to excitability say that you are implementing it!
---
I will try to clarify my answer :)
Imagine that you are designing a container that accepts any type that has the **size** member function. We formalize the Concept and call it HasSize, of course we should define it elsewhere but this is an example no more.
```
template <class HasSize>
class Container
{
HasSize[10]; // just an example don't take it seriously :)
// elements MUST have size member function!
};
```
Then, Imagine we are creating an instance of our **Container** and we call it **myShapes**, Shape is a base class and it defines the **size** member function. Square and Circle are just children of it. If Shape didn't define size then an error should be produced.
```
Container<Shape> myShapes;
if(/* some condition*/)
myShapes.add(Square());
else
myShapes.add(Circle());
```
I hope you see that Shape can be checked against **HasSize** at *compile time*, there is no reason to do the checking at run-time. Unlike the elements of **myShapes**, we could define a function that manipulates them :
```
void doSomething(Shape* shape)
{
if(/* shape is a Circle*/)
// cast then do something with the circle.
else if( /* shape is a Square */)
// cast then do something with the square.
}
```
In this function, you can't know what will be passed till run-time a Circle or a Square!
They are two tools for a similar job, though Interface-or whatever you call them- can do almost the same job of Concepts at run-time but you lose all benefits of compile-time checking and optimization! | Concepts are likes types (classes) for templates: it's for the generic programming side of the language only.
In that way, it's not meant to replace the interface classes (assuming you mean abstract classes or other C++ equivalent implementation of C# or Java Interfaces) as it's only meant to check types used in template parameters to match specific requirements.
The type check is only done at compile time like all the template code generation and whereas interface classes have an impact on runtime execution. | How do Concepts differ from Interfaces? | [
"",
"c++",
"templates",
"generics",
"c++11",
"c++-concepts",
""
] |
I'm creating a CMS as you might already know, and now I have a lil' problem.
Lets say:
I have a textfile containing this:
```
[b]Some bold text[/b]
[i]Italic[/i]
- List item 1
- List item 2
- List item 3
# List item 1
# List item 2
# List item 3
```
And I want to convert it to:
```
<b>Some bold text</b>
<i>Italic</i>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
```
The bold and italic work (with regexes), but how do I do the lists?
The '-' list should be transformed to
```
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
```
And the '#' list to
```
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
```
Does anybody have experience with this? Please help me. I'm using PHP 5.2.9 | If you don't want to use an existing parsing library, you have to parse the file line by line, and to keep the current state somewhere.
If the lines starts with " - ", and the state tells you that you're not already in a list, put a <ul> plus a <li>. If you're already in a list, just put the <li>.
Same thing with lines starting with " # ". | You might consider using another markup language such as [Markdown](http://daringfireball.net/projects/markdown/) or [Textile](http://textism.com/tools/textile/). Then you would just have to deal with a library. | PHP automatic list creation from a textfile to (X)HTML | [
"",
"php",
"html",
"html-lists",
""
] |
Ahoy Stack Overflow! This be mai first post...
*I'm attempting to identify users with a salted unique public key.*
1. ***Algorithm*** - Should I use uniqid(), sha256, sha512, something else? All hashes will be salted. NIST recommended SHA256, but I prefer to hear what others might suggest.
2. ***Generation*** - Does hash(SALT + `AUTO_INCREMENT_PK` + `CREATED_TIMESTAMP`) suffice? More entropy?
* I'd use email, as it is unique for each user, however the user can modify their email address. I was also considering storing signup\_email so that hashes would not have to be re-calculated.
3. ***MySQL Storage*** - Currently, our ID's are INT(255) `auto_increment` primary key's. As stated earlier, potentially hundreds of millions of keys. Depending on the crypto algo, I should have a fixed-size ID. Can I keep INT(255) or should I use CHAR(n)?
`---------------------- Thanks for reading :) -------------------------------` | One thing: If you don't trust the users with their IDs, sending them over GET or POST will not work; those are all visible to motivated users.
---
I would use SHA256 using a salt.counter.time string, and use the output to generate GUIDs for the actual id. This would minimize the possibility for collisions.
You will have to use CHAR for MySQL to store GUIDs.
See the comments at <https://www.php.net/manual/en/function.uniqid.php> for more in-depth info. AFAIK GUID is not part of the PHP core so you have to fake it a bit. | If you are using user id as the way to allow a user to do anything with your service, if one user "guesses" the user id of another one, he'll be able to do whatever he wants with that one's account ?
You do not have any kind of other password or anything to go along that ?
Well, in that case, you need something quite unique, don't you ;-)
*(Hoping I understood the question well -- but that might not be the case -- sorry, if it isn't)*
What do you think of using [Globally Unique Identifier](http://en.wikipedia.org/wiki/Globally_Unique_Identifier) (like, for instance, `61350955-9755-4AF3-8C19-6DBC42CA69E2`) for your users ?
For an example of how they look like, take a look at <http://createguid.com/>
As a sidenote, that GUID is quite long ; which means lots of bytes in your DB, if you have millions users... So, it probably shouldn't be used as any kind of primary/foreign key.
What about using the smallest possible integer (that fits the number of users you'll have) as primary/foreign key, as that one will be duplicated in many places of the application ; and only have the "long user id" stored only once, in your user table ? | Generating Strong Unique User ID's w/PHP & MySQL | [
"",
"php",
"mysql",
"security",
"optimization",
"hash",
""
] |
I have an existing jQuery plugin which makes a lot of AJAX calls (mostly JSON). I am wondering what is the quickest to allow it to do cross-site calls i.e. the $.get and $.post URL's will not be from the same domain.
I have heard of JSONP, but was wondering if someone could give me an concrete example to go about the whole process. I want to make minimal changes if possible to my script. Should I use a proxy.php of sorts?
Thank you for your time. | JSONP will allow you to do cross-site calls. [See jQuery docs on that matter.](http://docs.jquery.com/Ajax/jQuery.ajax)
The concept is simple: instead of doing a normal Ajax call, jQuery will append a `<script>` tag to your `<head>`. In order for this to work, your JSON data needs to be wrapped in a
function call.
Your server needs to send information in such way (PHP example):
```
$json = json_encode($data);
echo $_GET['jsonp_callback'] . '(' . $json . ');';
```
Then, you can use jQuery to fetch that information:
```
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: 'http://myotherserver.com/getdata',
success: function () {
// do stuff
},
});
```
More information is available here: [What is JSONP?](http://remysharp.com/2007/10/08/what-is-jsonp/) | If you have control over the remote domain or the remote domain has a permissive [crossdomain.xml](http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html) you can drop in a library like [flXHR](http://flxhr.flensed.com/) in conjunction with its [jQuery plugin](http://flxhr.flensed.com/jquery.php). | Cross-site AJAX using jQuery | [
"",
"javascript",
"jquery",
"ajax",
"cross-site",
""
] |
After much Google searching and code experimentation, I'm stumped on a complex C# LINQ-to-objects problem which in SQL would be easy to solve with a pair of ROW\_NUMBER()...PARTITION BY functions and a subquery or two.
Here's, in words, what I'm trying to do in code-- the underlying requirement is removing duplicate documents from a list:
1. First, group a list by (Document.Title, Document.SourceId), assuming a (simplified) class definition like this:
```
class Document
{
string Title;
int SourceId; // sources are prioritized (ID=1 better than ID=2)
}
```
2. Within that group, assign each document an index (e.g. Index 0 == 1st document with this title from this source, Index 1 = 2nd document with this title from this source, etc.). I'd love the equivalent of ROW\_NUMBER() in SQL!
3. Now group by (Document.Title, Index), where Index was computed in Step #2. For each group, return only one document: the one with the lowest Document.SourceId.
Step #1 is easy (e.g. codepronet.blogspot.com/2009/01/group-by-in-linq.html), but I'm getting stumped on steps #2 and #3. I can't seem to build a red-squiggle-free C# LINQ query to solve all three steps.
Anders Heilsberg's post on [this thread](http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/54f6ac70-e74c-4d9d-a9ee-6373714c0755/) is I think the answer to Steps #2 and #3 above if I could get the syntax right.
I'd prefer to avoid using an external local variable to do the Index computation, as recommended on slodge.blogspot.com/2009/01/adding-row-number-using-linq-to-objects.html, since that solution breaks if the external variable is modified.
Optimally, the group-by-Title step could be done first, so the "inner" groupings (first by Source to compute the index, then by Index to filter out duplicates) can operate on small numbers of objects in each "by title" group, since the # of documents in each by-title group is usually under 100. I really don't want an N2 solution!
I could certainly solve this with nested foreach loops, but it seems like the kind of problem which should be simple with LINQ.
Any ideas? | I think jpbochi missed that you want your groupings to be by pairs of values (Title+SourceId then Title+Index). Here's a LINQ query (mostly) solution:
```
var selectedFew =
from doc in docs
group doc by new { doc.Title, doc.SourceId } into g
from docIndex in g.Select((d, i) => new { Doc = d, Index = i })
group docIndex by new { docIndex.Doc.Title, docIndex.Index } into g
select g.Aggregate((a,b) => (a.Doc.SourceId <= b.Doc.SourceId) ? a : b);
```
First we group by Title+SourceId (I use an anonymous type because the compiler builds a good hashcode for the grouping lookup). Then we use Select to attach the grouped index to the document, which we use in our second grouping. Finally, for each group we pick the lowest SourceId.
Given this input:
```
var docs = new[] {
new { Title = "ABC", SourceId = 0 },
new { Title = "ABC", SourceId = 4 },
new { Title = "ABC", SourceId = 2 },
new { Title = "123", SourceId = 7 },
new { Title = "123", SourceId = 7 },
new { Title = "123", SourceId = 7 },
new { Title = "123", SourceId = 5 },
new { Title = "123", SourceId = 5 },
};
```
I get this output:
```
{ Doc = { Title = ABC, SourceId = 0 }, Index = 0 }
{ Doc = { Title = 123, SourceId = 5 }, Index = 0 }
{ Doc = { Title = 123, SourceId = 5 }, Index = 1 }
{ Doc = { Title = 123, SourceId = 7 }, Index = 2 }
```
**Update:** I just saw your question about grouping by Title first. You can do this using a subquery on your Title groups:
```
var selectedFew =
from doc in docs
group doc by doc.Title into titleGroup
from docWithIndex in
(
from doc in titleGroup
group doc by doc.SourceId into idGroup
from docIndex in idGroup.Select((d, i) => new { Doc = d, Index = i })
group docIndex by docIndex.Index into indexGroup
select indexGroup.Aggregate((a,b) => (a.Doc.SourceId <= b.Doc.SourceId) ? a : b)
)
select docWithIndex;
``` | To be honest, I'm quite confused with your question. Maybe if you should explain what you're trying to solve. Anyway, I'll try to answer what I understood.
1) First, I'll assume that you already have a list of documents grouped by `Title`+`SourceId`. For testing purposes, I hardcoded a list as follow:
```
var docs = new [] {
new { Title = "ABC", SourceId = 0 },
new { Title = "ABC", SourceId = 4 },
new { Title = "ABC", SourceId = 2 },
new { Title = "123", SourceId = 7 },
new { Title = "123", SourceId = 5 },
};
```
2) To get put a index in every item, you can use the `Select` extension method, passing a Func selector function. Like this:
```
var docsWithIndex
= docs
.Select( (d, i) => new { Doc = d, Index = i } );
```
3) From what I understood, the next step would be to group the last result by `Title`. Here's how to do it:
```
var docsGroupedByTitle
= docsWithIndex
.GroupBy( a => a.Doc.Title );
```
The GroupBy function (used above) returns an `IEnumerable<IGrouping<string,DocumentWithIndex>>`. Since a group is enumerable too, we now have an enumerable of enumerables.
4) Now, for each of the groups above, we'll get only the item with the minimum `SourceId`. To make this operation we'll need 2 levels of recursion. In LINQ, the outer level is a selection (for each group, get one of its items), and the inner level is an aggregation (get the item with the lowest `SourceId`):
```
var selectedFew
= docsGroupedByTitle
.Select(
g => g.Aggregate(
(a, b) => (a.Doc.SourceId <= b.Doc.SourceId) ? a : b
)
);
```
Just to ensure that it works, I tested it with a simple `foreach`:
```
foreach (var a in selectedFew) Console.WriteLine(a);
//The result will be:
//{ Doc = { Title = ABC, SourceId = 0 }, Index = 0 }
//{ Doc = { Title = 123, SourceId = 5 }, Index = 4 }
```
I'm not sure that's what you wanted. If not, please comment the answer and I can fix the answer. I hope this helps.
Obs.: All the classes used in my tests were [anonymous](http://msdn.microsoft.com/en-us/library/bb397696.aspx). So, you don't really need to define a `DocumentWithIndex` type. Actually, I haven't even declared a `Document` class. | LINQ-to-objects index within a group + for different groupings (aka ROW_NUMBER with PARTITION BY equivalent) | [
"",
"c#",
"linq",
"group-by",
"linq-to-objects",
"row-number",
""
] |
would this be possible? (I don't have vs. 2010, so I can't try it myself, sorry)
```
public interface IComplexList<out TOutput, in TInput> where TOutput : TInput
{
public IEnumerator<TOutput> GetEnumerator();
public void Add(TInput item);
}
public interface IList<T> : IComplexList<T, T>
{
}
```
If I get it right, you could use this to actually implement covariance and contravariance in the same interface. | No, you can't. In your example `IList<T>` is invariant. `IList<T>` would require to declare `in`/`out` to be covariant/contravariant. It's not possible to do that just by inheriting some interface that is covariant. | Well, your question is slightly confusing because of the existing `IList<T>` type. However, the following *does* compile:
```
public interface IComplexList<out TOutput, in TInput> where TOutput : TInput
{
IEnumerator<TOutput> GetEnumerator();
void Add(TInput item);
}
public interface ISimpleList<T> : IComplexList<T, T>
{
}
```
You can even change it to extend `IEnumerable<TOutput>`:
```
public interface IComplexList<out TOutput, in TInput>
: IEnumerable<TOutput>
where TOutput : TInput
{
void Add(TInput item);
}
public interface ISimpleList<T> : IComplexList<T, T>
{
}
```
The indexer is tricky, because you'd want different types involved. You could do:
```
TOutput Get(int index);
void Set(int index, TInput item);
```
and then put the indexer into `ISimpleList<T>` instead of course...
That doesn't let you use `ISimpleList<T>` variantly though, because you've basically forced TInput=TOutput.
An alternative approach is to separate out the input from the output:
```
public interface IReadableList<out T> : IEnumerable<T>
{
T Get(int index);
}
public interface IWritableList<in T>
{
void Add(T item);
void Set(int index, T item);
}
public interface IMyList<T> : IReadableList<T>, IWritableList<T> {}
```
Then you could write:
```
public void Foo(IWritableList<string> x) { ... }
IMyList<object> objects = new MyList<object>();
Foo(objects);
```
and vice versa for `IReadableList`. In other words, you allow variance for each side individually, but you never get variance for the two sides together. | IList using covariance and contravariance in c#, is this possible? | [
"",
"c#",
"generics",
"covariance",
"ilist",
"contravariance",
""
] |
Lets say I'm in a file called `openid.py` and I do :
```
from openid.consumer.discover import discover, DiscoveryFailure
```
I have the `openid` module on my pythonpath but the interpreter seems to be trying to use my `openid.py` file. How can I get the library version?
(Of course, something other than the obvious 'rename your file' answer would be nice). | Thats the reason absolute imports have been chosen as the new default behaviour. However, they are not yet the default in 2.6 (maybe in 2.7...). You can get their behaviour now by importing them from the future:
```
from __future__ import absolute_import
```
You can find out more about this in the PEP metnioned by Nick or (easier to understand, I think) in the document ["What's New in Python 2.5"](http://docs.python.org/whatsnew/2.5.html). | **Rename it**. This is the idea behind name spaces. your `openid` could be a sub-module in your top module `project`. your `email` will clash with top module `email` in stdlib.
because your openid is not universal, it provides a special case for your project. | Python: How can I choose which module to import when they are named the same | [
"",
"python",
"import",
"namespaces",
""
] |
Working in python I want to extract a dataset with the following structure:
Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potential to go on for infinity, in reality a depth of 10 levels is unusual, as is having more than 10 siblings at each level.
For each item in the dataset I want to show show all items for which this item is their parent... and so on until it reaches the bottom of the dataset.
Doing the first two levels is easy, but I'm unsure how to make it efficiently recurs down through the levels.
Any pointers very much appreciated. | you should probably use a defaultdictionary for this:
```
from collections import defaultdict
itemdict = defaultdict(list)
for id, parent_id in itemlist:
itemdict[parent_id].append(id)
```
then you can recursively print it (with indentation) like
```
def printitem(id, depth=0):
print ' '*depth, id
for child in itemdict[id]:
printitem(child, depth+1)
``` | Are you saying that each item only maintains a reference to its parents? If so, then how about
```
def getChildren(item) :
children = []
for possibleChild in allItems :
if (possibleChild.parent == item) :
children.extend(getChildren(possibleChild))
return children
```
This returns a list that contains all items who are in some way descended from item. | Recursive? looping to n levels in Python | [
"",
"python",
"recursion",
""
] |
Using C#.
I am trying to move a `Form` without its title bar.
I found an article about it on: <http://www.codeproject.com/KB/cs/csharpmovewindow.aspx>
It works as long as I do not set `FormBorderStyle` as `None`.
Is there a way to make it work with this property set as `None`? | I know this question is over a year old, but I was searching trying to remember how I've done it in the past. So for anyone else's reference, the quickest and less complex way then the above link is to override the WndProc function.
```
/*
Constants in Windows API
0x84 = WM_NCHITTEST - Mouse Capture Test
0x1 = HTCLIENT - Application Client Area
0x2 = HTCAPTION - Application Title Bar
This function intercepts all the commands sent to the application.
It checks to see of the message is a mouse click in the application.
It passes the action to the base action by default. It reassigns
the action to the title bar if it occured in the client area
to allow the drag and move behavior.
*/
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case 0x84:
base.WndProc(ref m);
if ((int)m.Result == 0x1)
m.Result = (IntPtr)0x2;
return;
}
base.WndProc(ref m);
}
```
This will allow any form to be moved by clicking and dragging within the client area. | Here it is the best way I have found. It is a ".NET way", wihout using WndProc. You just have to handle the MouseDown, MouseMove and MouseUp events of the surfaces you want to be draggable.
```
private bool dragging = false;
private Point dragCursorPoint;
private Point dragFormPoint;
private void FormMain_MouseDown(object sender, MouseEventArgs e)
{
dragging = true;
dragCursorPoint = Cursor.Position;
dragFormPoint = this.Location;
}
private void FormMain_MouseMove(object sender, MouseEventArgs e)
{
if (dragging)
{
Point dif = Point.Subtract(Cursor.Position, new Size(dragCursorPoint));
this.Location = Point.Add(dragFormPoint, new Size(dif));
}
}
private void FormMain_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
}
``` | How to move a Windows Form when its FormBorderStyle property is set to None? | [
"",
"c#",
"mousemove",
"formborderstyle",
""
] |
What does the `=>` operator mean in the following code?
```
foreach ($user_list as $user => $pass)
```
The code is a comment at PHP.net.
The user does not specify the value of `$user_list`, `$user` or `$pass`.
I normally see that `=>` means equal or greater than.
However, I am not sure about its purpose here because it is not assigned.
I read the code as
1. process a list of users in integers
2. such that the value of each user is equal or greater than password
The above does not make sense to me. | `=>` is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to `$user` and the value to `$pass`.
Example:
```
$user_list = array(
'dave' => 'apassword',
'steve' => 'secr3t'
);
foreach ($user_list as $user => $pass) {
echo "{$user}'s pass is: {$pass}\n";
}
// Prints:
// "dave's pass is: apassword"
// "steve's pass is: secr3t"
```
Note that this can be used for numerically indexed arrays too.
Example:
```
$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw
``` | It means assign the key to $user and the variable to $pass
When you assign an array, you do it like this
```
$array = array("key" => "value");
```
It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.
According to the [PHP Manual](https://www.php.net/manual/en/language.types.array.php), the '=>' created key/value pairs.
Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.
And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:
```
$array = array("test" => "foo");
foreach($array as $key => $value)
{
echo $key . " : " . $value; // Echoes "test : foo"
}
foreach($array as $value)
{
echo $value; // Echoes "foo"
}
``` | What does "=>" mean in PHP? | [
"",
"php",
""
] |
I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following
```
myHashTable = {}
myLists = { 'hits':{}, 'misses':{}, 'total':{} }
sorted = { 'hits':[], 'misses':[], 'total':[] }
for item in myList:
id = item.pop('id')
myHashTable[id] = item
for k, v in item.iteritems():
myLists[k][id] = v
```
So, if I had the following list of dictionaries:
```
[ {'id':'id1', 'hits':200, 'misses':300, 'total':400},
{'id':'id2', 'hits':300, 'misses':100, 'total':500},
{'id':'id3', 'hits':100, 'misses':400, 'total':600}
]
```
I end up with
```
myHashTable =
{
'id1': {'hits':200, 'misses':300, 'total':400},
'id2': {'hits':300, 'misses':100, 'total':500},
'id3': {'hits':100, 'misses':400, 'total':600}
}
```
and
```
myLists =
{
'hits': {'id1':200, 'id2':300, 'id3':100},
'misses': {'id1':300, 'id2':100, 'id3':400},
'total': {'id1':400, 'id2':500, 'id3':600}
}
```
I then need to sort all of the data in each of the myLists dictionaries.
What I doing currently is something like the following:
```
def doSort(key):
sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True)
which would yield, in the case of misses:
[('id3', 400), ('id1', 300), ('id2', 200)]
```
This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)
> **\* EDIT \*** This service is a ThreadingTCPServer which has a method
> allowing a client to connect and add
> new data. The new data may include
> new records (meaning dictionaries with
> unique 'id's to what is already in
> memory) or modified records (meaning
> the same 'id' with different data for
> the other key value pairs
>
> So, once this is running I would pass
> in
>
> ```
> [
> {'id':'id1', 'hits':205, 'misses':305, 'total':480},
> {'id':'id4', 'hits':30, 'misses':40, 'total':60},
> {'id':'id5', 'hits':50, 'misses':90, 'total':20
> ]
> ```
>
> I have been using dictionaries to
> store the data so that I don't end up
> with duplicates. After the
> dictionaries are updated with the
> new/modified data I resort each of
> them.
>
> **\* END EDIT \***
So, what is the best way for me to sort these? Is there a better method? | You may find this related answer from Guido: [Sorting a million 32-bit integers in 2MB of RAM using Python](http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html) | What you really want is an ordered container, instead of an unordered one. That would implicitly sort the results as they're inserted. The standard data structure for this is a tree.
However, there doesn't seem to be one of these in Python. I can't explain that; this is a core, fundamental data type in any language. Python's dict and set are both unordered containers, which map to the basic data structure of a hash table. It should definitely have an optimized tree data structure; there are many things you can do with them that are impossible with a hash table, and they're quite tricky to implement well, so people generally don't want to be doing it themselves.
(There's also nothing mapping to a linked list, which also should be a core data type. No, a deque is not equivalent.)
I don't have an existing ordered container implementation to point you to (and it should probably be implemented natively, not in Python), but hopefully this will point you in the right direction.
A good tree implementation should support iterating across a range by value ("iterate all values from [2,100] in order"), find next/prev value from any other node in O(1), efficient range extraction ("delete all values in [2,100] and return them in a new tree"), etc. If anyone has a well-optimized data structure like this for Python, I'd love to know about it. (Not all operations fit nicely in Python's data model; for example, to get next/prev value from another value, you need a reference to a node, not the value itself.) | Best way to sort 1M records in Python | [
"",
"python",
""
] |
We are working on a website that has tons of images and one of the requirement is to have ALT text for each image (JPG, JPEG, PNG, GIF etc). So whenever the HTML shows and image the ALT text for that image is also written to HTML along with IMG SRC.
After our discussion with developers the solutions that turned up are
1) Create a new table to hold all these image names. Then each time the image is used a db lookup is done and appropriate ALT text is added.
2) Another solution is to write some EXIF info into each file and each time they are used the EXIF info of the file is read and added to HTML as required.
Any suggestions on how to proceed. There are a lot of images so we are looking for the best solution with least load on server and loading time.
Additional info - We run PHP on our server to select images etc.
Thanks | I'ld rule out EXIF as it does not support PNG and GIF.
The db lookup sounds okay (to me) and would scale okay (as long as you did it cleverly). For example you should try to reduce lookups as much as possible.
You might even already have some of this data, and it would be useful to have data about the images anyways | If you wan't to give the images an alt text, [it should be something that works correctly if the image is not there](http://htmlhelp.com/feature/art3.htm).
I shouldn't be "image's alt text", or "image.jpg". Rather it should be something like "Stackoverflow.com has a lot of questions and answers." when showing a SO screenshot. But if your image **can't** have a meaningful alt text, then just make alt="", and move on, sometimes it's simply better to give no alt text than giving a bad alt text.
Because of this, you *should* store the alt text for every image that **means** something, and not put meaningless alt text (ruling out EXIF information). | ALT text for images in HTML | [
"",
"php",
"html",
"xhtml",
"accessibility",
""
] |
Imagine I have a class in C# called "Bar" that has a public function on it called Foo().
Inside the Foo() function, is there a way for me to to identify where Foo() has been executed from? More precisely I want to find out if Foo() was called from an .aspx file. Like this <% Bar.Foo() %> versus from code behind Bar.Foo().
The reason I ask is that I want the function to behave differently when it is executed inside a .aspx file.
**EDIT:**
I realize I can use two different functions, I really don't want to get into the boring details of my problem because it is very difficult to explain, not to mention very long. Just know that it is a unique problem I am wrestling with, and I know I can solve it by being able to identify the source of where it is called. | When you say "behave differently"; I wonder whether checking [`HttpContext.Current`](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.current.aspx) (after adding a reference to `System.Web.dll`) would be a better idea...
Otherwise, you're into stack-frame parsing territory; not a good idea.
Of course, I'd want the code to do the same job either way, using something like dependency injection to handle the differences... | It may be possible by examining the stack, but to me that would be a very bad smell. You might want to use the [Decorator](http://en.wikipedia.org/wiki/Decorator_pattern) pattern to modify the behavior of Bar, giving it a different Foo() implementation when called from a web page.
For example,
```
<% new WebBar( Bar ).Foo(); %>
```
Where WebBar has a different implementation of Foo that uses Bar, but does the different computation that you desire. This keeps your Bar class from having to be "web-aware", but still gives you a relatively easy way to get your "web" behavior from it.
On the other hand, if what you are after is just having it return a string when executed in code-behind and write to the response when executed in ASPX, then just use a different set of tags.
```
<%= Bar.Foo() %>
```
instead of
```
<% Bar.Foo(); %>
``` | Identifying the source of execution | [
"",
"c#",
"asp.net",
""
] |
From two unequal arrays, i need to compare & delete based on the last value of an array.
Example:
`m[0]` and `n[0]` are read form a text file & saved as a array, `[0]` - their column number in text file.
```
m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44]
n[0] = [0.00, 1.12, 1.34, 1.45, 2.54, 3.12, 3.57]
```
`n[0]` last value is `3.57`, it lies between `3.40` and `3.80 of m[0] so I need to print till 3.40 in`m[0]`
**Required output:**
```
p[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40]
``` | if both lists are ordered, you can do:
```
import bisect
m[0][:bisect.bisect(m[0],n[0][-1])]
``` | Some details are a little unclear, but this should do what you want:
```
p[0] = [x for x in m[0] if x < n[0][-1]]
``` | comparing and sorting array | [
"",
"python",
"list",
""
] |
If it wasn't a virtual method, you can still achieve the same effect by just writing your `ToString` method normally, right?
You could even use the optional `new` keyword.
Wouldn't this have better performance? | > If it wasn't a virtual method, you can still achieve the same effect, by just writing your ToString method as normal, right?
No. Consider (e.g.) the signature of (one overload of) the `Console.WriteLine` function:
```
void Console.WriteLine(object o);
```
If `ToString` were novirtual, this would always call the `System.Object.ToString` implementation, not the one on the actual object passed to the function. | Along the lines of Konrad's comment:
```
public Class A
{
public new string ToString()
{
return "Hello from A";
}
}
object a = new A();
a.ToString();
```
Would NOT return 'Hello from A' but instead would return the type name (which is what object's implementation does). | Why is Object.ToString a virtual method? | [
"",
"c#",
".net",
""
] |
I am accepting user input via a web form (as UTF-8), saving it to a MySQL DB (using UTF-8 character set) and generating a text file later (encoded as UTF-8). I am wondering if there is any chance of text corruption using UTF-8 instead of something like UCS-2? Is UTF-8 good enough in this situation? | More than that, it is perhaps the only encoding you should *ever* consider using.
Some great reading on the subject:
[The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky](http://www.joelonsoftware.com/articles/Unicode.html) | If you are working with a great deal of Asian text (more so than Latin text), you may want to consider UTF-16. UTF-8 can accurately represent the entire Unicode range of characters, but it is optimized for text that is mostly ASCII. UTF-16 is space-efficient over the entire [Basic Multilingual Plane](http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes).
But UTF-8 is most certainly "good enough"—there will not be corruption arising simply because you are using UTF-8 over, say, UTF-16. | Is UTF-8 acceptable for reading/writing Asian languages? | [
"",
"c#",
"unicode",
"utf-8",
""
] |
I'm writing some custom Comparators, and I'd like them to push null items to the bottom of the list, regardless of whether I'm sorting ascending or descending. What's a good strategy or pattern for approaching this?
Offhand:
* Simply write separate ascending and
descending comparators, sharing code
where possible
* Delegate null handling to another
class, either by throwing an NPE or
by calling it explicitly
* Include an ascending flag and put
conditional logic in it to navigate
around the nulls
* Wrap regular comparators in a
null-handling class
Any other strategies? I'd like to hear about any experiences with different approaches, and any pitfalls for the various strategies. | The last option appeals to me a lot. Comparators are really great to chain together. In particular you may well want to write a `ReverseComparator` as well as a `NullWrappingComparator`.
---
EDIT: You don't have to write this yourself. If you look at the [Ordering](http://code.google.com/p/google-collections/source/browse/trunk/src/com/google/common/collect/Ordering.java) class in the [Google Collections Library](http://code.google.com/p/google-collections/) you'll find this and all kinds of other goodies :)
---
EDIT: Going into more detail to show what I mean about `ReverseComparator`...
One word of warning - in the implementation of a `ReverseComparator`, reverse the order of the arguments instead of negating the result, as otherwise `Integer.MIN_VALUE` is "reversed" to itself.
So this implementation is wrong (assuming `original` is the comparator to reverse):
```
public int compare(T x, T y)
{
return -original.compare(x, y);
}
```
but this is right:
```
public int compare(T x, T y)
{
return original.compare(y, x);
}
```
The reason is that we always want to reverse the comparison, but if `original.compare(x, y)` returns `int.MIN_VALUE`, then the bad comparer will *also* return `int.MIN_VALUE`, which is incorrect. This is due to the funny property that `int.MIN_VALUE == -int.MIN_VALUE`. | I agree with Jon Skeet (it's so easy :). I tried to implement a very simple [decorator](http://en.wikipedia.org/wiki/Decorator_pattern):
```
class NullComparators {
static <T> Comparator<T> atEnd(final Comparator<T> comparator) {
return new Comparator<T>() {
public int compare(T o1, T o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return comparator.compare(o1, o2);
}
};
}
static <T> Comparator<T> atBeginning(final Comparator<T> comparator) {
return Collections.reverseOrder(atEnd(comparator));
}
}
```
given a Comparator:
```
Comparator<String> wrapMe = new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
};
```
and some test data:
```
List<String> strings = Arrays.asList(null, "aaa", null, "bbb", "ccc", null);
```
you can sort with nulls at end:
```
Collections.sort(strings, NullComparators.atEnd(wrapMe));
```
```
[aaa, bbb, ccc, null, null, null]
```
or at beginning:
```
Collections.sort(strings, NullComparators.atBeginning(wrapMe));
```
```
[null, null, null, ccc, bbb, aaa]
``` | Nice general way to sort nulls to the bottom, regardless? | [
"",
"java",
"design-patterns",
"comparator",
""
] |
> **Possible Duplicates:**
> [Gracefully avoiding NullPointerException in Java](https://stackoverflow.com/questions/963936/gracefully-avoiding-nullpointerexception-in-java)
> [Multilingual fields in DB tables](https://stackoverflow.com/questions/936936/multilingual-fields-in-db-tables)
>
> **Exact duplicate**
>
> [Gracefully avoiding NullPointerException in Java](https://stackoverflow.com/questions/963936/gracefully-avoiding-nullpointerexception-in-java)
What do you like more? I just hate seeing the last one. It just seems backwards.
```
String randomtext = "stack overflow";
if(randomtext.equals("stack overflow"))
{
//do something
}
```
or
```
String randomtext = "stack overflow";
if("stack overflow".equals(randomtext))
{
//do something
}
``` | Contrary to what some people think, these two are **not functionally equivalent.** The first one will throw a `NullPointerException` if the `randomtext` is `null` while the second one won't. This is why I'd choose the latter. | If the string variable can be `null`, you always want to make the literal go first.
```
"stack overflow".equals(randomtext)
```
will never cause a `NullPointerException`, but
```
randomtext.equals("stack overflow")
```
will, if `randomtext == null`.
For that reason, although I like the variable.equals(literal), I used the former. | If-statement - Check String against variable or variable against String? | [
"",
"java",
"if-statement",
""
] |
Hi I need a quick solution to do filtering/sorting using the Winforms DataGridView control just as in Excel.
I have reviewed the existing posts on this area but none seems to meet my needs.
I am populating my DataGridView manually - no data binding | The DataGridView columns already support sorting.
I would populate a DataTable with your data and then bind the DataGridView to myDataTable.DefaultView.
You can filter the rows displayed by setting myDataTable.DefaultView.RowFilter.
You could place Textboxes and/or Comboboxes above the DataGridView and update myDataTable.DefaultView.RowFilter as the input/selections change. | If you're looking for a Excel like filtering funcionality, check out this article:
<http://msdn.microsoft.com/en-us/library/aa480727.aspx> | C# Winforms DataGridView with sorting/filtering like Ms Excel | [
"",
"c#",
"datagridview",
""
] |
I'm looking to write a library that uses the new optional parameters feature of C# 4.0, but I want to target it to the 3.5 version of the framework. Is this possible?
Are optional parameters syntactic sugar in the same way that extension methods are? | With VS2010 RC, I was able to create a .NET 3.5 application that uses optional parameters in C#.
So yes, it's all about syntactic sugar. | VS 2010 supports optional parameters in C# for .NET 3.5 solutions. One caveat however, is that the command-line compiler will report errors.
So, if you have automated builds in running, - using NANT or something else using the command-line compiler - your builds will fail. | Can you use optional parameters in code targeting .NET 3.5? | [
"",
"c#",
"visual-studio-2010",
".net-4.0",
""
] |
I was just wondering if there was any way to make my object return false if placed in an if statement. The reason is I'm making a custom exception class. I would like to be able to do something along the lines of
```
class Dog{
public function lookAround()
{
if(seeDog())
{
return bark;
}
else
{
return sit;
}
}
public function seeDog()
{
if(object == Dog)
{
return "husky";
}
else
{
return Dog_Exception(no_see);
}
}
}
```
I understand that this is a horrendously stupid example. However, the point is that as this object stands, the `if(seeDog())` test will evaluate `true` for both string "husky" and for the `Dog_Exception` object. If at all possible, i'd like `Dog_Exception` to evaluate to `false`, if placed in an `if` condition. That way I wouldn't have to, for example, use a construct like `if(typeof(seeDog()) == Dog_Exception)` etc. I doubt this is possible, but any help would be great. Thanks! | Why are you returning an exception? Shouldn't you be throwing it? | what about something like a try catch? you need to throw the exception not return it.
```
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
```
via: <https://www.php.net/manual/en/language.exceptions.php> | How can I make a custom exception object evaluate to false in an if condition? | [
"",
"php",
"object",
"boolean-expression",
""
] |
I'm trying to optimize 'in the small' on a project of mine.
There's a series of array accesses that are individually tiny, but profiling has revealed that these array accesses are where the vast majority of my program is spending its time. So, time to make things faster, since the program takes about an hour to run.
I've moved the following type of access:
```
const float theValOld1 = image(x, y, z);
const float theValOld2 = image(x, y+1, z);
const float theValOld3 = image(x, y-1, z);
const float theValOld4 = image(x-1, y, z);
```
etc, for 28 accesses around the current pixel.
where image thunks down to
```
float image(const int x, const int y, const int z) const {
return data[z*xsize*ysize + y*xsize + x];
}
```
and I've replaced it with
```
const int yindex = y*xsize;
const int zindex = z*xsize*ysize;
const float* thePtr = &(data[z*xsize*ysize + y*xsize + x]);
const float theVal1 = *(thePtr);
const float theVal2 = *(thePtr + yindex);
const float theVal3 = *(thePtr - yindex);
const float theVal4 = *(thePtr - 1);
```
etc, for the same number of operations.
I would expect that, if the compiler were totally awesome, that this change would do nothing to the speed. If the compiler is not awesome, then I'd say that the second version should be faster, if only because I'm avoiding the implict pointer addition that comes with the [] thunk, as well as removing the multiplications for the y and z indeces.
To make it even more lopsided, I've moved the z operations into their own section that only gets hit if zindex != 0, so effectively, the second version only has 9 accesses. So by that metric, the second version should definitely be faster.
To measure performance, I'm using QueryPerformanceCounter.
What's odd to me is that the order of operations matters!
If I leave the operations as described and compare the timings (as well as the results, to make sure that the same value is calculated after optimization), then the older code takes about 45 ticks per pixel and the new code takes 10 ticks per pixel. If I reverse the operations, then the old code takes about 14 ticks per pixel and the new code takes about 30 ticks per pixel (with lots of noise in there, these are averages over about 100 pixels).
Why should the order matter? Is there caching or something happening? The variables are all named different things, so I wouldn't think that would matter. If there is some caching happening, is there any way I can take advantage of it from pixel to pixel?
Corollary: To compare speed, I'm supposing that the right way is to run the two versions independently of one another, and then compare the results from different runs. I'd like to have the two comparisons next to each other make sense, but there's obviously something happening here that prevents that. Is there a way to salvage this side-by-side run to get a reasonable speed comparison from a single run, so I can make sure that the results are identical as well (easily)?
EDIT: To clarify.
I have both new and old code in the same function, so I can make sure that the results are identical.
If I run old code and then new code, new code runs faster than old.
If I run new code and then old code, old code runs faster than new.
The z hit is required by the math, and the if statement cannot be removed, and is present in both. For the new code, I've just moved more z-specific code into the z section, and the test code I'm using is 100% 2D. When I move to 3D testing, then I'm sure I'll see more of the effect of branching. | If both the new and old versions run on the same data array, then yes, the last run will almost certainly get a speed bump due to caching. Even if the code is different, it'll be accessing data that was already touched by the previous version, so depending on data size, it *might* be in L1 cache, will probably be in L2 cache, and if a L3 cache exists, almost certainly in that. There'll probably also be some overlap in the code, meaning that the instruction cache will further boost performance of the second version.
A common way to benchmark is to run the algorithm once first, without timing it, simply to ensure that that's going to be cached, is cached, and then run it again a large number of times with timing enabled. (Don't trust a single execution, unless it takes at least a second or two. Otherwise small variations in system load, cache, OS interrupts or page faults can cause the measured time to vary). To eliminate the noise, measure the combined time taken for several runs of the algorithm, and obviously with no output in between. The fact that you're seeing spikes of 3x the usual time means that you're measuring at a *way* too fine-grained level. Which basically makes your timings useless.
> Why should the order matter? Is there caching or something happening? The variables are all named different things, so I wouldn't think that would matter. If there is some caching happening, is there any way I can take advantage of it from pixel to pixel?
The naming doesn't matter. When the code is compiled, variables are translated into memory addresses or register id's. But when you run through your image array, you're loading it all into CPU cache, so it can be read faster the next time you run through it.
And yes, you can and should take advantage of it.
The computer tries very hard to exploit spatial and temporal locality -- that is, if you access a memory address X at time T, it assumes that you're going to need address X+1 very soon (spatial locality), and that you'll probably also need X again, at time T+1 (temporal locality). It tries to speed up those cases in every way possible (primarily by caching), so you should try to exploit it.
> To make it even more lopsided, I've moved the z operations into their own section that only gets hit if zindex != 0, so effectively, the second version only has 9 accesses. So by that metric, the second version should definitely be faster.
I don't know where you placed that if statement, but if it's in a frequently evaluated block of code, the cost of the branch might hurt you more than you're saving. Branches *can* be expensive, and they inhibit the compiler's and CPU's ability to reorder and schedule instructions. So you may be better off without it. You should probably do this as a separate optimization that can be benchmarked in isolation.
I don't know which algorithm you're implementing, but I'm guessing you need to do this for every pixel?
If so, you should try to cache your lookups. Once you've got `image(x, y, z)`, that'll be the next pixel's `image(x+1, y, z)`, so cache it in the loop so the next pixel won't have to look it up from scratch. That would potentially allow you to reduce your 9 accesses in the X/Y plane down to three (use 3 cached values from the last iteration, 3 from the one before it, and 3 we just loaded in this iteration)
If you're updating the value of each pixel as a result of its neighbors values, a better approach may be to run the algorithm in a checkerboard pattern. Update every other pixel in the first iteration, using only values from their neighbors (which you're not updating), and then run a second pass where you update the pixels you read from before, based on the values of the pixels you updated before. This allows you to eliminate dependencies between neighboring pixels, so their evaluation can be pipelined and parallelized efficiently.
In the loop that performs all the lookups, unroll it a few times, and try to place all the memory reads at the top, and all the computations further down, to give the CPU a chance to overlap the two (since data reads are a lot slower, get them started, and while they're running, the CPU will try to find other instructions it can evaluate).
For any constant values, try to precompute them as much as possible. (rather than `z*xsize*ysize`, precompute `xsize*ysize`, and multiply z with the result of that.
Another thing that *may* help is to prefer local variables over globals or class members. You may gain something simply by, at the start of the function, making local copies of the class members you're going to need. The compiler can always optimize the extra variables out again if it wants to, but you make it clear that it shouldn't worry about underlying changes to the object state (which might otherwise force it to reload the members every time you access them)
And finally, study the generated assembly in detail. See where it's performing unnecessary store/loads, where operations are being repeated even though they could be cached, and where the ordering of instructions is inefficient, or where the compiler fails to inline as much as you'd hoped.
I honestly wouldn't expect your changes to the lookup function to have much effect though. An array access with the `operator[]` is easily convertible to the equivalent pointer arithmetic, and the compiler can optimize that pretty efficiently, as long as the offsets you're adding don't change.
Usually, the key to low-level optimizations is, somewhat ironically, *not* to look at individual lines of code, but at whole functions, and at loops. You need a certain amount of instructions in a block so you have something to work with, since a lot of optimizations deal with breaking dependencies between chains of instructions, reordering to hide instruction latency, and with caching individual values to avoid memory load/stores. That's almost impossible to do on individual array lookups, but there's almost certainly a lot gained if you consider a couple of pixels at a time.
Of course, as with almost all microoptimizations, there are no *always true* answers. Some of the above might be useful to you, or they might not.
If you tell us more about the access pattern (which pixels are you accessing, is there any required order, and are you just reading, or writing as well? If writing, when and where are the updated values used?)
If you give us a bit more information, we'll be able to offer much more specific (and likely to be effective) suggestions | You *may* (possibly) be running into some sort of readahead or cacheline boundary issue. Generally speaking, when you load a single value and it isn't "hot" (in cache), the CPU will pull in a cache line (32, 64, or 128 bytes are pretty typical, depending on processor). Subsequent reads to the same line will be much faster.
If you change the order of operations, you may just be seeing stalls due to how the lines are being loaded and evicted.
The best way to figure something like this out is to open "Disassembly" view and spend some quality time with your processor's reference manual.
If you're lucky, the changes that the code reordering causes will be obvious (the compiler may be generating extra instructions or branches). Less lucky, it will be a stall somewhere in the processor -- during the decode pipeline or due to a memory fetch...
A good profiler that can count stalls and cache misses may help here too (AMD has [CodeAnalyst](http://developer.amd.com/CPU/CODEANALYST/Pages/default.aspx), for example).
If you're not under a time crunch, it's really worthwhile to dive into the disasm -- at the very least, you'll probably end up learning something you didn't know before about how your CPU, machine architecture, compiler, libraries, etc work. (I almost always end up going "huh" when studying disasm.) | C++ 'small' optimization behaving strangely | [
"",
"c++",
"optimization",
""
] |
Would anyone mind having a look at these bits of code and see if there is a memory leak in them, it isn't going to be overly large but my program keeps crashing after a while of running and I don't know how to use viualvm even though I have been reading up on it for several days now and haven't the slightest idea what I am looking for in the heap dumps and so on. thanks for your help,
ps I know I have posted far to muchg code but i dont know what else to do so that you can hopefully see where the problem arises for me. If it helps I can email you the full program to take a look at. Thanks very much for any help you can give.
```
public class extraScreenPanel {
static JPanel screenPanel = new JPanel(new BorderLayout());
public static JPanel extraScreenPanel(int dispNum)
{
JLabel label = new JLabel("" + dispNum + "");
label.setPreferredSize(new Dimension(800, 600));
label.setVerticalAlignment( SwingConstants.TOP );
screenPanel = imgDisp(dispNum);
label.setForeground(Color.white);
label.setFont(new Font("Serif", Font.BOLD, 200));
screenPanel.add(label, BorderLayout.PAGE_END );
return screenPanel;
}
public static JPanel imgDisp(int picNum) {
String ref = "C:/PiPhotoPic/pic16.jpg";;
BufferedImage loadImg = loadImage(ref);
JImagePanel panel = new JImagePanel(loadImg, 0, 0);
panel.setPreferredSize(new Dimension(800, 600));
return panel;
}
public static class JImagePanel extends JPanel{
private BufferedImage image;
int x, y;
public JImagePanel(BufferedImage image, int x, int y) {
super();
this.image = image;
this.x = x;
this.y = y;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, null);
}
}
public static BufferedImage loadImage(String ref) {
BufferedImage bimg = null;
try {
bimg = javax.imageio.ImageIO.read(new File(ref));
} catch (Exception e) {
e.printStackTrace();
}
BufferedImage bimg2 = resize(bimg,800,600);//set these to the resolution of extra screens
return bimg2;
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
}
```
Another part of the method
```
public class piPhoto
{
static int mostRecent = 0;
static int dispNum = 0;
static int lastDisp = 0;
static JPanel picPanel = imgDisp.imgDisp(dispNum);
static JFrame frame = new JFrame("Pi Photography");
static JPanel cornerPanel = new JPanel();
static JPanel bottomPanel = new JPanel();
static JPanel menuPanel = new JPanel(new BorderLayout());
static JPanel currentNumPanel = currentNumDisp.currentNumDisp(dispNum);
static JPanel printPanel = printOptions.printOptions();
static JPanel buttonPanel = updateButtonPanel.updateButtonPanel(mostRecent);
static JPanel screen1Panel = new JPanel();
static JPanel screen2Panel = new JPanel();
static JPanel screen3Panel = new JPanel();
static JPanel screen4Panel = new JPanel();
static JPanel screenPanel12 = new JPanel(new BorderLayout());
static JPanel screenPanel123 = new JPanel(new BorderLayout());
static JPanel screenPanel1234 = new JPanel(new BorderLayout());
static JPanel screensPanel = new JPanel(new BorderLayout());
static JPanel deskScreen = new JPanel();
static JPanel wholePanel = new JPanel(new BorderLayout());
static JPanel wholePanel2 = new JPanel(new BorderLayout());
public static void launchPiPhoto()
{
launchNC4.launch();
bottomPanel.setPreferredSize(new Dimension(1440, 200));
buttonPanel.setPreferredSize(new Dimension(1120, 200));
cornerPanel.setPreferredSize(new Dimension(300,200));
screen1Panel.setPreferredSize(new Dimension(800,600));
screen2Panel.setPreferredSize(new Dimension(800,600));
screen3Panel.setPreferredSize(new Dimension(800,600));
screen4Panel.setPreferredSize(new Dimension(800,600));
screensPanel.setPreferredSize(new Dimension(3200,600));
deskScreen.setPreferredSize(new Dimension(800,600));
wholePanel.setPreferredSize(new Dimension(4640,900));
wholePanel2.setPreferredSize(new Dimension(5440,900));
cornerPanel.setLayout(new BoxLayout(cornerPanel, BoxLayout.PAGE_AXIS));
picPanel.setPreferredSize(new Dimension(1120, 620));
//Menu Panel Set-up
cornerPanel.add(currentNumPanel);
bottomPanel.add(buttonPanel);
bottomPanel.add(cornerPanel);
menuPanel.setPreferredSize(new Dimension(1440, 840));
menuPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
menuPanel.add(bottomPanel, BorderLayout.PAGE_END);
menuPanel.add(picPanel, BorderLayout.LINE_START);
menuPanel.add(printPanel, BorderLayout.LINE_END);
screen1Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent - 3);
screen2Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent - 2);
screen3Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent - 1);
screen4Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent);
screenPanel12.add(screen1Panel, BorderLayout.LINE_START);
screenPanel12.add(screen2Panel, BorderLayout.LINE_END);
screenPanel123.add(screenPanel12, BorderLayout.LINE_START);
screenPanel123.add(screen3Panel, BorderLayout.LINE_END);
screenPanel1234.add(screenPanel123, BorderLayout.LINE_START);
screenPanel1234.add(screen4Panel, BorderLayout.LINE_END);
screensPanel.add(screenPanel1234, BorderLayout.LINE_END);
deskScreen = extraScreenPanel.extraScreenPanel(dispNum);
wholePanel.add(menuPanel, BorderLayout.LINE_START);
wholePanel.add(screensPanel, BorderLayout.LINE_END);
wholePanel2.add(wholePanel, BorderLayout.LINE_START);
wholePanel2.add(deskScreen, BorderLayout.LINE_END);
frame.add(wholePanel2);
//Frame set-up and Initializing
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
newImageRecieved.runCheck();
}
public static void repaintButtonPanel()
{
bottomPanel.removeAll();
bottomPanel.setPreferredSize(new Dimension(1440, 200));
buttonPanel = updateButtonPanel.updateButtonPanel(mostRecent);
buttonPanel.setPreferredSize(new Dimension(1120, 200));
cornerPanel.add(currentNumPanel);
bottomPanel.add(buttonPanel);
bottomPanel.add(cornerPanel);
menuPanel.add(bottomPanel, BorderLayout.PAGE_END);
frame.validate();
}
public static void repaintScreens()
{
wholePanel.remove(screensPanel);
screen1Panel.removeAll();
screen1Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent);
screen2Panel.removeAll();
screen2Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent - 1);
screen3Panel.removeAll();
screen3Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent - 2);
screen4Panel.removeAll();
screen4Panel = extraScreenPanel.extraScreenPanel(piPhoto.mostRecent - 3);
screenPanel12.add(screen1Panel, BorderLayout.LINE_START);
screenPanel12.add(screen2Panel, BorderLayout.LINE_END);
screenPanel123.add(screenPanel12, BorderLayout.LINE_START);
screenPanel123.add(screen3Panel, BorderLayout.LINE_END);
screenPanel1234.add(screenPanel123, BorderLayout.LINE_START);
screenPanel1234.add(screen4Panel, BorderLayout.LINE_END);
screensPanel.add(screenPanel1234, BorderLayout.LINE_END);
wholePanel.add(menuPanel, BorderLayout.LINE_START);
wholePanel.add(screensPanel, BorderLayout.LINE_END);
frame.validate();
}
}
```
the part that checks to see if new images are added to the file yet
```
public class newImageRecieved {
static int count = 0;
public static void runCheck()
{
int delay = 500;
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
newImageRecieved(piPhoto.mostRecent+1);
}
};
new Timer(delay, taskPerformer).start();
}
public static void newImageRecieved(int picNum)
{
String url[] = new String[5000];
String part1;
url[0] = "C:/PiPhotoPic/pic16.jpg";
for(Integer i=1;i<5000;i++){
if(i<10){part1 = "C:/temp/new0000000";}
else if(i<100){part1 = "C:/temp/new000000";}
else if(i<1000){part1 = "C:/temp/new00000";}
else {part1 = "C:/temp/new00000";}
String num = Integer.toString(i);
url[i]= part1 + num + ".jpg";
}
if(picNum<0){picNum=0;}
String ref = url[picNum];
piPhoto.frame.validate();
boolean exists = (new File(ref)).exists();
if(exists == true)
{
while (exists == true)
{
piPhoto.updateMostRecent(picNum);
ref = url[picNum + 1];
picNum = picNum + 1;
exists = (new File(ref)).exists();
}
piPhoto.updateMostRecent(picNum-1);
piPhoto.repaintButtonPanel();
piPhoto.repaintScreens();
count=0;
}
// }
}
}
``` | Solved it today. Turns out I didnt remove the image panels from the old method, aso that when i was repainting them I was painting over the old ones and the old ones were still there. So I just needed to add in removeAll() for all the panels that were being updated and the program ran fine without heapstack errors. | You might try a memory profiler such as [YourKit](http://yourkit.com) | HEAPSPACE ERROR: cannot figure out what is causing the error | [
"",
"java",
"heap-memory",
"visualvm",
"jvisualvm",
""
] |
In the course of a complex database structure, I need to provide the user with a means of editing data stored in a series of tables. Although all the data types are the same, they don't line up 1:1 in their names. To alleviate this, I created a query that maps the original names (which come from outside reports) to the internally-used names; from these queries, everything is fed into one giant UNION query.
All the data types and field sizes line up properly.
What else do I need to do to make this UNION query work?
This is the current SQL behind the query:
```
SELECT * FROM MappingQuery1 UNION SELECT * FROM MappingQuery2;
```
EDIT:
An answer below posted a link to a [KB article](http://support.microsoft.com/kb/328828) that states with certainty that the data in a `UNION` query can't be updated. Is there any way I can work around this? For example:
```
SELECT * FROM MappingQuery1, MappingQuery2;
```
Will this work? Remember, all the fields are aligned in type, size, and name. | > When the query is a Union query, you
> cannot update data in the query.
<http://support.microsoft.com/kb/328828>
When Access combines rows from different tables in a union query, the individual rows lose their underlying table identity. Access cannot know which table you mean to update when you try to change a row in a union query, so it disallows all updates.
Following question **edit**:
You could probably work around this using **VBA** and **ADO** to update the corresponding table. The way i'd approach this would be to ensure that your union table contains a column that has the id from the source table along with another column that names the source table.
e.g. in your union you'd have something like this:
```
SELECT 'Table1', id, ... FROM Table1
UNION
SELECT 'Table2', id, ... FROM Table2
```
Then through a data entry form and VBA you could look at the values of the currently selected row and update the relevant table.
EDIT 2: For onedaywhen
This inserts values into a table using Access VBA
```
Option Compare Database
Option Explicit
Public Sub InsertDataPunk(TargetTable As String, IdVal As Long, MyVal As String)
Dim conn As ADODB.Connection
Set conn = CurrentProject.Connection
Dim sql As String
'You could build something fancier here
sql = "INSERT INTO " & TargetTable & " VALUES (" & IdVal & ",'" & MyVal & "')"
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = conn
cmd.CommandText = sql
cmd.CommandType = adCmdText
cmd.Execute
End Sub
InsertDataPunk "Table2", 7, "DooDar"
``` | My preference would be to consolidate those individual tables into a master table. With all the data in one table, this could be a whole lot easier.
However, assuming you **have** to keep the indiviual tables separate, change your mapping queries to include a field expression for the source table name. And include that table name field in the UNION query.
Then create a continuous form based on the read-only UNION query. Add a subform based on another query which returns a single editable record from the appropriate table. In the main form's On Current event, rewrite the RowSource for the subform's query:
```
strSQL = "SELECT fields_to_edit FROM " & Me.txtTableSource & _
" WHERE pkfield =" & Me.txtPKeyField & ";"
Me.SubformName.Rowsource = strSQL
Me.SubformName.Requery
``` | How do I make an editable UNION query? | [
"",
"sql",
"ms-access",
"ms-access-2007",
"ms-office",
""
] |
I am trying to make the user input exactly 4 characters with no spaces... here's what I have:
```
.[^\s]{4}
```
but everything I enter says that it didn't match the regex...
Where am I going wrong? | Why is there an extra `.` in front? That will match a separate character before your "four non-spaces" get counted.
You probably also want to bind it to the beginning and end of the string, so:
```
^[^\s]{4}$
``` | Your making it more complicated than it needs to be and using `\S`, not `\s` so you don't match spaces. I think this should work for you:
```
^[\S]{4}$
```
**Definition of solution:**
^ - begins with
[/S] - capital 'S' means no white space
{4} - match 4 times
$ - end of string | How can I create a regular expression that requires 4 characters and no spaces? | [
"",
"c#",
"asp.net",
"regex",
"validation",
""
] |
I'm looking to set up my development environment at home for writing Windows applications in Python.
For my first piece, I'm writing a simple, forms-based application that stores data input as XML (and can read that information back.) I do want to set up the tools I'd use professionally, though, having already done a round of didactic programming.
What tools are professional python developers using these days? In order to have a working python environment, what version of the compiler should I be using? What editor is common for professionals? What libraries are considered a must-have for every serious python developer?
Specifically, which Windowing and XML libraries are de rigeur for working in Windows? | I like [Eclipse + PyDev (with extensions)](http://fabioz.com/pydev/).
It is available on Windows, and it works very well well. However, there are [many other IDEs](https://stackoverflow.com/questions/81584/what-ide-to-use-for-python), with strengths and weakness.
As for the interpreter (Python is *interpreted*, not *compiled*!), you have three main choices: CPython, IronPython and Jython.
When people say "Python" they usually refer to "CPython" that is the reference implementation, but the other two (based, respectively, on .Net and Java) are full pythons as well :-)
In your case, I would maybe go on **IronPython**, because it will allow you to leverage your knowledge of .Net to build the GUI and treating the XML, while leaving the implementation of business logic to Python.
Finally, should you decide to use CPython, finally, there are several choices for working with xml:
* [minidom](http://docs.python.org/library/xml.dom.minidom.html); included in the standard library
* [lxml](http://codespeak.net/lxml/), faster and with a better API; it means an additional installation on top of Python. | Lots of questions, most hard to answer correctly. First of all, most of python development happens on unix-like platforms. You will hit many walls during development on Windows box.
Python is not a compiled lanugage, current preferred version for production is 2.5. For environement setup you should take a look at [virtualenv](http://pypi.python.org/pypi/virtualenv). Editor is a personal choice, many Python developers use Vim, you can customize it pretty well to suite your needs.
About libraries, Python is very strong around this area and it's really hard to say what is a must to know. If you want to handle XML, I would preffer [lxml](http://codespeak.net/lxml/). | What's the state-of-the-art in Python programming in Windows? | [
"",
"python",
"windows",
"xml",
"ide",
"wxpython",
""
] |
What is the best way to store a map of key object to a collection of value objects?
I could use
```
Dictionary<KeyType, Collection<ValueType>>
```
but that approach tends to involve a lot of housekeeping, and clutters up the code.
The Lookup type is almost the result I'm looking for, but it's immutable and has no constructor. I could create my own custom class, but it seems like it should exist in the framework *somewhere*. | That's about your best answer. It's pretty common to use `Dictionary<KeyType, ICollection<ValueType>>`. Using the `var` keyword to declare your local variables is the best way to tidy up.
Other than that, your only option is creating a `MultiDictionary<T,K>` type. You could also call it `Lookup` and put it in your own namespace?
Edit: Google says you should take a look at this for an existing implementation: [Multi-value Dictionary C# source code (.NET 3.5)](http://weblogs.asp.net/fbouma/archive/2009/05/18/multi-value-dictionary-c-source-code-net-3-5.aspx). BSD2 license means you can use it for commercial apps with at attribution. :) | You could also, as for tidying, alias the specific generic type:
```
using MultiDictionary = Dictionary<string, ICollection<int>>;
```
Then later:
```
var foo = new MultiDictionary();
``` | Elegant way to do Dictionary<Key, Collection<Value>> | [
"",
"c#",
"types",
""
] |
I have a simple WPF single window application contains Textboxes and Buttons. And I also use NotifyIcon and DateTimePicker of Windows Forms in WPF window. How can I effectively dispose all the controls? | Hardly anything in WPF has a `Dispose` method. The vast majority of classes encapsulate purely managed information. You can attach an object into the tree (e.g. via a `Children.Add` method) and you can remove it again - that's how the state management works. It exactly doesn't fit into the `IDisposable` pattern, because once you've removed a control you can add it again, whereas `Dispose` means forever (although you could use `Dispose` to manage it in addition to `Add`/`Remove` methods).
[A discussion about it on the Microsoft forums.](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/afa6cc76-92f4-4144-99c5-e8f5fdc88029/)
There are a few things that ought to be `IDisposable` but aren't, like `DispatcherTimer`, and there's nothing to stop you from implementing `IDisposable` on your own classes. It's up to you when to call `Dispose`; basically when you know you aren't going to be using the object any more.
For a `Window` you just call `Close` to close it, and WPF takes care of everything else. | I would say that the same rule applies in WPF applications as in any other .NET applications: if an object implements `IDisposable`, you should call `Dispose` when you are done using it. If you dynamically load and unload controls, and they do not implement `IDisposable`, just setting any references to `null` (and detaching any event handlers) should be enough for the garbage collector to do its job. | When to call Dispose() method in WPF application | [
"",
"c#",
"wpf",
"dispose",
""
] |
I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
```
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
```
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
**NOTE** the authed function worked fine before i added the session code. | what about using this to setup session
```
session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
```
and at the top of each "secure" page use this code:
```
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
```
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
```
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");
``` | First, don't store the password in the session. It's a **bad thing**. Second, don't store the username in the session until *after* you have authenticated.
Try the following:
```
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$authed = auth($username, $password);
if (! $authed) {
header('Location: http://website.com/fail.php');
} else {
$_SESSION['username'] = $username;
}
}
if (isset($_SESSION['username'])) {
$navbar = 1;
$logindisplay = 0;
} else {
header ('Location: http://website.com/fail.php');
}
``` | php sessions to authenticate user on login form | [
"",
"php",
"session",
""
] |
I am using simple model which is a very neat piece of code but i have one requirement i can't figure out.
<http://www.ericmmartin.com/simplemodal/>
my use case is the third options where i want a "Confirmation Popup" after a user clicks on an action. The issue is that in the example the message is hardcoded in the js file.
i need to be able to pass in this message as well as the link that is associated with the "Yes" and "no" buttons.
has anyone done anything similar. | Looking at the source of the page tells you everything you need to know.
```
<!-- Confirm -->
<link type='text/css' href='css/confirm.css' rel='stylesheet' media='screen' />
<script src='js/confirm.js' type='text/javascript'></script>
```
and
```
<div id='confirmDialog'><h2>Confirm Override</h2>
<p>A modal dialog override of the JavaScript confirm function. Demonstrates the use of <code>onShow</code> as well as how to display a modal dialog confirmation instead of the default JavaScript confirm dialog.</p>
<form action='download/' method='post'>
<input type='button' name='confirm' value='Demo' class='confirm demo'/><input type='button' name='download' value='Download' class='demo'/>
<input type='hidden' name='demo' value='confirm'/>
</form>
</div>
<div id='confirm' style='display:none'>
<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>
<div class='header'><span>Confirm</span></div>
<p class='message'></p>
<div class='buttons'>
<div class='no simplemodal-close'>No</div><div class='yes'>Yes</div>
</div>
</div>
```
Above we can clearly see that the messaging is all in the HTML, and not in the javascript at all.
And if we then look at the JS source of confirm.js it's all laid out there for you in terms of how to initialize/trigger it.
```
/*
* SimpleModal Confirm Modal Dialog
* http://www.ericmmartin.com/projects/simplemodal/
* http://code.google.com/p/simplemodal/
*
* Copyright (c) 2009 Eric Martin - http://ericmmartin.com
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Revision: $Id: confirm.js 185 2009-02-09 21:51:12Z emartin24 $
*
*/
$(document).ready(function () {
$('#confirmDialog input.confirm, #confirmDialog a.confirm').click(function (e) {
e.preventDefault();
// example of calling the confirm function
// you must use a callback function to perform the "yes" action
confirm("Continue to the SimpleModal Project page?", function () {
window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/';
});
});
});
function confirm(message, callback) {
$('#confirm').modal({
close:false,
position: ["20%",],
overlayId:'confirmModalOverlay',
containerId:'confirmModalContainer',
onShow: function (dialog) {
dialog.data.find('.message').append(message);
// if the user clicks "yes"
dialog.data.find('.yes').click(function () {
// call the callback
if ($.isFunction(callback)) {
callback.apply();
}
// close the dialog
$.modal.close();
});
}
});
}
``` | The code given in the confirm.js contains two method definitions. One is a generic method called `confirm`, which will create your modal popup with the message you want to be displayed. You have to use this method whenever you want to create the modal popup.
```
confirm("Are you sure you want to delete this item?", function() {
//Here you will write the code that will handle the click of the OK button.
});
```
Here, the second argument is a function (this works almost like a delegate in C#). What will happen is that the `confirm` function will show a dialog containing your message, and when the user clicks any button, the anonymous function passed as the second argument will be invoked. You can also write a "normal" function and pass it as a second argument to `confirm` -
```
function callbackHandler() {
//Here you will write the code that will handle the click of the OK button.
}
confirm("Are you sure you want to delete this item?", callbackHandler);
```
Your function will be invoked by this piece of code -
```
// if the user clicks "yes"
dialog.data.find('.yes').click(function () {
// call the callback
if ($.isFunction(callback)) { callback.apply(); }
// close the dialog
$.modal.close();
});
``` | how do i have dynamic confirmation popup using simple modal | [
"",
"javascript",
"jquery",
"variables",
"simplemodal",
""
] |
I'm trying to learn GDI+ (in C#). CodeProject has [this article](http://www.codeproject.com/KB/books/1861004990.aspx) which is a free chapter from the 2001 WROX book *Professional C#*. Is this still an advisable way to learn GDI+ or is a more modern resource preferable? If the latter, what would be such a resource? | AFAIK, GDI+ hasn't evolved too much since 2001, so I think this book is still relevant, although it might not contain the latest additions to the API. | Yes, you can safely use it. I've been working with GDI+ over several versions and I can't think of any changes. Now that's not foolproof but it has been one of the more stable API's. | GDI+ book from 2001: outdated or still relevant? | [
"",
"c#",
"gdi+",
"drawing",
""
] |
My site is gzipped compressed, and it doesn't load properly in IE. It works fine in FF/Chrome, but in IE, the only thing that pops up is a box asking to download the .gz file which contains the html document for the page.
Is this normal? Do I have to turn off gzip? | Are you sending the correct headers?
You need to send the
```
Content-Encoding: gzip
```
header for IE to understand that it is gzipped (Firefox, et al are smart enough to detect this automatically - even though they shouldn't!)
In PHP, you can do this using:-
```
header('Content-Encoding: gzip');
``` | One thing to add - you should turn off gzip compression for IE6 pre-SP2. Before SP2, IE6 doesn't always read and cache gzipped content properly and you end up with mangled code.
You can identify an IE6 SP2 install by looking for "SV1" in the user-agent string. | Why is gzip compression with Internet Explorer not working? | [
"",
"php",
"internet-explorer",
""
] |
I'm using Firefox 3.5. My doctype is XHTML 1.0 Strict. Let's say I want to insert an image into a div with id "foo"; then I might try:
```
var foo = $('#foo');
foo.html('<img src="bar.gif" />');
```
This does indeed add the image. But I noticed that this was causing some odd behavior later in the document, which I suspected might be due to XHTML breaking. Sure enough, using the Web Developer tool for Firefox, I checked the generated source and was horrified to find that after the script runs, I have:
```
<div id="foo"><img src="bar.gif"></div>
```
Where did the trailing slash on the img tag go!? Searching around, I found that this isn't a jQuery-specific problem: The pure JavaScript code
```
document.getElementById('foo').innerHTML = '<img src="bar.gif" />';
```
produces the same results. So, what should I do? I should note that using the expanded form
```
<img src="bar.gif"></img>
```
does not affect the result. How do I insert strictly valid XHTML into my document with JavaScript? | This is a little bit of a shot in the dark, and I am not sure whether this could be the cause, but are you sure that you are serving XHTML and not just standard HTML with XHTMLs syntax. That is: is the MIME type of the document the default text/html or is it application/xhtml+xml?
I read the following article recently, and the problem you are having would make perfect sense to me if the document wasn't actually being treated as XML by the browser (and therefore it was removing the erroneous XHTML style slashes for not conforming to the MIME type)...
<http://www.xml.com/pub/a/2003/03/19/dive-into-xml.html>
Just a thought. | Try this instead:
```
var image = document.createElement('img');
image.setAttribute('src', 'bar.gif');
foo.appendChild(image);
``` | XHTML DOM manipulation with jQuery | [
"",
"javascript",
"jquery",
"dom",
"xhtml",
""
] |
I have content from elsewhere that I would like to insert as a post in Wordpress and then associate with an existing category. It is pretty straightforward to insert a new post into the wp\_posts table, but I can't seem to figure out how to construct a query to both insert a new post and at the same time associate the post with a category. How would one go about doing this?
If it helps, I am using WordPress 2.8 | Use this query:
```
INSERT INTO wp_posts (post_title,post_content,post_name,post_date,post_date_gmt,post_modified,post_modified_gmt,post_author,post_status)
VALUES ('title','text','post_name',now(),now(),now(),now(),1,'publish')
INSERT INTO wp_term_relationships (object_id,term_taxonomy_id) VALUES ([the_id_of_above_post],1)
``` | Categories are stored in the `wp_terms` tables, with a cross-reference between `wp_posts` and `wp_terms` stored in the `wp_term_relationships table`.
So, you would first need to insert your post into the `wp_posts` table, and then for each of the existing categories that you want to associate it with, insert a record into the `wp_term_relationships` table.
More info here: [WordPress Database Description](http://codex.wordpress.org/Database_Description) | How can I insert a post into wordpress and associate it with a category? | [
"",
"php",
"mysql",
"wordpress",
""
] |
So I recently ran into this C# statement at work:
```
public new string SomeFunction(int i)
{
return base.SomeFunction(i);
}
```
I searched the web but I think I can find a better answer here.
Now, I'm guessing that all this does is return a new string with the same value as the string returned by the call to `base.SomeFunction(i)`... is this correct?
Also, does this feature exist in other languages (java specifically)?
**EDIT:**
In my specific case, `base.SomeFunction` is protected and **NOT** virtual... does this make a difference? Thanks | No, it means that it's *hiding* `SomeFunction` in the base class rather than *overriding* it. If there weren't a method in the base class with the same signature, you'd get a compile-time error (because you'd be trying to hide something that wasn't there!)
See [this question](https://stackoverflow.com/questions/1170158) for more information. (I don't think this is a duplicate question, as it's about what "new" is for at all rather than just talking about the warning when it's absent.)
Duplicate example from my answer on that question though, just to save the clickthrough...
Here's an example of the difference between hiding a method and overriding it:
```
using System;
class Base
{
public virtual void OverrideMe()
{
Console.WriteLine("Base.OverrideMe");
}
public virtual void HideMe()
{
Console.WriteLine("Base.HideMe");
}
}
class Derived : Base
{
public override void OverrideMe()
{
Console.WriteLine("Derived.OverrideMe");
}
public new void HideMe()
{
Console.WriteLine("Derived.HideMe");
}
}
class Test
{
static void Main()
{
Base x = new Derived();
x.OverrideMe();
x.HideMe();
}
}
```
The output is:
```
Derived.OverrideMe
Base.HideMe
``` | 'new' is the member-hiding keyword. From the docs:
> When used as a modifier, the new
> keyword explicitly hides a member
> inherited from a base class. When you
> hide an inherited member, the derived
> version of the member replaces the
> base-class version. Although you can
> hide members without the use of the
> new modifier, the result is a warning.
> If you use new to explicitly hide a
> member, it suppresses this warning and
> documents the fact that the derived
> version is intended as a replacement. | Adding 'new' in front of the return type of C# method definition? | [
"",
"c#",
".net",
"methods",
""
] |
I'm working on a WinForms application. I'd like to know if chrome is installed and if so, what version is installed. It is simple enough to see if it is installed. But what is the best way to get the version number programmaticlly?
For other browsers, I call FileVersionInfo.GetVersionInfo on the main executable. But google doesn't put the version number in the the meta data. | I don't really know much about google chrome installs - but it appears to me that the "chrome.exe" is just a shell. The "chrome.dll" appears to be the actual guts and THAT file does have versioning meta data on it. | The only thing I've seen thus far is in the registry, but it appears you are limited to the HKEY CURRENT USER node.
On my machine, it's in HKCU\Software\Google\Update\Clients{a guid}\pv
Under the clients node there are a number of guids. The guid containing the chrome pv key also contains a key called "name" with value of Google Chrome.
So you might need to iterate through the guid nodes under that Clients node until you find one with key "name" = "Google Chrome" and then look for the value of the pv key.
Good luck. | How can I determine which version of Chrome is installed? | [
"",
"c#",
"winforms",
"google-chrome",
""
] |
Given the following List:
```
List<String> list = new ArrayList<String>();
list.add("s1");
list.add("s2");
list.add(null);
list.add("s3");
list.add(null);
list.add("s4");
```
I need a helper class that removes null references. Something like:
SomeHelper.removeNullReference(list);
such that the list only contains "s1", "s2", "s4", "s4" (non-null references).
What should I use to fulfill this requirement? | ```
list.removeAll(Collections.singleton(null));
``` | Java 8 added [`Collection.removeIf(Predicate)`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-) that removes all elements matching the predicate, so you can remove all occurrences of `null` from a list (or any collection) with
```
list.removeIf(Objects::isNull);
```
using [`java.util.Objects.isNull`](https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object-) as a `Predicate`.
You can also use `.removeIf(x -> x == null)` if you prefer; [the difference is very minor](https://stackoverflow.com/questions/25435056/is-there-any-difference-between-objectsnonnull-and-x-x-null). | Helper to remove null references in a Java List? | [
"",
"java",
"collections",
""
] |
Consider this example :
```
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
C c = new C();
try {
Field f = C.class.getDeclaredField("a");
f.setAccessible(true);
Integer i = (Integer)f.get(c);
System.out.println(i);
} catch (Exception e) {}
}
}
class C {
private Integer a =6;
}
```
It seems illogical that you are allowed to access private fields of classes with reflection. Why is such a functionality available? Isn't it "dangerous" to allow such access? | Private is intended to prevent accidental misuse, not as a security mechanism. If you choose to bypass it then you can do so at your own risk and the assumption you know what you are doing. | Both `getDeclaredField()` and `setAccessible()` are actually checked by the security manager and will throw an exception when your code is not allowed to do this. More often than not you won't notice it, because Java code is often run without a security manager.
One important exception are Applets, which always run with a security manager. | Why is it allowed to access Java private fields via reflection? | [
"",
"java",
"reflection",
"private-members",
""
] |
I have the following JavaScript (the spaces in the `<P>`s are non-breaking):
```
var html = '...<li>sub 2</li></ol></li></ol>\n\
<p> i. subsub 1</p>\n\
<p> ii. subsub 2</p>\n\
<ol start="2"> \n\
<ol start="3"> \n\
<li>sub 3</li></ol>...';
$(function () {
var nestedListFixer = /(?:<\/li><\/ol>\s*)+(?:<p>(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*)+(?:<ol(?:\sstyle=\"[^\"]+\")?\sstart=\"[^\"]+\">\s*)+/i;
html = html.replace(nestedListFixer, function($0, $1){
var lis = ""
$.each($1, function () {
lis += "<li>" + this + "</li>\n";
});
alert("<ol>\n" + lis + "</ol></li>");
return "<ol>\n" + lis + "</ol></li>";
});
});
```
The `alert()`'s output:
```
<ol>
<li>s</li>
<li>u</li>
<li>b</li>
<li>s</li>
<li>u</li>
<li>b</li>
<li> </li>
<li>2</li>
</ol></li>
```
Here's what I hoped it would be:
```
<ol>
<li>subsub 1</li>
<li>subsub 2</li>
</ol></li>
```
How do I correctly loop through each match in the `$1`?
**Update:** simplified pattern and matching example:
```
var text = '1ab2cb3cd4ab5cb6cd7';
$(function () {
var textFixer = /(?:a)(?:b(.*?)c)+(?:d)/i;
text = text.replace(textFixer, function($0, $1){
var numbers = "";
$.each($1, function () {
numbers += this;
});
alert(numbers);
return numbers;
});
alert(text);
});
// actual text:
// 13467
// desired text:
// 1234567
``` | Here's the solution that I came up with but it doesn't seem to be very efficient:
```
$(function () {
var nestedListFixer = /(?:<\/li><\/ol>\s*)+(?:<p>(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*)+(?:<ol(?:\sstyle=\"[^\"]+\")?\sstart=\"[^\"]+\">\s*)+/gi;
var nestedListItem = /<p>(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*/gi;
// fix nested lists
html = html.replace(nestedListFixer, function($0, $1){
var lis = ""
$.each($0.match(nestedListItem), function () {
lis += "<li>" + this.replace(nestedListItem, "$1") + "</li>\n";
});
return "<ol>\n" + lis + "</ol></li>";
});
});
```
...or for the simpler example above:
```
$(function () {
var textFixer = /(?:a)(?:b(.*?)c)+(?:d)/gi;
var textItem = /b(.*?)c/gi;
text = text.replace(textFixer, function($0, $1){
var numbers = "";
$.each($0.match(textItem), function () {
numbers += this.replace(textItem, "$1");
});
return numbers;
});
});
```
Doing a `.replace()` substitution, inside a loop of a `.match()` array, inside of a custom `.replace()` function just doesn't seem like it is very economical. It does give me the output that I was looking for though. | The updated example you've given would only match "3" not "13467" as you described. If you change your regexp to do global matching, it would return "36" and still not the "13467".
Your first example doesn't output anything either.
Are you just trying to get matches to the regular expression and loop through the matches?
If so,
```
var text = '1ab2cb3cd4ab5cb6cd7';
var matches = text.match(/(\d)/g);
for (i=0; i<matches.length; i++) {
alert(matches[i]);
}
``` | How do I loop through a regex's matches inside a replace in javascript? | [
"",
"javascript",
"jquery",
"regex",
"lambda",
"match",
""
] |
I can check for a module in Python doing something like:
```
try:
import some_module
except ImportError:
print "No some_module!"
```
But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)
**Note:** The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions. | It takes trickery to perform the request (and one `raise` statement is in fact inevitable because it's the one and only way specified in the PEP 302 for an import hook to say "I don't deal with this path item"!), but the following would avoid any `try`/`except`:
```
import sys
sentinel = object()
class FakeLoader(object):
def find_module(self, fullname, path=None):
return self
def load_module(*_):
return sentinel
def fakeHook(apath):
if apath == 'GIVINGUP!!!':
return FakeLoader()
raise ImportError
sys.path.append('GIVINGUP!!!')
sys.path_hooks.append(fakeHook)
def isModuleOK(modulename):
result = __import__(modulename)
return result is not sentinel
print 'sys', isModuleOK('sys')
print 'Cookie', isModuleOK('Cookie')
print 'nonexistent', isModuleOK('nonexistent')
```
This prints:
```
sys True
Cookie True
nonexistent False
```
Of course, these would be absurd lengths to go to in real life for the pointless purpose of avoiding a perfectly normal `try`/`except`, but they seem to satisfy the request as posed (and can hopefully prompt Python-wizards wannabes to start their own research -- finding out exactly how and why all of this code does work as required is in fact instructive, which is why for once I'm not offering detailed explanations and URLs;-). | You can read [here](http://docs.python.org/reference/simple_stmts.html#the-import-statement) about how Python locates and imports modules. If you wanted to, you could replicate this logic in python, searching through sys.modules, sys.meta\_path & sys.path to look for the required module.
However, predicting whether it would parse successfully (taking into account compiled binary modules) without using exception handling would be very difficult, I imagine! | Check for a module in Python without using exceptions | [
"",
"python",
"module",
"python-module",
""
] |
I programmed a simple WCF service that stores messages sent by users and sends these messages to the intended user when asked for. For now, the persistence is implemented by creating *username*.xml files with the following structure:
```
<messages recipient="username">
<message sender="otheruser">
...
</message
</messages>
```
It is possible for more than one user to send a message to the same recipient at the same time, possibly causing the xml file to be updated concurrently. The WCF service is currently implemented with basicHttp binding, without any provisions for concurrent access.
What concurrency risks are there? How should I deal with them? A ReadWrite lock on the xml file being accessed?
Currently the service runs with 5 users at the most, this may grow up to 50, but no more.
EDIT:
As stated above the client will instantiate a new service class with every call it makes. (InstanceContext is PerCall, ConcurrencyMode irrelevant) This is inherent to the use of basicHttpBinding with default settings on the service.
The code below:
```
public class SomeWCFService:ISomeServiceContract
{
ClassThatTriesToHoldSomeInfo useless;
public SomeWCFService()
{
useless=new ClassThatTriesToHoldSomeInfo();
}
#region Implementation of ISomeServiceContract
public void IncrementUseless()
{
useless.Counter++;
}
#endregion
}
```
behaves is if it were written:
```
public class SomeWCFService:ISomeServiceContract
{
ClassThatTriesToHoldSomeInfo useless;
public SomeWCFService()
{}
#region Implementation of ISomeServiceContract
public void IncrementUseless()
{
useless=new ClassThatTriesToHoldSomeInfo();
useless.Counter++;
}
#endregion
}
```
So concurrency is never an issue until you try to access some externally stored data as in a database or in a file.
The downside is that you cannot store any data between method calls of the service unless you store it externally. | If your WCF service is a singleton service and guaranteed to be that way, then you don't need to do anything. Since WCF will allow only one request at a time to be processed, concurrent access to the username files is not an issue unless the operation that serves that request spawns multiple threads that access the same file. However, as you can imagine, a singleton service is not very scalable and not something you want in your case I assume.
If your WCF service is not a singleton, then concurrent access to the same user file is a very realistic scenario and you must definitely address it. Multiple instances of your service may concurrently attempt to access the same file to update it and you will get a '*can not access file because it is being used by another process*' exception or something like that. So this means that you need to synchronize access to user files. You can use a monitor (lock), ReaderWriterLockSlim, etc. However, you want this lock to operate on per file basis. You don't want to lock the updates on other files out when an update on a different file is going on. So you will need to maintain a lock object per file and lock on that object e.g.
```
//when a new userfile is added, create a new sync object
fileLockDictionary.Add("user1file.xml",new object());
//when updating a file
lock(fileLockDictionary["user1file.xml"])
{
//update file.
}
```
Note that that dictionary is also a shared resource that will require synchronized access.
Now, dealing with concurrency and ensuring synchronized access to shared resources at the appropriate granularity is very hard not only in terms of coming up with the right solution but also in terms of debugging and maintaining that solution. Debugging a multi-threaded application is not fun and hard to reproduce problems. Sometimes you don't have an option but sometimes you do. So, **Is there any particular reason why you're not using or considering a database based solution?** Database will handle concurrency for you. You don't need to do anything. If you are worried about the cost of purchasing a database, there are very good proven open source databases out there such as MySQL and PostgreSQL that won't cost you anything.
Another problem with the xml file based approach is that updating them will be costly. You will be loading the xml from a user file in memory, create a message element, and save it back to file. As that xml grows, that process will take longer, require more memory, etc. It will also hurt your scalibility because the update process will hold onto that lock longer. Plus, I/O is expensive. There are also benefits that come with a database based solution: transactions, backups, being able to easily query your data, replication, mirroring, etc.
I don't know your requirements and constraints but I do think that file-based solution will be problematic going forward. | You need to read the file before adding to it and writing to disk, so you do have a (fairly small) risk of attempting two overlapping operations - the second operation reads from disk before the first operation has written to disk, and the first message will be overwritten when the second message is committed.
A simple answer might be to queue your messages to ensure that they are processed serially. When the messages are received by your service, just dump the contents into an MSMQ queue. Have another single-threaded process which reads from the queue and writes the appropriate changes to the xml file. That way you can ensure you only write one file at a time and resolve any concurrency issues. | WCF service with XML based storage. Concurrency issues? | [
"",
"c#",
".net",
"wcf",
"concurrency",
"persistence",
""
] |
I want to write a web proxy for exercise, and this is the code I have so far:
```
// returns a map that contains the port and the host
def parseHostAndPort(String data) {
def objMap // this has host and port as keys
data.eachLine { line ->
if(line =~ /^(?i)get|put|post|head|trace|delete/) {
println line
def components = line.split(" ")
def resource = components[1]
def colon = resource.indexOf(":")
if(colon != -1) {
URL u = new URL(resource)
def pHost = u.host
def pPort = u.port
return (objMap = [host:pHost,port:pPort])
}
else {
return (objMap = [host:resource,port:80])
}
}
}
return objMap
}
// reads a http request from a client
def readClientData(Socket clientSocket) {
def actualBuffer = new StringBuilder()
InputStream inStream = clientSocket.inputStream
while(true) {
def available = inStream.available()
if(available == 0)
break;
println "available data $available"
def buffer = new byte[available]
def bytesRead = inStream.read(buffer,0,available)
actualBuffer << new String(buffer)
}
return actualBuffer.toString()
}
def sock = new ServerSocket(9000)
sock.reuseAddress = true
while(true) {
sock.accept { cli ->
println "got a client"
def data = readClientData(cli)
def parsed = parseHostAndPort(data)
def host = parsed["host"]
def port = parsed["port"]
println "got from client $data"
def nsock = new Socket(host,port)
nsock << data // send data received from client to the socket
nsock.outputStream.flush()
def datax = readClientData(nsock)
println "got back $datax"
cli << datax // send the client the response
cli.outputStream.flush()
cli.close()
}
}
```
Right now, all it does is :
* read the HTTP request my browser sends
* parse the host and port
* connect to that host, and write the data received from the client
* send the client back the data received from the host
But ... it doesn't work all the time. Sometimes it will make a good request, sometimes not. I think it's a buffering issue, I'm not sure. The thing is, I added `flush` calls, and still nothing.
Can you spot what I'm doing wrong?
EDIT:
* I noticed that if I add some `sleep` calls, the proxy seems to "work" on a higher number of requests, but not all of them.
* to collect the bounty, help me find out what I'm doing wrong. What's the normal "algorithm" used for a web proxy? Where am I deviating from it? Thanks! | First, it's really difficult to know what exactly is going wrong here - "Sometimes it will make a good request, sometimes not." doesn't really describe what's happening when the problem occurs!!
That said, I was still able to figure out what's going wrong for you.
As you've said already, you're looking for the most basic solution that'll work consistently, so I'll avoid anything unnecessary or getting into the efficiency or otherwise of your code. Also, I'll give you the answer first and then describe what's causing the problem (it's long, but worth reading :)
## Solution
The simple answer to your problem is that you need to do some HTTP protocol parsing to figure out if all of the data has been sent by the client and not rely on what `available()` or `read()` return. How much of a PITA this is depends on how completely you wish to support the HTTP protocol. To support GET requests, it's pretty easy. It's a little harder to support POSTs that specify a content length. It's much harder to support "other" encoding types (e.g. chunked or multipart/byteranges see <https://www.rfc-editor.org/rfc/rfc2616#section-4.4>).
Anyway, I assume you're just trying to get GETs working, so to do that, you have to know that HTTP headers and bodys are separated by an "empty line", that HTTP's line delimeter is \r\n and that GETs do not have a body. Therefore a client has finished sending a GET request when it transmits \r\n\r\n.
Some code like this should handle GETs consistently for you (code is untested but it should get you to at least 90%):
```
def readClientData(Socket clientSocket) {
def actualBuffer = new StringBuilder()
def eof = false;
def emptyLine = ['\r', '\n', '\r', '\n']
def lastEmptyLineChar = 0
InputStream inStream = clientSocket.inputStream
while(!eof) {
def available = inStream.available()
println "available data $available"
// try to read all available bytes
def buffer = new byte[available]
def bytesRead = inStream.read(buffer,0,available)
// check for empty line:
// * iterate through the buffer until the first element of emptyLine is found
// * continue iterating through buffer checking subsequent elements of buffer with emptyLine while consecutive elements match
// * if any element in buffer and emptyLine do not match, start looking for the first element of emptyLine again as the iteration through buffer continues
// * if the end of emptyLine is reached and matches with buffer, then the emptyLine has been found
for( int i=0; i < bytesRead && !eof; i++ ) {
if( buffer[i] == emptyLine[lastEmptyLineChar] ){
lastEmptyLineChar++
eof = lastEmptyLineChar >= emptyLine.length()
}
else {
lastEmptyLineChar = 0
}
}
// changed this so that you avoid any encoding issues
actualBuffer << new String(buffer, 0, bytesRead, Charset.forName("US-ASCII"))
}
return actualBuffer.toString()
}
```
For POSTs, you need to add to this by also looking for the String "Content-length: " and parsing the value after this. This value is the size of the HTTP body (i.e. the bit that comes after the /r/n/r/n end of header mark) **in octals**. So when you encounter the end of header, you just need to count that number of **octals** of bytes and you know that the POST request has completed transmission.
You'll also need to determine the type of request (GET, POST etc.) - you can do this by inspecting the characters transmitted before the first space.
## Problem
Your problem is that your `readClientData` function doesn't always read all of the data sent by the client. As a result, you're sometimes sending a partial request to the server and the returns some kind of error. You should see incomplete requests printed to standard out if you replace
```
println(new String(buffer))
```
with
```
println(avaliable)
```
in the `readClientData` function.
Why is this happening? It's because available() only tells you what's currently available to be read from the InputStream and not whether or not the client has sent all the data it's going to send. An InputStream, by it's very nature, can never actually tell whether or not there will be more data (the exception to this is if there is no more underlying data to read - e.g. a socket is closed, the end of the array or file has been reached, etc. - this is the *only* time read() will return -1 (i.e. EOF)). Instead it's up to higher level code to decide whether it should read more data from the stream and it makes this decision based on application-specific rules that apply to the application-specific data being read by the InputStream.
In this case, the application is HTTP, so you need to understand the basics of the HTTP protocol before you'll get this working (cmeerw, you were on the right track).
When a HTTP request is made by a client, the client opens a socket to the server and sends a request. The client **only** closes the socket as a result of a timeout, or the underlying network connection being disconnected, or in response to user action that requires that the socket is closed (application is closed, page is refreshed, stop button pushed etc.). Otherwise, after sending the request, it just waits for the server to send a response. Once the server has sent the response, the server closes the connection [1].
Where your code succeeds, data is being provided by the client quickly and consistently enough so that the InputStream receives additional data between your invocation of `read()` and your subsequent invocation of `available()` on the next iteration of the loop (remember that `InputStream` is being provided with data "in parallel" to your code that's invoking its `read()` method). Now in the other case, where your code fails, no data has yet been provided to `InputStream`, so when your code invokes `available()`, `InputStream` correctly returns 0 since no further data has been provided to it since you invoked `read()` and therefore it has 0 bytes available for you to `read()`. This is the race condition that Johnathan's talking about.
Your code assumes that when `available()` returns 0 that all data has been sent by the client when, in fact, sometimes it has, and sometimes it has not (so sometimes you get a "good request" and other times not :).
So you need something better than `available()` to determine wheter or not the client has sent all of the data.
Checking for EOF when you invoke `read()` (see R4an's answer [2]) isn't suitable either. It should be clear why this is the case - the only time `read()` is supposed to return EOF (-1) is when the socket is closed. This isn't supposed to happen until you've forwarded the request to the target proxy, received a response and sent that response to the client, but we know it can also exceptionally be closed by the client. In fact you're seeing this behaviour when you run the sample code - the proxy hangs until the stop button is clicked in the browser, causing the client to close the connection prematurely.
The correct answer, which you now know, is to do some parsing of the HTTP and use that to determine the state of the connection.
**Notes**
[1] It's beyond a proof of concept proxy, but since it was touched on already, if the HTTP connection is "keep-alive" the server will keep the connection open and wait on another request from the client
[2] There's an error in this code that causes the readClientData mangle the data:
```
byte[] buffer = new byte[16 * 1024];
while((bytesRead = inStream.read(buffer)) >= 0) { // -1 on EOF
def bytesRead = inStream.read(buffer,0,bytesRead);
actualBuffer << new String(buffer)
}
```
The second `inStream.read()` invocation completely overwrites the data read by the first invocation of `inStream.read()`. Also bytesRead is being redefined here (not familiar enough with Groovy to know whether or not this would be an error). This line should either read:
```
bytesRead = bytesRead + inStream.read(buffer,bytesRead,buffer.length()-bytesRead);
```
or be removed entirely. | Jonathan was on the right track. The problem is partly your use of `available()`. The method `available` doesn't say "is it done?" it says "is there currently any data available?". So immediately after you've made your request there won't be any data available, and depending on network timing that might happen during processing too, but it doesn't mean that no more is coming, so your `break` is premature.
Also, the `InputStream.read(byte[] ...)` family of methods is **always** allowed to return fewer bytes than you ask for. The array length or offset,length pair constrains the *maximum*, but you can always get less. So, this code of yours:
```
def buffer = new byte[available]
def bytesRead = inStream.read(buffer,0,available)
actualBuffer << new String(buffer)
```
could create a big array, but then only get it half full of data in the read, but still append the full buffer (with its trailing unread array elements) onto the String.
Here's a revision that relies on the fact that `InputStream.read(...)` will never return unless it's end of stream or there's some data available (but not necessarily as much as you asked).
```
// reads a http request from a client
def readClientData(Socket clientSocket) {
def actualBuffer = new StringBuilder()
InputStream inStream = clientSocket.inputStream
int bytesRead = 0;
byte[] buffer = new byte[16 * 1024];
while((bytesRead = inStream.read(buffer)) >= 0) { // -1 on EOF
def bytesRead = inStream.read(buffer,0,bytesRead); // only want newly read bytes
actualBuffer << new String(buffer)
}
return actualBuffer.toString()
}
```
That said, you've got a few other problems too:
* you're pulling the whole response into memory, when you should be copying it in a byte-pump-loop directly into the client's response output stream (what happens if it's a multi gigabyte response)
* you're using Strings to store binary data -- which assumes that all the bytes work fine in the default CharacterEncoding, which might be true in UTF-8 or US-ASCII, but isn't going to work with other locales | Please help me figure out what's wrong with this web proxy code | [
"",
"java",
"sockets",
"groovy",
""
] |
I am trying to load a file that I know part of the name (and know that it will be uniquely identified by the part that I know.)
Here is the jist of it:
```
string fileName = ID + " - " + Env + " - ";
byte[] buffer;
using (FileStream fileStream = new FileStream(Server.MapPath("~") +
fileName + "*", FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(fileStream))
{
buffer = reader.ReadBytes((int)reader.BaseStream.Length);
}
}
```
Line 4 is where I need help. If I say fileName+"\*" then I will get "ID - Env - \*" instead of a wildcard matching any file after "ID - Env -" (I have real vars for ID and Env, they are just no shown here.)
Is there any way to say "match on any file that fits the beginning"?
(I am using VS 2008 SP1 and .NET 3.5 SP1)
Thanks for any help. | You'll need to locate the file you want before you open a `FileStream`.
```
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~"), fileName + "*");
if(files.Length == 1) // We got one and only one file
{
using(BinaryReader reader = new BinaryReader(new FileStream(files[0])))
{
// use the stream
}
}
else // 0 or +1 files
{
//...
}
``` | You could use the Directory.GetFiles( ) method to get a collection of files that match the pattern first and then work with the stream based on the result. | Load a System.IO.FileStream using a WildCard | [
"",
"c#",
".net-3.5",
"file-io",
""
] |
I am having a problem doing a get on googles search url from php. Here's the code I have:
```
<?php
$handle = fopen("http://www.google.com/complete/search?hl=en&js=true&qu=" .
$_GET["qu"], "r");
while (!feof($handle)) {
$text = fgets($handle);
echo $text;
}
fclose($handle);
?>
```
Here's the error I get:
> PHP Warning:
> fopen(<http://www.google.com/complete/search?hl=en&js=true&qu=cat>):
> failed to open stream: A connection
> attempt failed because the connected
> party did not properly respond after a
> period of time, or established
> connection failed because connected
> host has failed to respond. in
> C:\Inetpub\test\google.php on line 3
> PHP Fatal error: Maximum execution
> time of 60 seconds exceeded in
> C:\Inetpub\test\google.php on line 3
I'm using fiddler, and doing a request on the url itself works fine, but for some reason the php does not. Anyone have any idea why?
update: Here is my javascript:
```
function getSuggest(keyEvent) {
keyEvent = (keyEvent) ? keyEvent : window.event;
input = (keyEvent.target) ? keyEvent.target : keyEvent.srcElement;
if (keyEvent.type == "keyup") {
if (input.value) {
getSearchData("google.php?qu=" + input.value);
} else {
var target = document.getElementById("targetDiv");
target.innerHTML = "<div></div>";
}
}
}
function getSearchData(dataSource) {
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
eval(XMLHttpRequestObject.responseText);
}
}
XMLHttpRequestObject.send(null);
}
}
function sendRPCDone(unusedVariable, searchTerm, arrayTerm, arrayResults, ususedArray) {
var data = "<table>";
var loopIndex;
if (arrayResults.length != 0) {
for (var loopIndex = 0; loopIndex < arrayResults.length; loopIndex++) {
data += "<tr><td>" + "<a href='http://www.google.com/search?q=" +
arrayTerm[loopIndex] + "'>" + arrayTerm[loopIndex] + '</a></td><td>' +
arrayResults[loopIndex] + "</td></tr>";
}
}
data += "</table>";
var targetDiv = document.getElementById("targetDiv");
targetDiv.innerHTML = data;
}
```
And here is my html:
```
<div id="googleSearch">
Search For <input id="textField" type="text" name="textField" onkeyup="getSuggest(event)" />
<div id="targetDiv4"></div>
</div>
``` | **Edit:**
If it turns out you are having user agent string problems, you can set the user-agent php uses by creating and running a file with the following code in it:
`<?php ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1) Gecko/20090615 Firefox/3.5'); ?>`
I think you'll have to restart IIS after setting this, but not 100% on that.
**Note:** this is a random user agent string I pulled, there are many out there, you can set it to pretty much anything you want. There are many more at: <http://www.useragentstring.com/>
---
To check if allow\_url\_fopen is on, do this:
1. Create a php file on your server, name it whatever you desire.
2. Put this into your file `<?php phpinfo(); ?>`
3. Execute the script on your server through a web browser or fiddler if you are using that
4. check for all necessary settings.
Let us know what it is, then we can walk you through setting it to what you need. | That looks like a timeout. It could be that the server you are trying to communicate with discriminates requests based on [USER\_AGENT](http://en.wikipedia.org/wiki/User_agent). | PHP fopen fails in response | [
"",
"php",
"url",
"get",
""
] |
Lets say I have a linked list with a bunch of different data in it.
```
class Node
{
public:
Node* next;
AAA dataA;
BBB dataB;
CCC dataC;
};
```
Is there a way I make one iterator that would iterate over whatever variable I specify (rather than making three separate ones for each variable). I understand that the iterator could use templates to make it iterate over types AAA, BBB or CCC, but I don't know how I could specify which variable to return. | I think I've found a way to do pretty much what I want based on rstevens' suggestion. I looked up some stuff on class member pointers and was able to skip the middleman accessor class by doing this:
```
template <typename T>
class iterator
{
private:
Node *current;
T Node::*var;
public:
iterator()
: current(NULL), var(NULL) {}
iterator(Node *start, T Node::*var)
: current(start), var(var)
{
}
typename T &operator *() const
{
return current->*var;
}
bool end() const
{
return (current == NULL);
}
iterator &operator++()
{
if (current)
current = current->next;
return *this;
}
};
```
And then I modified Node to have convenience functions to make the iterators:
```
class Node
{
public:
Node* next;
AAA dataA;
BBB dataB;
CCC dataC;
typedef iterator<AAA> AIter;
typedef iterator<BBB> BIter;
typedef iterator<CCC> CIter;
AIter getAIter()
{
return AIter(this, &Node::dataA);
}
BIter getBIter()
{
return BIter(this, &Node::dataB);
}
CIter getCIter()
{
return CIter(this, &Node::dataC);
}
};
```
So now I can do this to easily iterate over each data member of my class:
```
for (Node::CIter iter = n1.getCIter(); !iter.end(); ++iter)
{
// tada!
}
``` | The best way I've found to do this is with [boost bind](http://www.boost.org/doc/libs/1_39_0/libs/bind/bind.html) and [boost transform\_iterator](http://www.boost.org/doc/libs/1_39_0/libs/iterator/doc/transform_iterator.html)
First you'll need a collection of Node objects and an iterator that will traverse the collection. For brevity in my example I'll use a std::list.
```
#include <boost/bind.hpp>
#include <boost/iterator/transform_iterator.hpp>
using boost;
struct FunctionAAA
{
void operator() (const AAA& x)
{}
};
struct FunctionBBB
{
void operator() (const BBB& x)
{}
};
typedef std::list<Node> NodeList;
NodeList collection;
std::foreach (
make_transform_iterator (collection->begin(), bind (&Node::dataA, _1)),
make_transform_iterator (collection->end(), bind (&Node::dataA, _1)),
FunctionAAA());
std::foreach (
make_transform_iterator (collection->begin(), bind (&Node::dataB, _1)),
make_transform_iterator (collection->end(), bind (&Node::dataB, _1)),
FunctionBBB());
``` | Is there a generic way to iterate over a specific variable in a group of objects? | [
"",
"c++",
"iterator",
""
] |
I am new to Documentum, I have to upgrade one code from Documentum foundation class to Documentum Foundation Services. Can someone provide the pros and cons of each, and good source of information to get started with it.
btw, I am writing code in Java to get information from documentum. | DFS is an abstraction layer on top of DFC.
SourceRebels is partially right, except for the detail that EMC is now treating DFS as a primary model of integration for external applications (API). You no longer need to use a compiled language (Java or .Net), since you can do everything via SOAP webservice calls. DFC remains available for low-level interaction, but with every Documentum release there are more services added to DFS.
One of the key differences is the object model. In DFS, you can create a batch of operations to send to the server for execution (for instance, create 10 objects). There are also some complex operations in DFS that would take much more code to accomplish using DFC. DFS also allows you to deploy your code to machines without the DFC installed.
Your best resource for Documentum-related questions is <http://developer.emc.com>. | IMHO they are not comparable because they are not focused on the same. DFC is an API to access Documentum while DFS is a service framework with some predefined services providing some functionality to interact with Documentum.
**Thats important: I never used DFS :-)**
DFC = Do-it-yourself. Traditional Client-Server programming. Faster.
DFS = Use predefined services or do it yourself for non-trivial tasks. SOA. Probably you need to deploy your services in a new server or purchase more Documentum licenses (not sure about that). Slow but I will feel more comfortable using this if I want to access Documentum from some legacy systems.
Thats my grain of salt I hope you find it useful. | Pros and Cons of DFC and DFS? | [
"",
"java",
"documentum6.5",
"documentum-dfs",
""
] |
I'm implementing a class-like structure in jQuery, but I'm having some trouble when I try to call some of my functions.
This is how the structure is setup:
```
MyClass = function(name) {
this.init(name);
}
$.extend(MyClass.prototype, {
init: function(theName) {
this.myFunction(); // works
$('.myclass').each(function(){
this.myFunction(); // doesn't work
});
},
myFunction = function(){}
});
```
The problem I'm having is that when I try to call one of my functions (e.g., `myFunction()`) from inside a jQuery block (like the `each()` construct above), I get the error "`myFunction() is not a function`."
I think this has something to do with the `this` keyword changing its meaning inside the jQuery block, but I'm not sure. Any help would be appreciated! | You need to assign `this` to another variable, because of how scope works.
```
MyClass = function(name) {
this.init(name);
}
$.extend(MyClass.prototype, {
init: function(theName) {
this.myFunction(); // works
var that = this;
$('.myclass').each(function(){
this.myFunction(); // doesn't work
that.myFunction(); // should work
});
},
myFunction = function(){}
});
``` | ```
MyClass = function(name) {
this.init(name);
}
$.extend(MyClass.prototype, {
init: function(theName) {
this.myFunction(); // works
temp = this;
$('.myclass').each(function(){
temp.myFunction(); // works
});
},
myFunction = function(){}
});
```
Try that. :) | How can I maintain control of the this keyword when extending prototypes in jQuery? | [
"",
"jquery",
"prototype",
"oop",
"this",
"javascript",
""
] |
I've got my hands on an old Microsoft J++ project that uses some old Microsoft-specific things from the Microsoft Java Virtual Machine (now deprecated and unsupported). It uses additional things from the old Microsoft Java Development Kit, which I can't find anywhere on the web.
It seems the best route forward is to migrate this project to the latest version of Java, and migrate the J++ .sln solution file to an Eclipse project file.
I'm a bit overwhelmed right now -- are there any tools to help ease the migration process? Any tips for doing such a conversion? | I would break this up in multiple steps.
First get this to compile and in Visual J++. You will most likely need to buy a used copy from e.g. Ebay.
A quick search found <http://cgi.ebay.com/Visual-J-6-0-Professional-Commercial-Box-561-00176_W0QQitemZ320309632655QQihZ011QQcategoryZ80301QQcmdZViewItem>
THen when you can see how this works you can work isolating and refactoring the Microsoftisms into something generically usable. This page illustrates how to make J++ work with a Sun JRE so you can do the initial work there: <http://java3d.j3d.org/tutorials/quick_fix/vis_jpp.html>
Then you will most likely have a bunch of java files which you can copy-paste into a fresh Java project inside Eclipse. | I actually developed a J++ app on Eclipse for a number of years, using Eclipse as an editor and VS as a compiler. The WFC problem was prohibitive (and will definitely keep you from porting to straight Java), but Eclipse was still able to grok and refactor most everything as a straight editor with compilation turned off. This was actually where I learned to love Eclipse.
We eventually ported the entire 700K+ line app to C# with relative ease. I would avoid J#, as it's deprecated now. Go straight to C#, use VS with Resharper and you'll *almost* feel like you're in Eclipse. : ) The C# converter was pretty dang accurate, and left helpful comments in the sections where it knew there was a less than 1-to-1 conversion, most of which were minor. | Migrate old J++ project to Eclipse? | [
"",
"java",
"migration",
"jvm",
"j++",
""
] |
I have one PHP5 object passing messages to another, and would like to attach a type to each message. For example, `MSG_HOT`, `MSG_WARM`, and `MSG_COLD`. If PHP5 had an enum type, I would probably use that to define the message types, but (unless I'm mistaken) there is no such animal. I've looked at a few options:
Strings (`'MSG_HOT'`, `'MSG_WARM'`, and `'MSG_COLD'`) are bad because I would inevitably type something like `'MSG_WRAM'` and things would break. Numbers suffer the same problem and are also less clear.
Defines work:
```
define('MSG_HOT', 1);
define('MSG_WARM', 2);
define('MSG_COLD', 3);
```
but pollute the global namespace, and thus would require more verbose names to ensure uniqueness. I'd prefer not to have my code littered with things like `APPLICATIONNAME_MESSAGES_TYPE_HOT`.
Finally, I could use class names to distinguish types, like so:
```
class MessageHot extends Message {}
class MessageWarm extends Message {}
class MessageCold extends Message {}
class Message
{
public function Type()
{
return get_class($this);
}
public function Data()
{
return $this->data;
}
public function __construct($data)
{
$this->data = $data;
}
private $data;
}
```
This is good, I think, but is also a lot of work for what seems like it ought to be a simple concept.
Am I missing a better alternative? | A very common convention is to use class constants in PHP.
e.g.
```
class Message
{
const HOT = 0;
const WARM = 1;
const COLD = 2;
}
``` | I also use a class with consts for this. I add the following
* make the class abstract, to make sure no one tries to instantiate it
* add a static array that maps the consts to strings for printing friendly messages
* implement a static \_\_toString() method to do the previous
```
abstract class Message {
const HOT = 0;
const WARM = 1;
const COLD = 2;
public static $enums= array(
self::HOT => "hot",
self::WARM => "warm",
self::COLD => "cold"
);
public static __toString($enum) {
return self::$enums[$enum];
}
}
```
I can also use the Message::$enums to test variables:
```
if (!array_key_exists($is_it_valid, Message::$enums)
``` | Alternative to enum types in PHP5? | [
"",
"php",
"enums",
""
] |
I monitor files that are dropped on a ftp via filesystem watcher then move to another dir. Now I trigger the copy off the create event of the filesystem watcher but obviously in the case of ftp the create is just a stub file and the data comes in and fills the file as it uploads till complete. Anyone have an elegant solution for this, or do I have to do what I think I have to do
```
1 wait till last access time is about n ms in past before I copy
2 throw a control file in there to state that that file is done being copied, then delete control file
3 pound the crap out of it
``` | this is a very naive implementation but it suits my purposes, i have seen enough people with this problem on the web so decided to contribute. The implementation is fairly specific to my needs I almost completely unconcerned with changed events given the nature of my problem but people can throw their own code in there if they need to do something different, it really the created which cause the most issues. I havent fully tested this but at first write it looks good
```
using System;
using System.Collections.Generic;
using System.IO;
using System.Timers;
namespace FolderSyncing
{
public class FTPFileSystemWatcher
{
private readonly string _path;
public event FileSystemEventHandler FTPFileCreated;
public event FileSystemEventHandler FTPFileDeleted;
public event FileSystemEventHandler FTPFileChanged;
private Dictionary<string, LastWriteTime> _createdFilesToCheck;
private readonly object _lockObject = new object();
private const int _milliSecondsSinceLastWrite = 5000;
private const int _createdCheckTimerInterval = 2000;
private readonly FileSystemWatcher _baseWatcher;
public FTPFileSystemWatcher(string path, string Filter)
{
_path = path;
_baseWatcher = new FileSystemWatcher(path,Filter);
SetUpEventHandling();
}
public FTPFileSystemWatcher(string path)
{
_path = path;
_baseWatcher = new FileSystemWatcher(path);
SetUpEventHandling();
}
private void SetUpEventHandling()
{
_createdFilesToCheck = new Dictionary<string, LastWriteTime>();
Timer copyTimer = new Timer(_createdCheckTimerInterval);
copyTimer.Elapsed += copyTimer_Elapsed;
copyTimer.Enabled = true;
copyTimer.Start();
_baseWatcher.EnableRaisingEvents = true;
_baseWatcher.Created += _baseWatcher_Created;
_baseWatcher.Deleted += _baseWatcher_Deleted;
_baseWatcher.Changed += _baseWatcher_Changed;
}
void copyTimer_Elapsed(object sender, ElapsedEventArgs e)
{
lock (_lockObject)
{
Console.WriteLine("Checking : " + DateTime.Now);
DateTime dateToCheck = DateTime.Now;
List<string> toRemove = new List<string>();
foreach (KeyValuePair<string, LastWriteTime> fileToCopy in _createdFilesToCheck)
{
FileInfo fileToCheck = new FileInfo(_path + fileToCopy.Key);
TimeSpan difference = fileToCheck.LastWriteTime - fileToCopy.Value.Date;
fileToCopy.Value.Update(fileToCopy.Value.Date.AddMilliseconds(difference.TotalMilliseconds));
if (fileToCopy.Value.Date.AddMilliseconds(_milliSecondsSinceLastWrite) < dateToCheck)
{
FileSystemEventArgs args = new FileSystemEventArgs(WatcherChangeTypes.Created, _path, fileToCopy.Key);
toRemove.Add(fileToCopy.Key);
InvokeFTPFileCreated(args);
}
}
foreach (string removal in toRemove)
{
_createdFilesToCheck.Remove(removal);
}
}
}
void _baseWatcher_Changed(object sender, FileSystemEventArgs e)
{
InvokeFTPFileChanged(e);
}
void _baseWatcher_Deleted(object sender, FileSystemEventArgs e)
{
InvokeFTPFileDeleted(e);
}
void _baseWatcher_Created(object sender, FileSystemEventArgs e)
{
if (!_createdFilesToCheck.ContainsKey(e.Name))
{
FileInfo fileToCopy = new FileInfo(e.FullPath);
_createdFilesToCheck.Add(e.Name,new LastWriteTime(fileToCopy.LastWriteTime));
}
}
private void InvokeFTPFileChanged(FileSystemEventArgs e)
{
FileSystemEventHandler Handler = FTPFileChanged;
if (Handler != null)
{
Handler(this, e);
}
}
private void InvokeFTPFileDeleted(FileSystemEventArgs e)
{
FileSystemEventHandler Handler = FTPFileDeleted;
if (Handler != null)
{
Handler(this, e);
}
}
private void InvokeFTPFileCreated(FileSystemEventArgs e)
{
FileSystemEventHandler Handler = FTPFileCreated;
if (Handler != null)
{
Handler(this, e);
}
}
}
public class LastWriteTime
{
private DateTime _date;
public DateTime Date
{
get { return _date; }
}
public LastWriteTime(DateTime date)
{
_date = date;
}
public void Update(DateTime dateTime)
{
_date = dateTime;
}
}
}
``` | Wait until you can exclusively open the file- I wouldn't go as far to say that it is a nice solution, but probably the safest strategy in the circumstances. | C# FileSystemWatcher And FTP | [
"",
"c#",
"ftp",
"filesystemwatcher",
""
] |
Are there advantages to either approach? If I need to traverse List items and perform an action on each one, should I use the traditional foreach loop mechanism or move on to List.ForEach?
Matthew Podwysocki @ CodeBetter.com wrote an interesting article about the [anti-for campaign](http://codebetter.com/blogs/matthew.podwysocki/archive/2009/06/26/the-anti-for-campaign.aspx). This got me thinking about the problem a loop is trying to solve. In this article, Matthew argues that explicit loop structures make you think about the 'how' instead of the 'what'.
What are some good reasons to use one over the other (if there are any)? | For one thing, you'd use it if you'd been passed the delegate to apply for whatever reason. For example, you might create your own list, populate it etc and then apply a delegate to each entry. At that point, writing:
```
list.ForEach(action);
```
is simpler than
```
foreach (Item item in list)
{
action(item);
}
``` | I found List.ForEach to be significantly faster. Here are the results of the last four runs of the (now revised) performance test:
```
NativeForLoop: 00:00:04.7000000
ListDotForEach: 00:00:02.7160000
---------------------------------------
NativeForLoop: 00:00:04.8660000
ListDotForEach: 00:00:02.6560000
---------------------------------------
NativeForLoop: 00:00:04.6240000
ListDotForEach: 00:00:02.8160000
---------------------------------------
NativeForLoop: 00:00:04.7110000
ListDotForEach: 00:00:02.7190000
```
Each test was executed with one hundred million (100,000,000) iterations. I updated the test to use a custom class (Fruit) and have each loop access and work with a member inside the current object. Each loop is performing the same task.
Here is the entire source of the test class:
```
class ForEachVsClass
{
static Int32 Iterations = 1000000000;
static int Work = 0;
public static void Init(string[] args)
{
if (args.Length > 0)
Iterations = Int32.Parse(args[0]);
Console.WriteLine("Iterations: " + Iterations);
}
static List<Fruit> ListOfFruit = new List<Fruit> {
new Fruit("Apple",1), new Fruit("Orange",2), new Fruit("Kiwi",3), new Fruit("Banana",4) };
internal class Fruit {
public string Name { get; set; }
public int Value { get; set; }
public Fruit(string _Name, int _Value) { Name = _Name; Value = _Value; }
}
[Benchmark]
public static void NativeForLoop()
{
for (int x = 0; x < Iterations; x++)
{
NativeForLoopWork();
}
}
public static void NativeForLoopWork()
{
foreach (Fruit CurrentFruit in ListOfFruit) {
Work+=CurrentFruit.Value;
}
}
[Benchmark]
public static void ListDotForEach()
{
for (int x = 0; x < Iterations; x++)
{
ListDotForEachWork();
}
}
public static void ListDotForEachWork()
{
ListOfFruit.ForEach((f)=>Work+=f.Value);
}
```
}
Here is the resulting IL for the work methods (extracted to make them easier to read):
```
.method public hidebysig static void NativeForLoopWork() cil managed
{
.maxstack 2
.locals init (
[0] class ForEachVsClass/Fruit CurrentFruit,
[1] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class ForEachVsClass/Fruit> CS$5$0000)
L_0000: ldsfld class [mscorlib]System.Collections.Generic.List`1<class ForEachVsClass/Fruit> ForEachVsClass::ListOfFruit
L_0005: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> [mscorlib]System.Collections.Generic.List`1<class ForEachVsClass/Fruit>::GetEnumerator()
L_000a: stloc.1
L_000b: br.s L_0026
L_000d: ldloca.s CS$5$0000
L_000f: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator<class ForEachVsClass/Fruit>::get_Current()
L_0014: stloc.0
L_0015: ldsfld int32 ForEachVsClass::Work
L_001a: ldloc.0
L_001b: callvirt instance int32 ForEachVsClass/Fruit::get_Value()
L_0020: add
L_0021: stsfld int32 ForEachVsClass::Work
L_0026: ldloca.s CS$5$0000
L_0028: call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator<class ForEachVsClass/Fruit>::MoveNext()
L_002d: brtrue.s L_000d
L_002f: leave.s L_003f
L_0031: ldloca.s CS$5$0000
L_0033: constrained [mscorlib]System.Collections.Generic.List`1/Enumerator<class ForEachVsClass/Fruit>
L_0039: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_003e: endfinally
L_003f: ret
.try L_000b to L_0031 finally handler L_0031 to L_003f
}
.method public hidebysig static void ListDotForEachWork() cil managed
{
.maxstack 8
L_0000: ldsfld class [mscorlib]System.Collections.Generic.List`1<class ForEachVsClass/Fruit> ForEachVsClass::ListOfFruit
L_0005: ldsfld class [mscorlib]System.Action`1<class ForEachVsClass/Fruit> ForEachVsClass::CS$<>9__CachedAnonymousMethodDelegate1
L_000a: brtrue.s L_001d
L_000c: ldnull
L_000d: ldftn void ForEachVsClass::<ListDotForEachWork>b__0(class ForEachVsClass/Fruit)
L_0013: newobj instance void [mscorlib]System.Action`1<class ForEachVsClass/Fruit>::.ctor(object, native int)
L_0018: stsfld class [mscorlib]System.Action`1<class ForEachVsClass/Fruit> ForEachVsClass::CS$<>9__CachedAnonymousMethodDelegate1
L_001d: ldsfld class [mscorlib]System.Action`1<class ForEachVsClass/Fruit> ForEachVsClass::CS$<>9__CachedAnonymousMethodDelegate1
L_0022: callvirt instance void [mscorlib]System.Collections.Generic.List`1<class ForEachVsClass/Fruit>::ForEach(class [mscorlib]System.Action`1<!0>)
L_0027: ret
}
``` | When would I use List<T>.ForEach over a native foreach loop? | [
"",
"c#",
"collections",
"design-patterns",
""
] |
I need to replace Microsoft Word's version of single and double quotations marks (`“ ” ‘ ’`) with regular quotes (' and ") due to an encoding issue in my application. I do not need them to be HTML entities and I cannot change my database schema.
I have two options: to use either a regular expression or an associated array.
Is there a better way to do this? | Considering you only want to replace a few specific and well identified characters, I would go for [`str_replace`](http://www.php.net/str_replace) with an array: you obviously don't need the heavy artillery regex will bring you ;-)
And if you encounter some other special characters (damn copy-paste from Microsoft Word...), you can just add them to that array whenever is necessary / whenever they are identified.
The best answer I can give to your comment is probably this link: [Convert Smart Quotes with PHP](http://shiflett.org/blog/2005/oct/convert-smart-quotes-with-php)
And the associated code *(quoting that page)*:
```
function convert_smart_quotes($string)
{
$search = array(chr(145),
chr(146),
chr(147),
chr(148),
chr(151));
$replace = array("'",
"'",
'"',
'"',
'-');
return str_replace($search, $replace, $string);
}
```
*(I don't have Microsoft Word on this computer, so I can't test by myself)*
I don't remember exactly what we used at work *(I was not the one having to deal with that kind of input)*, but it was the same kind of stuff... | I have found an answer to this question. You need just one line of code using `iconv()` function in php:
```
// replace Microsoft Word version of single and double quotations marks (“ ” ‘ ’) with regular quotes (' and ")
$output = iconv('UTF-8', 'ASCII//TRANSLIT', $input);
``` | How to replace Microsoft-encoded quotes in PHP | [
"",
"php",
"string",
"encoding",
"character-encoding",
""
] |
I create fullscreen interactive demos in Flash and have recently been looking to migrate to a new language. My Flash demos are basically software prototypes and operate in a projector EXE, outside of the browser. I want to leave Flash for a variety of reasons, including:
* Poor quality control in the Flash player
* Hardware acceleration issues on both nVidia and ATI resulting in repeateable BSODs
* Not enough low-level access to file-system, network
In finding a new platform, I need the ability to develop for the following requirements:
* Cross-platform (just Mac and PC)
* 100% graphics (32-bit transparent PNG) based UI
* Fullscreen exclusive mode (if possible, ability to adjust user's screen resolution)
* High-quality media playback
+ H.264/AAC MPEG-4 video up to 1920x1080
+ WAV & MP3 audio
* Basic UI components - ScrollBar, TextField, etc (preferably skinnable/extensible)
* 3D capabilities
I would appreciate any recommendations you could make on languages, frameworks, books, websites, etc. I am more knowledgable in Java than in C/C++, so it would be nice to see more recommendations there. | # [Processing](http://processing.org/)
I think your best answer is [Processing](http://processing.org/) given your familiarity with Java. Processing is used to create many demos and cutting edge graphics applications. Processing is built in Java but has a proprietary language that is very easy to use, and you can use straight Java as well. I don't know if it has a specific widget library, but certainly it is easy enough to build yourself. Check out some of the [Processing exhibitions](http://processing.org/exhibition/) for a look at its power and flexibility.
## [The Simple Directmedia Layer](http://www.libsdl.org/)
For true cross platform speed and hardware access you could look at something like the [Simple DirectMedia Layer](http://www.libsdl.org/). The SDL is a cross platform library used for demos and games. It has 2d and 3d support as well as device access. It will run on Windows, Linux, Mac and countless other variations of hardware and software. It is written in C to make it easily cross platform, but you can code C++ or use the bindings for Python, Java, or Ruby if you are looking for something different. The SDL doesn't come with a built-in widget library, I don't believe, but there are many listed on their site under the [SDL Interface category of libraries](http://www.libsdl.org/libraries.php?category=14).
## [Qt](http://qt.nokia.com/)
Another option is [Qt](http://qt.nokia.com/) which is a cross platform widget library recently purchased by Nokia. Nokia is an odd owner, but the library is licensed under [LGPL](http://www.gnu.org/licenses/lgpl-2.1.html) and it offers everything you would need. I am not familiar with building graphically intense demos under Qt, but their documentation makes it sound feasible.
## [openFrameworks](http://www.openframeworks.cc/)
[openFrameworks](http://www.openframeworks.cc/) is also used to for demos and cutting edge graphics and hardware applications. openFrameworks is written in C++ and is not so easy for less experienced developers. It does not have a specific widget library, and it is still in an alpha release state. I have not dug deeply into openFrameworks yet but it is much more advanced and tailored for advanced applications such as the ones tagged [openFrameworks on Vimeo](http://vimeo.com/tag:openframeworks). | The traditional competitor to Flash is [Silverlight](http://silverlight.net/). | Transitioning Away from Flash | [
"",
"java",
"flash",
"actionscript-3",
"3d",
"actionscript-2",
""
] |
I have VS2005 and .net 3.5 installed on my machine I have heard of WPF and want to practice WPF solutions what other software should I install to write WPF program in VS2005 as it does not show any option for the same by default.
Also any link for some cool stuff for beginners on WPF will be very helpful.
Please help | You can get them from here: <http://download.cnet.com/The-Visual-Studio-2005-extensions-for-NET-Framework-3-0-WCF-WPF-November-2006-CTP/3000-10250_4-10727672.html>.
This was the last version Microsoft released before telling everyone to go with VS2008. If you can't do VS2008, this is an ok solution. We used it for a year and a half and have production UIs running based on it. The problems are that the designer is basically non-existent (so be ready to code XAML by hand), it can be a bit slow, and there's some bugs.
Re: 3.5, VS 2005 is incapable of handling 3.5 projects, linq, etc. If you really want, you can work outside of VS and just use msbuild 3.5. An interesting fact: .Net 3.5 replaces, among some libraries, the PresentationFramework assembly. The new version of this assembly includes additional methods and method signatures that are not included in .Net 3.0. **This means that these new 3.5 methods will be accessible in VS2005.** | Vinay,
i don't think 2005 can do WPF and it definitely cannot handle .Net 3.5. VS2005 is 2.0.
Start with downloading VS2008 Express. It's free and will have the tools you need to get started with WPF.
<http://www.microsoft.com/express/download/> | What software do i need to install to use WPF in VS2005 | [
"",
"c#",
".net",
"asp.net",
"wpf",
""
] |
here's my problem:
1. User inputs a password in the Options section of the program.
2. The password is hashed (MD5) and stored in the registry.
3. The program is ran, an Excel spreadsheet is created, and password protected using the hashed value that is stored in the registry.
4. The user opens the spreadsheet, and is prompted to enter the password.
5. The user enters the password, but it fails no matter what.
The reason it fails is because the user is inputting the password in cleartext, yet the function is comparing it to a hashed value, which it will obviously error out.
How can I hash the Excel password that is being entered when accessing the spreadsheet in order to compare it with the stored hash in the Registry?
Any ideas on working around this would also be appreciated.
I'm writing this in C# using Excel Interop...
Thanks...
Woody | Your program will have to provide the password, because the user doesn't know what it is!
Fortunately, the `Excel.Workbooks.Open` method takes an argument permitting you to specify the password required. So your code could get the hashed password from the registry (or from wherever you are storing it) and then open the wokrbook via code:
```
string fileName = @"C:\...";
string password = GetHashedPasswordFromRegistry();
Excel.Workbook workbook = excelApp.Workbooks.Open(
fileName, Type.Missing, Type.Missing,Type.Missing,
password, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
```
I think this should do what you're looking for? Let us know how it goes...
Mike | Like this:
```
using System;
using System.Security.Cryptography;
using System.Text;
public static class Helpers
{
public static Guid GetHash(string password)
{
return new Guid(new MD5CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(password.Trim())));
}
}
```
usage:
```
string hash = Helpers.GetHash("password").ToString();
``` | Comparing hashes when entering Excel password | [
"",
"c#",
"excel",
"hash",
"passwords",
""
] |
I'm going to be working with a C++ library written in plain C++ (not .NET and without MFC). The library is available compiled using both Visual Studio 2005 / Intel Fortran 9.1 and VS 2008 / Intel Fortran 10.1.
Obviously I'm going to grab the binaries for VS 2008 since that's the environment on my computer but I'm curious if there are reasons why a straight C++ library wouldn't be compatible between VS 2005 and 2008. I'd assume that the name-mangling would be the same but maybe there are other reasons. I haven't used C++ in a long time so I'm a little rusty when it comes to these things. | The biggest issue you will run into is the usage of the CRT. If the CRT (C RunTime) is statically linked into the DLL, you shouldn't have any issues.
However if the CRT is dynamically linked into the project you may run into trouble. Visual Studio 2005 and 2008 use different versions of the CRT and they cannot easily be loaded togeter. But if one or both of the DLL's statically links the CRT you should be in decent shape. | It should probably work. The DLL compiled with VS 2005 will be dependent on VS 2005's implementation of the C standard library (`msvcr80.dll`), whereas your code will depend on VS 2008's C library (`msvcr90.dll`). This means that at runtime, both versions of the C libraries will be loaded, which is ok, but it increases your memory usage and slows down your load time by a very small amount. | Can a C++ dll compiled using Visual Studio 2008 be used with Visual Studio 2005? | [
"",
"c++",
"windows",
"visual-studio",
"visual-studio-2008",
"visual-studio-2005",
""
] |
Where can I find information like how to make input text, input password, radiobutton, checkbox and textarea in a software made with java? | [Here is a good set of Sun tutorials.](http://java.sun.com/docs/books/tutorial/uiswing/TOC.html) | It depends on the GUI toolkit you are using.
You've tagged this HTML, so if you are generating webpages — just output the HTML for the form controls you want.
<http://www.w3.org/TR/html4/interact/forms.html> | input text, input password, radiobutton, checkbox, textarea etc in java | [
"",
"java",
"html",
""
] |
I know there are several other posts on this topic but they still leave me confused.
I've included jQuery and everything and,
I have a simple javascript class like this example:
```
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph=fillKph;
}
function fillKph(){
$("#kphdiv").html(this.speed*1.61);
}
car1 = new CarConstructor();
car1.fillKph();
```
Now I know that that code snippet doesn't work and is not properly consturcted.
The "this" keyword there is referencing my dom element with the id of "kphdiv".
The question I have is what is the best way to handle this.
Ive seen one method where you set some variable equal to this (binding it) and then use that variable to reference your object. For example:
```
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph=fillKph;
}
function fillKph(){
var me=this;
$("#kphdiv").html(me.speed*1.61);
}
car1 = new CarConstructor();
car1.fillKph();
```
I could also make the me a global variable ... I don't know.
I was just curious if there is another/better way. | Oh boy, you are confusing quite a few things.
```
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph; // <-> This particular statement has no meaning.
//When you write this.fillKph without any assignment, it will be 'undefined'.
//Just because you have a function named 'fillKph' somewhere else,
//it doesn't mean it will get attached to this property.
}
```
Try,
```
var toyota = new Car();
alert(typeof toyota.fillKph); //will alert undefined.
```
The fillKph function is created in global scope, i.e. as property of 'Window' object.
```
function fillKph(){
var me=this;
$("#kphdiv").html(me.speed*1.61);
}
```
To fix it, you can what rezzif suggested. Your final code will look like
```
function Car()
{
this.speed=19; // in mph
this.make="Ford";
this.fillKph = function (){
$("#kphdiv").html(this.speed*1.61);
};
}
car1 = new Car();
car1.fillKph();
```
If you notice, I did not store reference to 'this' inside a local variable. Why? There is no need in this scenario. To understand more, see [my detailed answer here](https://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work/1162192#1162192).
If you are going to create lot of Car objects, you can define the fillKph method on the prototype.
```
function Car()
{
this.speed=19; // in mph
this.make="Ford";
}
Car.prototype.fillKph = function fillKph() { $("#kphdiv").html(this.speed*1.61); };
car1 = new Car();
car1.fillKph();
```
**EDIT:**
If you do something like,
```
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph = fillKph;
}
function fillKph(){
$("#kphdiv").html(me.speed*1.61);
}
car1 = new Car();
car1.fillKph(); //This will work as expected.
```
But the problem is that fillKph is defined in 'Window' scope, so I can directly call it like,
```
fillKph(); //Calling it this way will break it as it won't get correct 'this'.
```
Point is,
```
alert(typeof fillKph); // alerts 'function' if you do it your way,
alert(typeof fillKph); // alerts 'undefined', if you do it the way I suggested, which is preferred in my opinion.
``` | ```
function CarConstructor(){
var _this = this;
this.speed=19; // in mph
this.make="Ford";
this.fillKph = function (){
$("#kphdiv").html(_this.speed*1.61);
};
}
car1 = new CarConstructor();
car1.fillKph();
``` | How does 'this' work in JavaScript? | [
"",
"javascript",
"this",
""
] |
I have been trying, unsuccessfully, to get a HTML page to load an external GZIP compressed javascript file from the local filesystem using a HTML file such as this:
```
<html>
<head>
<script src="test.js.gz" type="text/javascript"></script>
</head>
<body></body>
</html>
```
When I open this HTML file directly in a browser, the Javascript file is not decompressed, but just included as-is. Since there is no webserver to tell the browser that the data is compressed, I was wondering if anyone knew of any other way of getting a setup such as this working? (the final result will not be running of a webserver). | GZIP (de)compression of files is part of the HTTP/1.1 protocol which isn't used by browsers for loading local files. So I think the short answer is no. Sorry!
You could resort to uncompressed files, or decompress them before loading the web page, or running an HTTP daemon (web server) on the local machine which serves files to the web browser.
Hope that helps | No, there isn't.
I assume you are doing this for testing — in which case, don't worry. A properly configured web server will gzip files on the fly (and cache them). You don't need to link to a .js.gz version. | Is it possible to load gzip compressed javascript without a webserver? | [
"",
"javascript",
"html",
"gzip",
""
] |
I am working on a mutual exclusion assignment, but when I started I noticed my application's thread ID's start at 9. It doesn't change when I compile and execute it again. Is there some problem I'm missing, or can Java Thread IDs start at an arbitrary number? [This question](https://stackoverflow.com/questions/591627/thread-getid-global-uniqueness-question) is related.
---
For those interested, here is a class from Herlihy & Shavit's "The Art of Multiprocessor Programming" for numbering threads:
```
public class ThreadID {
private static volatile int nextID = 0;
private static class ThreadLocalID extends ThreadLocal<Integer> {
protected synchronized Integer initialValue() {
return nextID++;
}
}
private static ThreadLocalID threadID = new ThreadLocalID();
public static int get() {
return threadID.get();
}
public static void set(int index) {
threadID.set(index);
}
}
```
You can then call
```
ThreadID.get();
```
which will automatically increment numbers and always start at 1. | From the [`Thread#getId()`](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getId()) documentation:
> Returns the identifier of this Thread.
> The thread ID is a positive long
> number generated when this thread was
> created. The thread ID is unique and
> remains unchanged during its lifetime.
> When a thread is terminated, this
> thread ID may be reused.
Nothing indicates that it is guaranteed will start at 0. I would guess that, internally, Java makes several Thread objects before the first one that you create, and thus the thread IDs 0–8 are already occupied. However, nothing in the documentation guarantees that this number will be in any way sequential (though that's how it is current implemented), so you should not depend on that. | Yes. But the thread ID is shared by whole JVM so for you application it could start from any number. | Should Java Thread IDs always start at 0? | [
"",
"java",
"multithreading",
"numbers",
""
] |
Initially I thought I needed this, but I eventually avoided it. However, my curiosity (and appetite for knowledge, hum) make me ask:
Can a preprocessor macro, for instance in
```
#include "MyClass.h"
INSTANTIATE_FOO_TEMPLATE_CLASS(MyClass)
```
expand to another include, like in
```
#include "MyClass.h"
#include "FooTemplate.h"
template class FooTemplate<MyClass>;
```
? | I believe that cannot be done, this is because the pre-processor is **single pass**. So it cannot emit other preprocessor directives.
Specifically, from the C99 Standard (6.10.3.4 paragraph 3):
> 3 The resulting completely
> macro-replaced preprocessing token
> sequence is not processed as a
> preprocessing directive even if it
> resembles one, ...
Interestingly enough, This is why the unary `_Pragma` operator was added to c99. Because `#pragma` could not be emited by macros, but `_Pragma` can. | The C standard says this about preprocessing directives (C99 - 6.10(2) - Preprocessing directives):
> A preprocessing directive consists of a sequence of preprocessing tokens that begins with
> a # preprocessing token that (at the start of translation phase 4)
> ...
and (C99 - 6.10(7)):
> The preprocessing tokens within a preprocessing directive are not subject to macro
> expansion unless otherwise stated.
>
> EXAMPLE In:
>
> ```
> #define EMPTY
> EMPTY # include <file.h>
> ```
>
> the sequence of preprocessing tokens on the second line is not a preprocessing directive, because it does not begin with a # at the start of translation phase 4, even though it will do so after the macro EMPTY has been replaced
So, no, macros cannot expand into a '`#include`' preprocessing directive. Those directives need to be in place at the start of translation phase 4 (when handling those directives takes place preprocessing happens). Since macro expansion occurs during phase 4, macros can't cause something to exist at the start of phase 4.
I'd like to point out however, that the following **does** work:
```
#ifdef WIN32
#define PLATFORM_HEADER "platform/windows/platform.h"
#else
#define PLATFORM_HEADER "platform/linux/platform.h"
#include PLATFORM_HEADER
```
because the C standard says this (C99, 6.10.2(4) - Source file inclusion):
> A preprocessing directive of the form
>
> ```
> # include pp-tokens new-line
> ```
>
> (that does not match one of the two previous forms) is permitted. The preprocessing
> tokens after include in the directive are processed just as in normal text. (Each
> identifier currently defined as a macro name is replaced by its replacement list of
> preprocessing tokens.) | Preprocessor macro expansion to another preprocessor directive | [
"",
"c++",
"macros",
"c-preprocessor",
"expansion",
"preprocessor-directive",
""
] |
I am looking for some JavaScript simple samples to compute elapsed time. My scenario is, for a specific point of execution in JavaScript code, I want to record a start time. And at another specific point of execution in JavaScript code, I want to record an end time.
Then, I want to calculate the elapsed time in the form of: how many Days, Hours, Minutes and Seconds are elapsed between end time and start time, for example: `0 Days, 2 Hours, 3 Minutes and 10 Seconds are elapsed`.
Any reference simple samples? :-)
Thanks in advance,
George | Hope this will help:
```
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>compute elapsed time in JavaScript</title>
<script type="text/javascript">
function display_c (start) {
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh = 1000; // Refresh rate in milli seconds
if( window.start >= end ) {
mytime = setTimeout( 'display_ct()',refresh )
} else {
alert("Time Over ");
}
}
function display_ct () {
// Calculate the number of days left
var days = Math.floor(window.start / 86400);
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start - (days * 86400 ))/3600)
// After days and hours , how many minutes are left
var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes.
var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))
var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";
document.getElementById('ct').innerHTML = x;
window.start = window.start - 1;
tt = display_c(window.start);
}
function stop() {
clearTimeout(mytime);
}
</script>
</head>
<body>
<input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
<span id='ct' style="background-color: #FFFF00"></span>
</body>
</html>
``` | Try something like this ([FIDDLE](http://jsfiddle.net/cckSj/5/))
```
// record start time
var startTime = new Date();
...
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the ms
timeDiff /= 1000;
// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
var minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
var hours = Math.round(timeDiff % 24);
// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);
// the rest of timeDiff is number of days
var days = timeDiff ;
``` | Compute elapsed time | [
"",
"javascript",
"datetime",
""
] |
Suppose I have an array in PHP that looks like this
```
array
(
array(0)
(
array(0)
(
.
.
.
)
.
.
array(10)
(
..
)
)
.
.
.
array(n)
(
array(0)
(
)
)
)
```
And I need all the leaf elements of this mulit-dimensional array into a linear array, how should I go about doing this without resorting recursion, such like this?
```
function getChild($element)
{
foreach($element as $e)
{
if (is_array($e)
{
getChild($e);
}
}
}
```
Note: code snippet above, horribly incompleted
Update: example of array
```
Array
(
[0] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 5000000
[balance:private] => 4998970
[queueid:private] => 0
[sellerid:private] => 2
[dateTime:private] => 2009-07-25 17:53:10
)
)
)
```
...snipped.
```
[2] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 10000000
[balance:private] => 9997940
[queueid:private] => 135
[sellerid:private] => 234
[dateTime:private] => 2009-07-14 23:36:00
)
)
....snipped....
)
```
) | Actually, there is a single function that will do the trick, check the manual page at: <http://php.net/manual/en/function.array-walk-recursive.php>
Quick snippet adapted from the page:
```
$data = array('test' => array('deeper' => array('last' => 'foo'), 'bar'), 'baz');
var_dump($data);
function printValue($value, $key, $userData)
{
//echo "$value\n";
$userData[] = $value;
}
$result = new ArrayObject();
array_walk_recursive($data, 'printValue', $result);
var_dump($result);
``` | You could use iterators, for example:
```
$result = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::LEAVES_ONLY) as $value) {
$result[] = $value;
}
``` | Extract leaf nodes of multi-dimensional array in PHP | [
"",
"php",
"arrays",
""
] |
[Sorry for long question but it is necessary to explain the problem]
I am working on a learning website and it is supposed to show a list of messages to user if there are any. Something like this:
[](https://i.stack.imgur.com/AP9li.png)
When user presses close button, that message must be marked "read" and should not be shown next time. Following code is used to generate those messages:
```
<% foreach (var m in Model.UserMessages) { %>
<div class="um" id="m<%=Html.AttributeEncode(m.ID) %>">
<p class="mh"><%= Html.Encode (String.Format ("From {0} ({1})", m.From, m.Sent)) %></p>
<p><%= Html.Encode (m.Text) %></p>
<% using (Html.BeginForm ("CloseMessage", "Home", new { id = m.ID })) { %>
<input type="submit" value="Close<%= Html.AttributeEncode (m.ID) %>" id="c<%= Html.AttributeEncode (m.ID) %>"/>
<% } %>
</div>
<% } %>
```
After that, following the guidelines, I added the support of http post method in controller which marks the message as read and then refreshes the view (to handle disabled JavaScript):
```
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CloseMessage (int id) {
using (var dl = new DL ()) {
dl.MarkAsRead (id);
}
if (Request.IsAjaxRequest ()) {
return new EmptyResult ();
}
else {
return RedirectToAction ("Index");
}
}
```
Then I wanted to add JavaScript support such that only the message goes away (using jQuery). But the problem is that I am generating the buttons and messages programmatically.
So ended up with a weird looking javascript code in viewpage:
```
<script type="text/javascript">
$().ready(function() {
<% foreach (var m in Model.UserMessages) { %>
$("#c<%=Html.AttributeEncode (m.ID) %>").click(function(event) {
$.post("Home/CloseMessage/<%=Html.AttributeEncode (m.ID) %>");
$("#m<%=Html.AttributeEncode (m.ID) %>").slideUp("slow");
event.preventDefault();
});
<% } %>
});
</script>
```
This is basically creating the javascript code in a C# loop which actually works but too much for me to digest. Is there any better way of doing this? | You could just create one javascript function that takes the element IDs as parameters :
```
function myFunction(ID) {
$.post("Home/CloseMessage/" + ID);
$("#m" + ID).slideUp("slow");
}
```
And :
```
<% foreach (var m in Model.UserMessages) { %>
<div class="um" id="m<%=Html.AttributeEncode(m.ID) %>">
<p class="mh"><%= Html.Encode (String.Format ("From {0} ({1})", m.From, m.Sent)) %></p>
<p><%= Html.Encode (m.Text) %></p>
<% using (Html.BeginForm ("CloseMessage", "Home", new { id = m.ID })) { %>
<input type="submit" value="Close<%= Html.AttributeEncode (m.ID) %>"
id="c<%= Html.AttributeEncode (m.ID) %>"
onclick="myFunction('<%=Html.AttributeEncode(m.ID)%>')"/>
<% } %>
</div>
<% } %>
``` | YOu could uses a CSS selector in your JS to get all buttons with a particular class assigned to them. Then you can wire up you click event to them. So your HTML would be something like this:
```
<% foreach (var m in Model.UserMessages) { %>
<div class="um" id="m<%=Html.AttributeEncode(m.ID) %>">
<p class="mh"><%= Html.Encode (String.Format ("From {0} ({1})", m.From, m.Sent)) %></p>
<p><%= Html.Encode (m.Text) %></p>
<% using (Html.BeginForm ("CloseMessage", "Home", new { id = m.ID })) { %>
<input type="submit" class="MyCloseButton" value="Close<%= Html.AttributeEncode (m.ID) %>" id="c<%= Html.AttributeEncode (m.ID) %>"/>
<% } %>
</div>
<% } %>
```
I've only added the class="MyCloseButton" to your input
Then in your JS (I use mootools but JQuery has CSS selectors too but you will need to port it sorry) you can do something like this:
```
window.addEvent( "domready", function() {
$$("input.MyCloseButton").each( function( button ) {
// Add your code here, you can reference button.id etc for each of your buttons
}
});
```
This way you only have to write out one little function in plan JS and not worry about doing it server-side, all you need to do it decorate your buttons with a css class so the JS can find them. | Is it right to generate the javascript using C# in ASP.NET MVC view page? | [
"",
"javascript",
"jquery",
"asp.net-mvc",
"viewpage",
""
] |
When I define constant values in my Java code, I generally declare them 'private static final', but recently I've been maintaining code where the constants are defined 'private final'.
I'm optimizing at the moment and was wondering whether to 'static'ize these.
For example
```
public class X {
private final String SOME_CONST = "Whatever";
}
```
Is the above code equivalent (at run-time) to the following, so only 1 copy of 'SOME\_CONST' is held?
```
public class X {
private static final String SOME_CONST = "Whatever";
}
```
I would have thought this was fairly basic, but I can't find the answer anywhere.
[Edit]
Some people have answered on the String instance being interned. Sorry, I should have picked a better example, in the case I'm looking at, it's not just Strings, but a lot of different types (some standard, some user defined).
I'm more interested in the effects of the 'private final' versus a 'private static final' declaration. | [FindBugs](http://findbugs.sourceforge.net/) helpfully points out that such a final member should be static. One could infer from that that the optimization doesn't take place. | When `SOME_CONST` is declared **non-static**, the virtual machine will create one `String` instance whose content is `"Whatever"`. However, all instances of the `X` class will contain a reference to this `String` object. Therefore, there is only one instance of your `String`, but many references to it.
It would probably be worthwhile to make that field static so as to avoid the unnecessary references. | Do final members assigned constants on declaration get optimized at run-time to 'static final's? | [
"",
"java",
"optimization",
""
] |
I have an Excel sheet in which the first row contains title for all the columns. I want all the names in the first row.
What is the SQL command for reading all the entries in the first row?
If possible, I want to define the max-limit.
In addition: I want to enumerate all the column names. | This works for me in Excel using a saved workbook, and it enumerates the column (field) names.
```
Sub ListFieldADO()
strFile = Workbooks(1).FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
''You can also use the name of a named range
Set rs = cn.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, "Sheet1$"))
While Not rs.EOF
Debug.Print " " & rs!Column_Name
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
End Sub
``` | You need to mention "HDR=No;" in your connection string. Then you can use the following query:
```
Select Top 1 * from [SheetName$]
```
"HDR=No" will specify that the first row DOES NOT contains the column names.
Being said that, I don't know if there is a SQL statement to get the column names from a table. If there is, then you can have HDR=Yes in the connection string and use that SQL statement. | SQL command for reading all columns in the first row | [
"",
"sql",
"mysql",
"sql-server",
"excel",
""
] |
guys, how or where is the "join" query in Django?
i think that Django dont have "join"..but how ill make join?
Thanks | If you're using models, the select\_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model. | Look into [model relationships](http://docs.djangoproject.com/en/dev/topics/db/models/#relationships) and [accessing related objects](http://docs.djangoproject.com/en/dev/ref/models/relations/#ref-models-relations). | Django .."join" query? | [
"",
"python",
"django",
""
] |
I have the following text that I am trying to parse:
```
"user1@emailaddy1.com" <user1@emailaddy1.com>, "Jane Doe" <jane.doe@ addyB.org>,
"joe@company.net" <joe@company.net>
```
I am using the following code to try and split up the string:
```
Dim groups As GroupCollection
Dim matches As MatchCollection
Dim regexp1 As New Regex("""(.*)"" <(.*)>")
matches = regexp1 .Matches(toNode.InnerText)
For Each match As Match In matches
groups = match.Groups
message.CompanyName = groups(1).Value
message.CompanyEmail = groups(2).Value
Next
```
But this regular expression is greedy and is grabbing the entire string up to the last quote after "joe@company.net". I'm having a hard time putting together an expression that will group this string into the two groups I'm looking for: Name (in the quotes) and E-Mail (in the angle brackets). Does anybody have any advice or suggestions for altering the regexp to get what I need? | Rather than rolling your own regular expression, I would do this:
```
string[] addresses = toNode.InnerText.Split(",");
foreach(string textAddress in addresses)
{
textAddress = address.Trim();
MailAddress address = new MailAddress(textAddress);
message.CompanyName = address.DisplayName;
message.CompanyEmail = address.Address;
}
```
While your regular expression may work for the few test cases that you have shown. Using the `MailAddress` class will probably be much more reliable in the long run. | How about `"""([^""]*)"" <([^>]*)>"` for the regex? I.e. make explicit that the matched part won't include a quote/closing paren. You may also want to use a more restrictive character-range instead. | How can I group multiple e-mail addresses and user names using a regular expression | [
"",
"c#",
"asp.net",
"vb.net",
"regex",
""
] |
I have an array in php like this:
$myArray = array('name'=>'juank', 'age'=>26, 'config'=>array('usertype'=>'admin','etc'=>'bla bla'));
I need this array to be accesible along the script to allow changes in any field EXCEPT in the "config" field. Is there a way to protect an array or part of an array from being modified as if it where declared private inside a class? I tried defining it as a constant but it's value changes during script execution. Implementing it as a class would mean I'd have to rebuild the complete application from scratch :S
thanks! | I do not think you can do this using "pure" "real" arrays.
One way to get to this **might** be using some class that implements [`ArrayInterface`](http://php.net/manual/en/class.arrayaccess.php) ; you code would look like it's using arrays... But it would actually be using objects, with accessor methods that could forbid write-access to some data, I guess...
It would have you **change a couple of things** *(creating a class, instanciating it)* ; **but not everything** : access would still be using an array-like syntax.
Something like this might do the trick *(adapted from the manual)* :
```
class obj implements arrayaccess {
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
if ($offset == 'one') {
throw new Exception('not allowed : ' . $offset);
}
$this->container[$offset] = $value;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$a = new obj();
$a['two'] = 'glop'; // OK
var_dump($a['two']); // string 'glop' (length=4)
$a['one'] = 'boum'; // Exception: not allowed : one
```
You have to instanciate an object with `new`, which is not very array-like... But, after that, you can use it as an array.
And when trying to write to an "locked" property, you can throw an Exception, or something like that -- btw, declaring a new `Exception` class, like `ForbiddenWriteException`, would be better : would allow to catch those specifically **:-)** | You could make the array private and create a method to modify its contents that will check if someone doesn't try to overwrite the `config` key.
```
<?php
class MyClass {
private static $myArray = array(
'config' => array(...),
'name' => ...,
...
);
public static function setMyArray($key, $value) {
if ($key != 'config') {
$this::myArray[$key] = $value;
}
}
}
```
Then when you want to modify the array you call:
```
MyClass::setMyArray('foo', 'bar'); // this will work
MyClass::setMyArray('config', 'bar'); // this will be ignored
``` | How can I protect part of an array in php from being modified? | [
"",
"php",
"arrays",
"private",
"protected",
""
] |
I'm pretty new to PHP, so if you have any thoughts or suggestions to point me in the right direction, I'd be grateful.
Trying to make a simple function to check if a user's email address translates into a valid Gravatar Image, but it seems gravatar.com has changed their headers.
Using `get_headers('urlencoded_bad_email@example.com')` returns a 200 instead of 302.
Here are the headers from a bad gravatar image, none of which seem to be able to help because they are identical to a valid gravatar image:
```
array(13) {
[0]=>
string(15) "HTTP/1.1 200 OK"
[1]=>
string(13) "Server: nginx"
[2]=>
string(35) "Date: Sun, 26 Jul 2009 20:22:07 GMT"
[3]=>
string(24) "Content-Type: image/jpeg"
[4]=>
string(17) "Connection: close"
[5]=>
string(44) "Last-Modified: Sun, 26 Jul 2009 19:47:12 GMT"
[6]=>
string(76) "Content-Disposition: inline; filename="5ed352b75af7175464e354f6651c6e9e.jpg""
[7]=>
string(20) "Content-Length: 3875"
[8]=>
string(32) "X-Varnish: 3883194649 3880834433"
[9]=>
string(16) "Via: 1.1 varnish"
[10]=>
string(38) "Expires: Sun, 26 Jul 2009 20:27:07 GMT"
[11]=>
string(26) "Cache-Control: max-age=300"
[12]=>
string(16) "Source-Age: 1322"
}
```
p.s. I am aware of the `'&d'` parameter, but it will not serve my purpose. :)
**EDIT:**
Use `'?d'` instead of `'&d'`. Must be a gravatar.com 'thang. | **NOTE**: at the time of writing, this was the only option. However, some later time `?d=404` was added, making [Andrew's answer](https://stackoverflow.com/questions/1185506/check-for-valid-gravatar-php/2131360#2131360) much cleaner.
---
Though you said you know about the [`d` parameter](http://en.gravatar.com/site/implement/url), do you know it actually returns a redirect header when applicable? So, the following [yields](http://web-sniffer.net/?url=http%3A%2F%2Fwww.gravatar.com%2Favatar%2F3b3be63a4c2a439b013787725dfce802%3Fd%3Dhttp%253A%252F%252Fwww.google.com%252Fimages%252Flogo.gif&submit=Submit&http=1.1&type=GET&uak=0) 302 Found because the avatar does not exist:
<http://www.gravatar.com/avatar/3b3be63a4c2a439b013787725dfce802?d=http%3A%2F%2Fwww.google.com%2Fimages%2Flogo.gif>
```
HTTP/1.1 302 Found
...
Last-Modified: Wed, 11 Jan 1984 08:00:00 GMT
Location: http://www.google.com/images/logo.gif
Content-Length: 0
...
Expires: Sun, 26 Jul 2009 23:18:33 GMT
Cache-Control: max-age=300
```
Seems to me that all you need to do is add that `d` parameter and check the HTTP result code then. | Gravatar have added an option to the 'd' parameter, meaning that [if you pass in `d=404`](http://en.gravatar.com/site/implement/images/), you get a 404 page (instead of some `302` redirect to a default picture) if there's no picture, rather than having to use heuristics. | Check for valid gravatar (PHP) | [
"",
"php",
"gravatar",
""
] |
I am trying to do the following Linq query on a [Visio Masters](http://msdn.microsoft.com/en-us/library/ms368289.aspx) collection:
```
List<string> allMasterNames = (from master in myStencil.Masters select master.NameU).ToList<string>
```
I get the following error:
> Could not find an implementation of
> the query pattern for source type
> 'Microsoft.Office.Interop.Visio.Masters'.
> 'Select' not found. Consider
> explicitly specifying the type of the
> range variable 'master'.
From reading around this error seems to occur when the queried object does not implement `IEnumerable<T>` or `IQueryable<T>`. Is that the case here, or is it something else? | Yes, it is because it's not `IEnumerable<T>`, `IQueryable<T>` and it doesn't have its own custom Select method written.
Contary to popular believe you **don't** have to implement those interfaces to have LINQ support, you just need to have the methods they compile down to.
This is fine:
```
public class MyClass {
public MyClass Select<MyClass>(Func<MyClass, MyClass> func) { ... }
}
var tmp = from m in new MyClass()
select m;
```
Sure a `.ToList()` wont work though ;)
As you solving your problem try using the `Cast<T>()` extension method, that'll make it an `IEnumerable<T>` and allow you to LINQ to your hearts content. | As the exception message suggests, consider explicitly specifying the type of the range variable 'master'.
```
from Visio.Master master in myStencil.Masters select master.NameU
``` | Why can't I use a Linq query on a Visio Masters collection? | [
"",
"c#",
"linq",
""
] |
I'm doing some graphics programming and I'm using Vertex pools. I'd like to be able to allocate a range out of the pool and use this for drawing.
Whats different from the solution I need than from a C allocator is that I never call malloc. Instead I preallocate the array and then need an object that wraps that up and keeps track of the free space and allocates a range (a pair of begin/end pointers) from the allocation I pass in.
Much thanks. | in general: you're looking for a memory mangager, which uses a [(see wikipedia) memory pool](http://en.wikipedia.org/wiki/Memory_pool) (like the [boost::pool](http://www.boost.org/doc/libs/1_39_0/libs/pool/doc/index.html) as answered by TokenMacGuy). They come in many flavours. Important considerations:
* block size (fixed or variable; number of different block sizes; can the block size usage be predicted (statistically)?
* efficiency (some managers have 2^n block sizes, i.e. for use in network stacks where they search for best fit block; very good performance and no fragementation at the cost of wasting memory)
* administration overhead (I presume that you'll have many, very small blocks; so the number of ints and pointers maintainted by the memory manager is significant for efficiency)
In case of boost::pool, I think the [simple segragated storage](http://www.boost.org/doc/libs/1_39_0/libs/pool/doc/interfaces/simple_segregated_storage.html) is worth a look.
It will allow you to configure a memory pool with many different block sizes for which a best-match is searched for. | [boost::pool](http://www.boost.org/doc/libs/1_39_0/libs/pool/doc/index.html) does this for you very nicely! | Given an Array, is there an algorithm that can allocate memory out of it? | [
"",
"c++",
"c",
"memory",
"graphics",
"allocation",
""
] |
Why would I want to use prototype.js with scriptaculous.js? What's the main reason?
When would I need both libraries and when wouldn't I? | I've used prototype for quite some time, and scriptaculous with it ; I now use jQuery on some projects, Mootools on others, and prototype on others...
Why do I use a JS Framework ?
Well, three main reasons :
* They provide lots of stuff I do not want to re-develop by myself
* They are well-tested ; more than my own code would be
* They provide a layer of cross-browser-compatibility (And I prefer having a framework that deals with that, instead of having to fight this war by myself !)
As for which JS Framework you should use, that's another question - it's entirely up to you ^^
When including prototype.js and/or scriptaculous.js :
* prototype.js : on any page that needs some JS stuff (most pages generally)
* scriptaculous.js : at least on pages that require effects like drag'n drop, autocompleter, etc...
Same thing with other JS frameworks too, btw... | Scriptaculous uses Prototype internally. If you use Scriptaculous, you need Prototype. | Why would I use prototype.js with scriptaculous.js... What's the main reason? | [
"",
"javascript",
"scriptaculous",
""
] |
Is there a portable way of determining if a database table already exists or not? | Portable? I don't think so.
Maybe the closest you can get is:
```
select * from <table>
```
And this would return an error if the table doesn't exist. | This is as portable as it gets, sadly:
```
select
count(*)
from
information_schema.tables
where
table_name = 'tablename'
and table_schema = 'dbo'
```
This definitely works on SQL Server, MySQL, and Postgres. Not so much on Oracle, though. You'd have to access the Oracle data dictionary for that. However, there is an open source project that [creates `information_schema` in Oracle](http://sourceforge.net/projects/ora-info-schema/) from the data dictionary. You can try that if you need absolute portability.
P.S.-Schema doesn't have to be `dbo`, but that's the most common. | Portable SQL to determine if a table exists or not? | [
"",
"sql",
"portability",
""
] |
I am after a definitive, cross-browser solution to set the cursor/caret position to the last known position when a contentEditable='on' <div> regains focus. It appears default functionality of a content editable div is to move the caret/cursor to the beginning of the text in the div each time you click on it, which is undesirable.
I believe I would have to store in a variable the current cursor position when they are leaving focus of the div, and then re-set this when they have focus inside again, but I have not been able to put together, or find a working code sample yet.
If anybody has any thoughts, working code snippets or samples I'd be happy to see them.
I don't really have any code yet but here is what I do have:
```
<script type="text/javascript">
// jQuery
$(document).ready(function() {
$('#area').focus(function() { .. } // focus I would imagine I need.
}
</script>
<div id="area" contentEditable="true"></div>
```
*PS. I have tried this resource but it appears it does not work for a <div>. Perhaps only for textarea ([How to move cursor to end of contenteditable entity](https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity))* | This is compatible with the standards-based browsers, but will probably fail in IE. I'm providing it as a starting point. IE doesn't support DOM Range.
```
var editable = document.getElementById('editable'),
selection, range;
// Populates selection and range variables
var captureSelection = function(e) {
// Don't capture selection outside editable region
var isOrContainsAnchor = false,
isOrContainsFocus = false,
sel = window.getSelection(),
parentAnchor = sel.anchorNode,
parentFocus = sel.focusNode;
while(parentAnchor && parentAnchor != document.documentElement) {
if(parentAnchor == editable) {
isOrContainsAnchor = true;
}
parentAnchor = parentAnchor.parentNode;
}
while(parentFocus && parentFocus != document.documentElement) {
if(parentFocus == editable) {
isOrContainsFocus = true;
}
parentFocus = parentFocus.parentNode;
}
if(!isOrContainsAnchor || !isOrContainsFocus) {
return;
}
selection = window.getSelection();
// Get range (standards)
if(selection.getRangeAt !== undefined) {
range = selection.getRangeAt(0);
// Get range (Safari 2)
} else if(
document.createRange &&
selection.anchorNode &&
selection.anchorOffset &&
selection.focusNode &&
selection.focusOffset
) {
range = document.createRange();
range.setStart(selection.anchorNode, selection.anchorOffset);
range.setEnd(selection.focusNode, selection.focusOffset);
} else {
// Failure here, not handled by the rest of the script.
// Probably IE or some older browser
}
};
// Recalculate selection while typing
editable.onkeyup = captureSelection;
// Recalculate selection after clicking/drag-selecting
editable.onmousedown = function(e) {
editable.className = editable.className + ' selecting';
};
document.onmouseup = function(e) {
if(editable.className.match(/\sselecting(\s|$)/)) {
editable.className = editable.className.replace(/ selecting(\s|$)/, '');
captureSelection();
}
};
editable.onblur = function(e) {
var cursorStart = document.createElement('span'),
collapsed = !!range.collapsed;
cursorStart.id = 'cursorStart';
cursorStart.appendChild(document.createTextNode('—'));
// Insert beginning cursor marker
range.insertNode(cursorStart);
// Insert end cursor marker if any text is selected
if(!collapsed) {
var cursorEnd = document.createElement('span');
cursorEnd.id = 'cursorEnd';
range.collapse();
range.insertNode(cursorEnd);
}
};
// Add callbacks to afterFocus to be called after cursor is replaced
// if you like, this would be useful for styling buttons and so on
var afterFocus = [];
editable.onfocus = function(e) {
// Slight delay will avoid the initial selection
// (at start or of contents depending on browser) being mistaken
setTimeout(function() {
var cursorStart = document.getElementById('cursorStart'),
cursorEnd = document.getElementById('cursorEnd');
// Don't do anything if user is creating a new selection
if(editable.className.match(/\sselecting(\s|$)/)) {
if(cursorStart) {
cursorStart.parentNode.removeChild(cursorStart);
}
if(cursorEnd) {
cursorEnd.parentNode.removeChild(cursorEnd);
}
} else if(cursorStart) {
captureSelection();
var range = document.createRange();
if(cursorEnd) {
range.setStartAfter(cursorStart);
range.setEndBefore(cursorEnd);
// Delete cursor markers
cursorStart.parentNode.removeChild(cursorStart);
cursorEnd.parentNode.removeChild(cursorEnd);
// Select range
selection.removeAllRanges();
selection.addRange(range);
} else {
range.selectNode(cursorStart);
// Select range
selection.removeAllRanges();
selection.addRange(range);
// Delete cursor marker
document.execCommand('delete', false, null);
}
}
// Call callbacks here
for(var i = 0; i < afterFocus.length; i++) {
afterFocus[i]();
}
afterFocus = [];
// Register selection again
captureSelection();
}, 10);
};
``` | **This solution works in all major browsers:**
`saveSelection()` is attached to the `onmouseup` and `onkeyup` events of the div and saves the selection to the variable `savedRange`.
`restoreSelection()` is attached to the `onfocus` event of the div and reselects the selection saved in `savedRange`.
This works perfectly unless you want the selection to be restored when the user clicks the div aswell (which is a bit unintuitative as normally you expect the cursor to go where you click but code included for completeness)
To achieve this the `onclick` and `onmousedown` events are canceled by the function `cancelEvent()` which is a cross browser function to cancel the event. The `cancelEvent()` function also runs the `restoreSelection()` function because as the click event is cancelled the div doesn't receive focus and therefore nothing is selected at all unless this functions is run.
The variable `isInFocus` stores whether it is in focus and is changed to "false" `onblur` and "true" `onfocus`. This allows click events to be cancelled only if the div is not in focus (otherwise you would not be able to change the selection at all).
If you wish to the selection to be change when the div is focused by a click, and not restore the selection `onclick` (and only when focus is given to the element programtically using `document.getElementById("area").focus();` or similar then simply remove the `onclick` and `onmousedown` events. The `onblur` event and the `onDivBlur()` and `cancelEvent()` functions can also safely be removed in these circumstances.
This code should work if dropped directly into the body of an html page if you want to test it quickly:
```
<div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
<script type="text/javascript">
var savedRange,isInFocus;
function saveSelection()
{
if(window.getSelection)//non IE Browsers
{
savedRange = window.getSelection().getRangeAt(0);
}
else if(document.selection)//IE
{
savedRange = document.selection.createRange();
}
}
function restoreSelection()
{
isInFocus = true;
document.getElementById("area").focus();
if (savedRange != null) {
if (window.getSelection)//non IE and there is already a selection
{
var s = window.getSelection();
if (s.rangeCount > 0)
s.removeAllRanges();
s.addRange(savedRange);
}
else if (document.createRange)//non IE and no selection
{
window.getSelection().addRange(savedRange);
}
else if (document.selection)//IE
{
savedRange.select();
}
}
}
//this part onwards is only needed if you want to restore selection onclick
var isInFocus = false;
function onDivBlur()
{
isInFocus = false;
}
function cancelEvent(e)
{
if (isInFocus == false && savedRange != null) {
if (e && e.preventDefault) {
//alert("FF");
e.stopPropagation(); // DOM style (return false doesn't always work in FF)
e.preventDefault();
}
else {
window.event.cancelBubble = true;//IE stopPropagation
}
restoreSelection();
return false; // false = IE style
}
}
</script>
``` | Set cursor position on contentEditable <div> | [
"",
"javascript",
"jquery",
"html",
"contenteditable",
"cursor-position",
""
] |
Do you know of any websites that allow users to share there custom PHP functions and code snippets other then? It would be nice to compile a list of a few good resources
<http://www.phpclasses.org> | There is Snipplr.com - A public source code repository for sharing code snippets. | Might be obvious to some, but don't forget to include <http://pear.php.net/> in your list. ;-) | Is there any sites where users share custom PHP code? | [
"",
"php",
"resources",
""
] |
I have a social network
* The users table is around 60,000 rows
* The friends table is around 1 million
rows (used to determine who is your
friend)
I am wanting to do a friend feed, wall, whatever you like to call it, it will show things like user status post (twitter type posts), it will show a few different items but for the start it will just be friend status and maybe blog post.
Basicly you will only see content published with a user ID that is in your friend list.
I have been trying to come up with the best way and haven't gotten very far but here is my latest idea.
Currently to build this feed, I have to
1. Get the list of friend ID's on the
large friend table
2. Get the stream data from the friend
ids from the above result
3. JOIN the user table to get the
publishers picture URL and username
4. Then JOIN the comments table to get
comments posted on the feed items
That is one big task to build that feed
**I have 3 ideas so far, this is where your help can come in.**
**Memcache Option:**
1. Use memcache and cache a users
friendlist as an array when the user
logs into the site, also when the user
approves a new friend request for a
friend to be added to there list, it
would rebuild there cache.
2. In addition to just getting there friends I could save there friends picture URL and username, this would speed up things again by eliminating this query when building the friend feed.
**File cache Option:**
1. Do the same as the memcache option
does but save this data as an array
to a cache file instead of memory,
then include this cache file into
the page.
2. I am not sure which is the best
method for performance I understand
memcache stores everything in memory
so friends that have like 20,000
friends that could use a lot of
memory and a file cache would only
put it in memory when the users
needs it if I am correct. Also if I
did the file method, when a user
logs out of the site, I would delete
there cache file so the cache folder
would never be too large of files
**Session cache Option:**
1. Same as file cache above, I just realized that session data is saved into a file so wouldn't that make it capable of being a cache?
**Please give me your opinions or any advice or info you have on this as I don't have much knowledge of caching, I have read a lot but sometimes other peoples ideas help a lot** | Memcache is your best bet for a lot of reasons:
1. It's REALLY fast - Everything's in memory, and it's highly optimized for situations just like yours (and caching in general :)
2. It's distributed - This means that if you have multiple web / app servers running, they can all access the same cache
3. You can pool multiple servers for memcache - If you've got a few servers that are relatively underutilized (or several dedicated cache servers), you can pool them all together into one big cache
4. It's super-scalable (for the reasons mentioned prior)
5. It's got great PHP support - The PECL package for memcache was recently updated with a lot of new goodness
6. You can even store your user sessions in memcache - just set it up in your php.ini file. This is much faster than storing sessions in databases, and allows your sessions to persist across multiple web hosts (if you're in a load balanced situation)... this will also give your site a bit of a performance boost as there's no need to hit the filesystem / database for session info on every request.
... and many more ;)
As to some of your concerns about memory footprint of individual cached items you've got a few options. My initial thought is to just give it a whirl, see how big these cache items really get (you can find several open-source things to monitor the actual cache usage, such as cacti). I think they'll be smaller than you'd think.
If they're not, I'd suggest re-thinking your cache strategy as far as what you actually cache, for how long, etc. Maybe you could build the feed from several things already in the cache (i.e. cache individual user data, and then build the feed for a person from all those individual items in cache). There are a lot of good articles out there on that front, just search 'em out :) | The default maximum object size that is allowed in Memcache is 1MB.
@jsaondavis :
"session data is saved into a file".
Your above statement is wrong. Session can be configured to store in database. Default session hadndler is file. | Session VS File VS Memcache for a Cache in PHP? | [
"",
"php",
"session",
"caching",
"memcached",
""
] |
I have code that controls a mutex lock/unlock based on scope:
```
void PerformLogin()
{
ScopeLock < Lock > LoginLock( &m_LoginLock );
doLoginCommand();
ScopeLock < SharedMemoryBase > MemoryLock( &m_SharedMemory );
doStoreLogin();
...
}
```
Can I guarantee that `MemoryLock` will be destructed before `LoginLock`? | Yes, it is. In any particular scope local objects are destroyed in the reverse order that they were constructed. | Yes, destructors are called in the reverse order of construction. | Can you guarantee destructor order when objects are declared on a stack? | [
"",
"c++",
"destructor",
""
] |
I have a class like this
```
class MyClass
{
int Identifier;
int Context;
int Data;
}
```
and I plan to store it in a STL container like
```
vector<MyClass> myVector;
```
but I will need to access it either by the extenal Index (using `myVector[index]`); and the combination of `Identifier` and `Context` which in this case I would perform a search with something like
```
vector<MyClass>::iterator myIt;
for( myIt = myVector.begin(); myIt != myVector.end(); myIt++ )
{
if( ( myIt->Idenfifier == target_id ) &&
( myIt->Context == target_context ) )
return *myIt; //or do something else...
}
```
Is there a better way to store or index the data? | [Boost::Multi-Index](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/index.html) has this exact functionality if you can afford the boost dependency (header only). You would use a `random_access` index for the array-like index, and either `hashed_unique`, `hashed_non_unique`, `ordered_unique`, or `ordered_non_unique` (depending on your desired traits) with a functor that compares Identifier and Context together. | We need to know your usage. *Why* do you need to be able to get them by index, and how often do you need to search the container for a specific element.
If you store it in an [`std::set`](http://www.cplusplus.com/reference/stl/set/), your search time with be O(ln n), but you cannot reference them by index.
If you use an [`std::vector`](http://www.cplusplus.com/reference/stl/vector/), you can index them, but you have to use [`std::find`](http://www.cplusplus.com/reference/algorithm/find/) to get a specific element, which will be O(n).
But if you need an index to pass it around to other things, you could use a pointer. That is, use a set for faster look-up, and pass pointers (not index's) to specific elements. | Container with two indexes (or a compound index) | [
"",
"c++",
"stl",
"indexing",
""
] |
I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:
```
,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
```
Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.
Thanks. | Something like this?
```
import csv
source= csv.reader( open("some file","rb") )
dest= csv.writer( open("another file","wb") )
for row in source:
result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
dest.writerow( result )
```
---
**Example**
```
>>> data=''',,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
... '''.splitlines()
>>> rdr= csv.reader( data )
>>> row= rdr.next()
>>> row
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CT', '', 'goo', '' ]
>>> row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CTgoo', '']
``` | You can use the csv module to do the heavy lifting: <http://docs.python.org/library/csv.html>
You didn't say exactly how you wanted to merge the columns; presumably you don't want your merged field to be "Moved from Portland, CTgoo". The code below allows you to specify a separator string (maybe `", "`) and handles empty/blank fields.
```
[transcript of session]
prompt>type merge.py
import csv
def merge_csv_cols(infile, outfile, startcol, numcols, sep=", "):
reader = csv.reader(open(infile, "rb"))
writer = csv.writer(open(outfile, "wb"))
endcol = startcol + numcols
for row in reader:
merged = sep.join(x for x in row[startcol:endcol] if x.strip())
row[startcol:endcol] = [merged]
writer.writerow(row)
if __name__ == "__main__":
import sys
args = sys.argv[1:6]
args[2:4] = map(int, args[2:4])
merge_csv_cols(*args)
prompt>type input.csv
1,2,3,4,5,6,7,8,9,a,b,c
1,2,3,4,5,6,,,,a,b,c
1,2,3,4,5,6,7,8,,a,b,c
1,2,3,4,5,6,7,,9,a,b,c
prompt>\python26\python merge.py input.csv output.csv 6 3 ", "
prompt>type output.csv
1,2,3,4,5,6,"7, 8, 9",a,b,c
1,2,3,4,5,6,,a,b,c
1,2,3,4,5,6,"7, 8",a,b,c
1,2,3,4,5,6,"7, 9",a,b,c
``` | How can I merge fields in a CSV string using Python? | [
"",
"python",
"database",
"string",
"csv",
""
] |
Am I right that you'd only need a using() for the outermost stream if you're doing e.g
```
MemoryStream mstr = new MemoryStream();
using(StreamWriter w = new StreamWriter(mstr)) {
....
}
```
As disposing the StreamWriter should also dispose/close the underlying stream, there's no need to do this ?:
```
using(MemoryStream mstr = new MemoryStream())
using(StreamWriter w = new StreamWriter(mstr)) {
....
}
```
(Note these are just examples, for how to dispose wrapped streams, not looking for alternatives like just use a StringWriter etc.) | My rule of thumb: If it implements IDisposable, dispose of it.
While currently (and probably forever), calling StreamWriter.Dispose() *closes* the underlying stream, other stream-derived classes you may use in the future may not. Also, it seems not to actually call Dispose() either, so non-MemoryStreams may not get properly disposed (although I can't think of any that would suffer from that right now).
So, while you *can* safely dispose only of the StreamWriter, I find it a much better practice to always use using blocks for disposables whenever possible. | It's a good idea to put all dependent resources in their own `using` blocks from a readability and maintainability point of view as much as anything. e.g. in the below code, after the final brace, it's impossible to attempt to access `mstr` because it is scoped to within the block where it is valid:
```
using (MemoryStream mstr = new MemoryStream())
using (StreamWriter w = new StreamWriter(mstr) {
....
}
// cannot attempt to access mstr here
```
If you don't scope it like this, then it's still possible to access `mstr` outside the scope of where it is valid
```
MemoryStream mstr = new MemoryStream();
using (StreamWriter w = new StreamWriter(mstr) {
....
}
mstr.Write(...); // KABOOM! ObjectDisposedException occurs here!
```
So while it may not always be necessary (and in this case it isn't) it's a good idea as it both clarifies and enforces your intention as to its scope. | using() and dispose with multiple wrapped streams | [
"",
"c#",
"stream",
"dispose",
""
] |
I'm considering shifting from PHP to Rails. Does an average web host support the Ruby language and everything that Rails needs? Does a normal Rails app using MySQL or does it handle data differently? And is it as "easy" to get an app up and running, as PHP? | No, the average shared webhost provider does not because most are preconfigured with LAMP and Ruby usually isn't installed, but RoR support is on the rise.
However, if you're interested in a dedicated/vps (unmanaged) then you pretty much can do whatever you want ( I would recommend slicehost/linode if you are looking for a vps and your budget is around $20/mo ).
A decent web application ( ROR ) can handle many types of DBMS's including MySQL, PostgreSQL, SQLite.
What's your budget? How big will your site be? | > Does an average web host support the Ruby language and everything that Rails needs?
No. Many hosts have still to come on board with this. If you're looking for cheap shared hosting, I'd suggest <http://railsplayground.com/>
> Does a normal Rails app using MySQL or does it handle data differently?
Rails is database agnostic. You can connect to SQLITE, MySQL, PostgreSQL, Oracle and more.
> And is it as "easy" to get an app up and running, as PHP?
Subjective. I'd say no. If you're looking for painless rails deployment with Apache or nginx I'd have to suggest using [Phusion Passenger](http://modrails.com/) aka modrails. | Is Ruby on Rails supported by most hosts? | [
"",
"php",
"ruby-on-rails",
"web-hosting",
""
] |
The reason I am asking this question is because I have landed my first real (yes, a paid office job - no more volunteering!) Web Development job about two months ago. I have a couple of associates in computer information systems (web development and programming). But as many of you know, what you learn in college and what you need in the job site can be very different and much more. I am definitely learning from my job - I recreated the entire framework we use from scratch in a MVC architecture - first time doing anything related to design patterns.
I was wondering what you would recommend as the best way to pass/return values around in OO PHP? Right now I have not implement any sort of standard, but I would like to create one before the size of the framework increases any more. I return arrays when more than 1 value needs to get return, and sometimes pass arrays or have multiple parameters. Is arrays the best way or is there a more efficient method, such as json? I like the idea of arrays in that to pass more values or less, you just need to change the array and not the function definition itself.
Thank you all, just trying to become a better developer.
EDIT: I'm sorry all, I thought I had accepted an answer for this question. My bad, very, very bad. | How often do you run across a situation where you actually need multiple return values? I can't imagine it's that often.
And I don't mean a scenario where you are returning something that's *expected* to be an enumerable data collection of some sort (i.e., a query result), but where the returned array has no other meaning that to just hold two-or-more values.
One technique the PHP library itself uses is reference parameter, such as with [preg\_match()](https://www.php.net/preg_match). The function itself returns a single value, a boolean, but optionally uses the supplied 3rd parameter to store the matched data. This is, in essence, a "second return value".
Definitely don't use a data interchange format like JSON. the purpose of these formats is to move data between disparate systems in an expected, parse-able way. In a single PHP execution you don't need that. | You can return anything you want: a single value, an array or a reference (depending on the function needs). Just be consistent.
But please don't use JSON internally. It just produces unnecessary overhead. | Best method of passing/return values | [
"",
"php",
""
] |
As a C++ stickler, this has really been bugging me. I've always liked the idea of the "language-independant framework" that Microsoft came up with roughly a decade ago. Why have they dropped the ball on this idea? Does anyone know the reasoning behind it? | Part of the reason will be that C++ support is actually two languages in one -- the native and the CLI variants; that extra development load has been acknowledged by the Visual C++ team as the reason that proper MSBuild integration lagged (lags? I haven't checked in 2008 or later) behind other languages.
Another part will be to do with the code generation during compilation that goes on in a C# build to support e.g. the binding "magic"; I've found that even in F#, you don't get it "just happening". | If it were me my reasoning would be that C++.Net should not be used to write GUIs.
I'm not trying to be snarky here, maybe someone can show me the error of my ways but I don't think it's a good idea. I'm messing around with one right now and development much much slower than if the application had been written in C#. My feeling is if features in C++.Net or just regular C++ are required for the application it seems like a better idea would be to create a DLL to do the heavy lifting and could interface with C#. | Why doesn’t WPF support C++.NET - the way WinForms does? | [
"",
"c++",
".net",
"wpf",
"managed-c++",
""
] |
I want to create a program, which can encrypt and decrypt a complete file with an individual password. Is there any way to manage this in Qt and/or C++ and how? | I've never used it myself, but I've heard great things about [QCA](https://api.kde.org/qca/html/index.html). It's cross platform, uses a Qt-style API and Qt datatypes. | www.cryptopp.com is a very complete C++ library with implementations of most algorithms.
The actual program (select file, read, obtain key, encrypt etc) should be piece of cake. | How to encrypt and decrypt a file with Qt/C++? | [
"",
"c++",
"qt",
"encryption",
"qt4",
""
] |
My quest of starting to use namespaces in PHP keeps continuing. This time PHPUnit gives me problems. My setup() method is like this:
```
$test = new \MyNamespace\NonPersistentStorage(); // works
$mock = $this->getMock('\\MyNamespace\\NonPersistentStorage'); // doesn't work
```
The getMock() method only results in PHP looking for a NonPersistentStorage class. Not within the namespace.
Q: What do I need to change to get the getMock() method look for the class in the namespace?
Edit: The double backslash is not the problem. Also see: [the manual](https://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.quote): (quote)
'Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.'
edit: What worked for me is in the comments of the answer of Ignace R. | String references to classes generally don't have the leading backslash. Try removing it and tell us if it works.
**EDIT:** and if it doesn't, try [class\_alias](https://www.php.net/manual/en/function.class-alias.php) to create an alias in the global namespace for that class. However, that would be an ugly solution... | use this string instead (without the double backslashes):
```
$mock = $this->getMock('\MyNamespace\NonPersistentStorage');
``` | PHPUnit getMock() with namespace | [
"",
"php",
"namespaces",
"phpunit",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.