Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've wrapped my wcf client in a IDisposable wrapper and everything appears to work correctly, I have a test case that runs this x times after around 10 times I start to get timeout's
The calling code has the helper wrapped in a using statement, so tbh I'm at a bit of a loss
Anyone shed any light on this?
```
public class CrmServiceHelper : IDisposable
{
private CrmServices.CRMServicesClient client;
public CrmServices.CRMServicesClient GetClient
{
get
{
lock (this)
{
if (client == null)
client = new CrmServices.CRMServicesClient();
}
return client;
}
}
public void Dispose()
{
try
{
client.Close();
}
catch (CommunicationException ex)
{
client.Abort();
}
catch (TimeoutException ex)
{
client.Abort();
}
}
}
```
Sample usage code:
```
using (CrmServiceHelper client = new CrmServiceHelper())
{
AListReponse resp = client.GetClient.GetAList(companyId);
if ((resp != null) && (resp.AList != null))
{
return resp.AList ;
}
else
{
return null;
}
}
```
Service config | After about 10 times.... that almost sounds as if you're hitting a server throttling limit.... maybe you're not properly closing your client proxy? Client sessions are hanging around, and the service won't accept any new incoming requests?
How does your service hosting look like? IIS? Self-Hosted? Are you using a per-call model, or session-based calls?
Can you show us the server side config, and the code to host the service (if you're self-hosting, that is). That might help us find a reason.
Marc
**UPDATE**:
if you're using "out-of-the-box-no-changes" mode, you'll have the wsHttpBinding, and you'll be using a session-based approach. The service is limited to a maximum of 10 sessions by default.
You can do two things:
1) You could change the service throttling behavior on your server side to allow more than 10 sessions at once:
```
<behaviors>
<serviceBehaviors>
<behavior name="Throttled">
<serviceThrottling
maxConcurrentCalls="25"
maxConcurrentSessions="25"
maxConcurrentInstances="25" />
</behavior>
</serviceBehaviors>
</behaviors>
```
Be aware this puts more strain on your server - you don't want to go too high....
2) you could change the calling model to "per-call" by adorning your service implementation with this attribute:
```
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
class YourService : IYourService
{
......
}
```
But even in this case, the service throttling might kick in - the service is limited to 16 concurrent calls by default - you might need to increase that (and the MaxInstances, too, to the same number). | I don't see anything wrong with the code (though I'd test for null first, before doing the lock, in addition to after the lock).
Perhaps the problem is not with the client side, but with the service? | WCF Timeouts When Calling Operation in a Loop | [
"",
"c#",
"wcf",
""
] |
I'm a .NET guy originally, working in Java recently, and finding I'm really missing LINQ to Objects, specifically for performing filtering against collections.
A few people here on Stack Overflow have answered the "LINQ for Java?" question with a single word :
> [Quaere](http://quaere.codehaus.org/)
However, on the site it clearly states "Pre-Beta", and there's been no commits to their code for over a year, so I'm guessing the project is pretty much dead.
Is anyone actually using this, and / or have any experience with it?
The second most common answer appears to be "use Google Collections". Is this the most appropriate Java way?
Cheers
Marty | You can select the items in a collection (and much more) in a more readable way by using the lambdaj library
<http://code.google.com/p/lambdaj/> | Quaere is in a pioneer position with LINQ in Java, but is not typesafe, which is one of the main points of LINQ.
[Querydsl](http://www.querydsl.com) is type-safe and supports filtering, sorting and projecting Collections.
It supports operations on JPA/Hibernate, JDO and SQL backends as well.
The syntax is similar to SQL with the difference that the basic order is from-where-list.
I am the maintainer of Querydsl, so this answer is biased. | Quaere - Anyone using it yet? (LINQ to Objects for Java) | [
"",
"java",
"collections",
"linq-to-objects",
""
] |
Say, you are submitting a form, which affects your database (adding records/ deleting them/ updating them) and this is how your request looks like:
POST /application/action=update
Now, say, you are done with your update, so you would like to take the user to the home page.
Response.sendRedirect /application/action=home
This works wonderfully well. User is sent a redirect after POST, so even if the user tries to refresh the page by hitting F5, you are good. However, this will not work if you did this:
requestDispatcher.forward(/application/action=home)
Given that there is a scenario where you have to display different kinds of error / success messages after you are done with your update, you are most likely doing a forward after POST. In such a scenario, how do you avoid update actions from happening twice?
I find it rather amusing that many secure sites (banks) / payment gateways tend to inform the user by placing text on screen, such as "Please don't press back / refresh buttons".
Is there no better way to handling this? Other than requesting the user not to press these buttons? When I last checked, there was something called the 'Vertical Response Cache'. A Filter that would identify uniqueness of your request in a session and tries to send a cached response if the request is duplicate. Are there any simpler ways to solving this classic problem?
Here is a link to the vertical response cache solution I was talking about: <http://www.fingo.info/en/articles/_1.html>. I am, However, not sure as to how well this really works. | One thought that I've had is to embed a unique ID (probably a random string) as a hidden form field in the form that is being POST-submitted. The ID string can be put in the database as a "transaction ID". Now, when you go to update the database, first check whether there's an existing record with the submitted transaction ID, and if so, assume it's a duplicate and don't change the database.
Of course, as I said, this is just a thought. I don't know what methods are actually used in practice. (I suspect that a lot of less-critical sites just ignore the problem and hope their users will be smart... a losing proposition if I ever saw one ;-)
*EDIT*: as pointed out in the comments, storing transaction IDs in the database might take up a lot of space, but if that's an issue, you could keep an in-memory cache of all transaction IDs processed in the last 5 minutes/1 hour/1 day/whatever. That should work unless you're up against a determined hacker... | Yes, I believe that you should redirect after a POST, with the exception of API requests. Without doing this not only do you have to worry about getting duplicate POSTs when the user uses the back button, but the browser will also give the user annoying dialogs when they try to use the back button.
Response.sendRedirect works in practice, but tecnically speaking this is sending the wrong HTTP response code for this purpose. sendRedirect sends a 302, but the correct code to use to transform a POST into a GET is 303. (most browsers will treat a 302 just like a 303 if they get it in response to a POST, however)
In general you want the redirect to send the user to whatever view will display the effect of their change. For example, if they edit a widget, they should be redirected to the view of that widget. If they delete a widget, they should be redirected to the view that the widget would have appeared in when it existed (perhaps the widget list).
Sometimes it's nice to have a status message to further drive home the fact that an action occurred. A simple way to do this is to have a common parameter to your views that, when set, will display an action completed message. eg:
```
/widget?id=12345&msg=Widget+modified.
```
Here the "msg" parameter contains the message "Widget modified". The one downside to this approach is that it may be possible for malicious sites to give your users confusing/misleading messages. eg:
```
/account?msg=Foo+Corp.+hates+you.
```
If you're really worried about this you could include an expiring signature for the message as an additional parameter. If the signature is invalid or has expired, simply don't display the message. | Do you always REDIRECT after POST? If yes, How do you manage it? | [
"",
"java",
"jakarta-ee",
"form-submit",
""
] |
What is a good resource for finding out the warning numbers in Visual C# 2008. I found this page: <http://msdn.microsoft.com/en-us/library/4wtxwb6k.aspx> but it's very hard to sort through the warning numbers.
I am trying to figure out which warning number to use for the warning disable pragma:
<http://msdn.microsoft.com/en-us/library/441722ys.aspx>
Specifically, I am trying to find the one related to Missing XML comments for publicly visible types. | It's CS1591. Just press F1 on the warning location to view MSDN documentation for it.
You can resolve this specific warning either by:
* Reducing warning level (it's a level 4 warning)
* Removing `/doc` switch (which will stop XML file generation)
* Disable the warning using `#pragma` directive
* Disable the warning using `/nowarn:1591` switch | To find warning numbers in Visual Studio, build your project and then look for the warning numbers in the Output window. | Warning number guide in Visual C# 2008 | [
"",
"c#",
"visual-studio",
""
] |
I have a `String[]` with values like so:
```
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
```
Given `String s`, is there a good way of testing whether `VALUES` contains `s`? | ```
Arrays.asList(yourArray).contains(yourValue)
```
Warning: this doesn't work for arrays of primitives (see the comments).
---
## Since [java-8](/questions/tagged/java-8 "show questions tagged 'java-8'") you can now use Streams.
```
String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
```
To check whether an array of `int`, `double` or `long` contains a value use `IntStream`, `DoubleStream` or `LongStream` respectively.
## Example
```
int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
``` | ## Concise update for Java SE 9
Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have `Set.of`.
```
private static final Set<String> VALUES = Set.of(
"AB","BC","CD","AE"
);
```
"Given String s, is there a good way of testing whether VALUES contains s?"
```
VALUES.contains(s)
```
O(1).
The **right type**, **immutable**, **O(1)** and **concise**. Beautiful.\*
## Original answer details
Just to clear the code up to start with. We have (corrected):
```
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
```
This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:
```
private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
```
(Note, you can actually drop the `new String[];` bit.)
Reference arrays are still bad and we want a set:
```
private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
new String[] {"AB","BC","CD","AE"}
));
```
(Paranoid people, such as myself, may feel more at ease if this was wrapped in `Collections.unmodifiableSet` - it could then even be made public.)
(\*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.) | How do I determine whether an array contains a particular value in Java? | [
"",
"java",
"arrays",
""
] |
I'm writing an asp.net web app. and i've hit a bit of a brick wall.
basically i have 2 pages, the main page with a text box in and a popup that contains a treeview.
My problem is this. when i select a treeview item i want the program to perform some database transactions using asp.net and then pass the value retrieved from the database into a javascript function that passes the data back from the popup page to the parent page. My problem is that i cannot find any way of calling a javascript function from asp.net. I've tried assigning attributes to controls on page load, but this does not work as when the page loads the data has not been retrieved from the database. | Have a look at the ClientScriptManager class. You can register scripts from code-behind that will run when the HTML page loads. Those scripts can call other javascript functions on the page.
There are many tutorials and examples on the Web. Here's one I found that may help but there are many more.
[How to use the client script manager](http://blogs.syrinx.com/blogs/dotnet/archive/2009/01/19/how-to-use-the-client-script-manager.aspx) | You hit the nail on the head when you said "I've tried assigning attributes to controls on page load, but this does not work as when the page loads the data has not been retrieved from the database." You just need to discover when you're pulling the data from the database, and then assign the values after that. Without looking at your code, there's no way to know for sure, but Page\_PreRender is probably a good bet to assign your values...it's probably after you're pulling information from the db...it's pretty much the last place that you can make things happen before the html is generated for the client. | triggering javascript events using asp.net | [
"",
"asp.net",
"javascript",
"vb.net",
""
] |
I am developing a Qt application that can play the videos and shows some scrolling bar along the way. The window size MUST Not exceed the limit of 720px in height and 1280 in width. I use MPlayer as a slave process and pass it the winId() of the QWidget and it renders the video in it. Now I want another widget on top of this video widget to show some results all the time but placing a label widget on top of the widget that contains video does not serve the purpose as it gets painted over and over by the video. Any workaround? Suggestions about it? | When using MPlayer in this manner, I believe your best option would be to create a *second window*.
There's a couple ways you could go from here, the fancier way which might not work on some versions/configurations of Xorg is to have the second window the same size as the first, and place it directly on top of the other (with a mechanism to move the other window when either is moved), and make the window transparent except for your controls (transparency being the problem with some versions of X, check labs.trolltech.com for some examples of this).
The alternative method, which I believe is what VLC uses when in fullscreen mode, is to have the second window just be a small little thing with the controls, and position it on top of the first window with an offset and no border... making it so when the first window is moved, the second window's position is updated. | I suggest you look into the Phonon framework for playing the video. It should handle the playing without calling a separate executable, which would likely solve the painting problem. | Painting on top of video in a Qt Widget | [
"",
"c++",
"qt",
""
] |
i'm just testing out the csv component in python, and i am having some trouble with it.
I have a fairly standard csv string, and the default options all seems to fit with my test, but the result shouldn't group 1, 2, 3, 4 in a row and 5, 6, 7, 8 in a row?
Thanks a lot for any enlightenment provided!
```
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> c = "1, 2, 3, 4\n 5, 6, 7, 8\n"
>>> test = csv.reader(c)
>>> for t in test:
... print t
...
['1']
['', '']
[' ']
['2']
['', '']
[' ']
['3']
['', '']
[' ']
['4']
[]
[' ']
['5']
['', '']
[' ']
['6']
['', '']
[' ']
['7']
['', '']
[' ']
['8']
[]
>>>
``` | csv.reader expects an iterable. You gave it `"1, 2, 3, 4\n 5, 6, 7, 8\n"`; iteration produces characters. Try giving it ["1, 2, 3, 4\n", "5, 6, 7, 8\n"] -- iteration will produce lines. | `csv.reader` takes an iterable or iterator returning lines, see [the docs](http://docs.python.org/library/csv.html#csv.reader). You're passing it a string, which is an iterable returning single characters.
So, use `csv.reader(c.splitlines())` or similar constructs! | python csv question | [
"",
"python",
"csv",
""
] |
I'd like to display a tree on a Facebook page with JavaScript. Therefore there can be no dependencies on frameworks such as jQuery or [Ext](http://en.wikipedia.org/wiki/Ext_%28JavaScript_library%29) which won't run on Facebook, at least as far as I know when I last worked on that platform (April 2009). Can anybody recommend a "framework-free" JavaScript/tree library? I have ported some fairly complex JavaScript to Facebook so I'm sure I'll be able to port just about any existing pure JavaScript library.
Clarification points:
* I am targeting [FBJS](http://en.wikipedia.org/wiki/Facebook_features#Facebook_Markup_Language)
* I too can (and did) google for JavaScript/tree engines but am seeking recommendations as to which one(s) | Look at this implementation... <http://www.destroydrop.com/javascripts/tree/> | You didn't describe the requirements for your JS tree, so I would suggest you write one yourself. It's a relatively simple task unless you need more complex functionality.
A simple tree is just a matter of having a bunch of DOM nodes that have other DOM nodes inside them that can be toggled on and off (display block/none) | JavaScript tree functionality without framework | [
"",
"javascript",
"facebook",
"tree",
"fbjs",
"no-framework",
""
] |
I'd like to test an abstract class. Sure, I can [manually write a mock](https://stackoverflow.com/questions/243274/best-practice-unit-testing-abstract-classes) that inherits from the class.
Can I do this using a mocking framework (I'm using Mockito) instead of hand-crafting my mock? How? | The following suggestion lets you test abstract classes without creating a "real" subclass - the Mock *is* the subclass and only a partial mock.
Use `Mockito.mock(My.class, Answers.CALLS_REAL_METHODS)`, then mock any abstract methods that are invoked.
Example:
```
public abstract class My {
public Result methodUnderTest() { ... }
protected abstract void methodIDontCareAbout();
}
public class MyTest {
@Test
public void shouldFailOnNullIdentifiers() {
My my = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS);
Assert.assertSomething(my.methodUnderTest());
}
}
```
Note: The beauty of this solution is that you do not *have to* implement the abstract methods. `CALLS_REAL_METHODS` causes all real methods to be run as is, as long as you don't stub them in your test.
In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiable subclass of your abstract class. | If you just need to test some of the concrete methods without touching any of the abstracts, you can use `CALLS_REAL_METHODS` (see [Morten's answer](https://stackoverflow.com/questions/1087339/using-mockito-to-test-abstract-classes/4317631#4317631)), but if the concrete method under test calls some of the abstracts, or unimplemented interface methods, this won't work -- Mockito will complain "Cannot call real method on java interface."
(Yes, it's a lousy design, but some frameworks, e.g. Tapestry 4, kind of force it on you.)
The workaround is to reverse this approach -- use the ordinary mock behavior (i.e., everything's mocked/stubbed) and use `doCallRealMethod()` to explicitly call out the concrete method under test. E.g.
```
public abstract class MyClass {
@SomeDependencyInjectionOrSomething
public abstract MyDependency getDependency();
public void myMethod() {
MyDependency dep = getDependency();
dep.doSomething();
}
}
public class MyClassTest {
@Test
public void myMethodDoesSomethingWithDependency() {
MyDependency theDependency = mock(MyDependency.class);
MyClass myInstance = mock(MyClass.class);
// can't do this with CALLS_REAL_METHODS
when(myInstance.getDependency()).thenReturn(theDependency);
doCallRealMethod().when(myInstance).myMethod();
myInstance.myMethod();
verify(theDependency, times(1)).doSomething();
}
}
```
---
**Updated to add:**
For non-void methods, you'll need to use [`thenCallRealMethod()`](http://docs.mockito.googlecode.com/hg/org/mockito/stubbing/OngoingStubbing.html#thenCallRealMethod()) instead, e.g.:
```
when(myInstance.myNonVoidMethod(someArgument)).thenCallRealMethod();
```
Otherwise Mockito will complain "Unfinished stubbing detected." | Using Mockito to test abstract classes | [
"",
"java",
"unit-testing",
"mocking",
"abstract-class",
"mockito",
""
] |
I'm using Python and PyGTK. I'm interested in running a certain function, which gets data from a serial port and saves it, every several minutes.
Currently, I'm using the sleep() function in the time library. In order to be able to do processing, I have my system set up like this:
```
import time
waittime = 300 # 5 minutes
while(1):
time1 = time.time()
readserial() # Read data from serial port
processing() # Do stuff with serial data, including dumping it to a file
time2 = time.time()
processingtime = time2 - time1
sleeptime = waittime - processingtime
time.sleep(sleeptime)
```
This setup allows me to have 5 minute intervals between reading data from the serial port. My issue is that I'd like to be able to have my readserial() function pause whatever is going on every 5 minutes and be able to do things all the time instead of using the time.sleep() function.
Any suggestions on how to solve this problem? Multithreading? Interrupts? Please keep in mind that I'm using python.
Thanks. | Do not use such loop with sleep, it will block gtk from processing any UI events, instead use gtk timer e.g.
```
def my_timer(*args):
return True# do ur work here, but not for long
gtk.timeout_add(60*1000, my_timer) # call every min
``` | This is exactly like [my answer here](https://stackoverflow.com/questions/1309006/running-function-5-seconds-after-pygtk-widget-is-shown/1309404#1309404)
If the time is not critical to be exact to the tenth of a second, use
```
glib.timeout_add_seconds(60, ..)
```
else as above.
*timeout\_add\_seconds* allows the system to align timeouts to other events, in the long run reducing CPU wakeups (especially if the timeout is reocurring) and [save energy for the planet](http://gould.cx/ted/blog/Saving_the_world_one__w_at_a_time)(!) | Run a function every X minutes - Python | [
"",
"python",
"gtk",
"timer",
"pygtk",
""
] |
I found that I have to perform a swap in python and I write something like this:
```
arr[first], arr[second] = arr[second], arr[first]
```
I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegant?
**EDIT:**
I think another example will show my doubts:
```
self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]
```
is this the only available solution for swap in python? | The one thing I might change in your example code: if you're going to use some long name such as `self.memberlist` over an over again, it's often more readable to alias ("assign") it to a shorter name first. So for example instead of the long, hard-to-read:
```
self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]
```
you could code:
```
L = self.memberlist
L[someindexA], L[someindexB] = L[someindexB], L[someindexA]
```
Remember that Python works by-reference so L refers to exactly the same object as `self.memberlist`, NOT a copy (by the same token, the assignment is extremely fast no matter how long the list may be, because it's not copied anyway -- it's just one more reference).
I don't think any further complication is warranted, though of course some fancy ones might easily be conceived, such as (for a, b "normal" indices `>=0`):
```
def slicer(a, b):
return slice(a, b+cmp(b,a), b-a), slice(b, a+cmp(a,b), a-b)
back, forth = slicer(someindexA, someindexB)
self.memberlist[back] = self.memberlist[forth]
```
I think figuring out these kinds of "advanced" uses is a nice conceit, useful mental exercise, and good fun -- I recommend that interested readers, once the general idea is clear, focus on the role of those `+cmp` and how they make things work for the three possibilities (a>b, a<b, a==b) [[not for negative indices, though -- why not, and how would slicer need to change to fix this?]]. But using such a fancy approach in production code would generally be overkill and quite unwarranted, making things murkier and harder to maintain than the simple and straightforward approach.
Remember, [simple is better than complex](http://www.python.org/dev/peps/pep-0020/)! | ```
a, b = b, a
```
[Is a perfectly Pythonic idiom.](http://love-python.blogspot.com/2008/02/swap-values-python-way.html) It is short and readable, as long as your variable names are short enough. | Pythonic Swap of 2 lists elements | [
"",
"python",
"swap",
""
] |
I'm facing a problem that seems to have no straighforward solution.
I'm using `java.util.Map`, and I want to update the value in a Key-Value pair.
Right now, I'm doing it lik this:
```
private Map<String,int> table = new HashMap<String,int>();
public void update(String key, int val) {
if( !table.containsKey(key) ) return;
Entry<String,int> entry;
for( entry : table.entrySet() ) {
if( entry.getKey().equals(key) ) {
entry.setValue(val);
break;
}
}
}
```
So is there any method so that I can get the required `Entry` object without having to iterate through the entire `Map`? Or is there some way to update the entry's value in place? Some method in `Map` like `setValue(String key, int val)`?
jrh | Use
```
table.put(key, val);
```
to add a new key/value pair or overwrite an existing key's value.
From the Javadocs:
> V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.) | If key is present `table.put(key, val)` will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is `table.get(key);` That's about it | Updating a java map entry | [
"",
"java",
"dictionary",
"in-place",
""
] |
imagine I have a bunch of C++ related classes (all extending the same base class and providing the same constructor) that I declared in a common header file (which I include), and their implementations in some other files (which I compile and link statically as part of the build of my program).
I would like to be able to instantiate one of them passing the name, which is a parameter that has to be passed to my program (either as command line or as a compilation macro).
The only possible solution I see is to use a macro:
```
#ifndef CLASS_NAME
#define CLASS_NAME MyDefaultClassToUse
#endif
BaseClass* o = new CLASS_NAME(param1, param2, ..);
```
Is it the only valuable approach? | This is a problem which is commonly solved using the [Registry Pattern](http://sinnema313.wordpress.com/2009/03/01/the-registry-pattern/):
> This is the situation that the
> Registry Pattern describes:
>
> > Objects need to contact another
> > object, knowing only the object’s name
> > or the name of the service it
> > provides, but not how to contact it.
> > Provide a service that takes the name
> > of an object, service or role and
> > returns a remote proxy that
> > encapsulates the knowledge of how to
> > contact the named object.
>
> It’s the same basic publish/find model
> that forms the basis of a Service
> Oriented Architecture (SOA) and for
> the services layer in OSGi.
You implement a registry normally using a singleton object, the singleton object is informed at compile time or at startup time the names of the objects, and the way to construct them. Then you can use it to create the object on demand.
For example:
```
template<class T>
class Registry
{
typedef boost::function0<T *> Creator;
typedef std::map<std::string, Creator> Creators;
Creators _creators;
public:
void register(const std::string &className, const Creator &creator);
T *create(const std::string &className);
}
```
You register the names of the objects and the creation functions like so:
```
Registry<I> registry;
registry.register("MyClass", &MyClass::Creator);
std::auto_ptr<T> myT(registry.create("MyClass"));
```
We might then simplify this with clever macros to enable it to be done at compile time. [ATL](http://en.wikipedia.org/wiki/Active_Template_Library) uses the Registry Pattern for CoClasses which can be created at runtime by name - the registration is as simple as using something like the following code:
```
OBJECT_ENTRY_AUTO(someClassID, SomeClassName);
```
This macro is placed in your header file somewhere, magic causes it to be registered with the singleton at the time the COM server is started. | A way to implement this is hard-coding a mapping from class 'names' to a factory function. Templates may make the code shorter. The STL may make the coding easier.
```
#include "BaseObject.h"
#include "CommonClasses.h"
template< typename T > BaseObject* fCreate( int param1, bool param2 ) {
return new T( param1, param2 );
}
typedef BaseObject* (*tConstructor)( int param1, bool param2 );
struct Mapping { string classname; tConstructor constructor;
pair<string,tConstructor> makepair()const {
return make_pair( classname, constructor );
}
} mapping[] =
{ { "class1", &fCreate<Class1> }
, { "class2", &fCreate<Class2> }
// , ...
};
map< string, constructor > constructors;
transform( mapping, mapping+_countof(mapping),
inserter( constructors, constructors.begin() ),
mem_fun_ref( &Mapping::makepair ) );
```
EDIT -- upon general request :) a little rework to make things look smoother (credits to Stone Free who didn't probably want to add an answer himself)
```
typedef BaseObject* (*tConstructor)( int param1, bool param2 );
struct Mapping {
string classname;
tConstructor constructor;
operator pair<string,tConstructor> () const {
return make_pair( classname, constructor );
}
} mapping[] =
{ { "class1", &fCreate<Class1> }
, { "class2", &fCreate<Class2> }
// , ...
};
static const map< string, constructor > constructors(
begin(mapping), end(mapping) ); // added a flavor of C++0x, too.
``` | Instantiate class from name? | [
"",
"c++",
"class",
"macros",
""
] |
So i'm trying out MVC after only playing with it some time ago.
Need to find the best way to selectively show and hide sections (divs, etc) on clicking or changing a value of a control, but not having to post back, i.e. javascript?
Any suggestions. | Use [jQuery](http://jquery.com/). You can use a jQuery Event to detect a click and then [hide](http://docs.jquery.com/Effects/hide) or [show](http://docs.jquery.com/Effects/show) divs.
So, You have a button called "HideDiv" and "DivToHide" is the div you wish to hide.
```
$("#HideDiv").click(function() {
$("#divToHide").hide();
};
```
It's that easy. Can't really go in-depth here but check out their tutorials: <http://docs.jquery.com/Tutorials> or browse this site: <http://www.learningjquery.com/category/levels/beginner>
jQuery actually comes with ASP.Net MVC, check the scripts folder of a new MVC project and you'll see it in there. This site using jQuery and MVC :) So your browsing a sample of what is possible with it | You can do the same way as you are doing it with normal ASP.NET application using JavaScript. I think JavaScript is best as its fast and works on client-side.
If you are having a specific requirement then please put the specific requirement here.
You can use jQuery or MooTools if you want some animation. | How to show/hide selected object like div? | [
"",
"javascript",
"asp.net-mvc",
""
] |
There is a very particular edge case in cross-domain policies regarding the window.top.Location object...
Let's say I have IFrame A , in domain www.bbb.com, living inside a page in domain www.aaa.com.
The page inside the IFrame can:
* Compare window.top.location to window.location (to detect whether it's being framed)
* Call window.top.location.replace(window.location) to redirect to self
* Call window.top.location.replace("any arbitrary string") to redirect somewhere else
But it cannot:
* Alert, Document.Write, or do any kind of output of window.top.location.href
* Concatenate it in any other variable, or use it in any useful way
* Call window.top.location.reload()
These are just the ones I could quickly find. I'm sure there are other edge cases.
It seems like the browser is not allowing the use of the top.location object if the top is in another domain, **except** for a few whitelisted things...
Is this documented anywhere?
Can I find what these whitelisted things are?
Is this in the HTML standard, and implemented equally in all browsers? Or is the implementation of this semi-random? | The security rules does differ with the version of browser. Generally newer versions have stricter rules, but also more fine tuned.
I suspect that older browsers would freely let you access the location object of the top frame, a little newer browsers would deny it totally, and the current versions let you compare location objects but not read from them.
You might be able find documentation about this, but it would be specific for each browser and specific for each version of the browser. As far as I know, there is no real standard for this. Each browser vendor tries to protect the user as much as possible, while still keeping some usability for the web site builder. Generally you can't really assume that anything close to the border works in all browsers, or that it will continue to work in future versions. | This is exactly specified by the [HTML5 standard in section 5.5.3.1](http://www.w3.org/TR/html5/browsers.html#security-location). | What exactly can an IFrame do with the top.Location object (cross-domain)? | [
"",
"javascript",
"security",
"iframe",
"cross-domain",
"window.location",
""
] |
The output of [/proc/net/dev](http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/en-US/Reference%5FGuide/s2-proc-dir-net.html) on Linux looks like this:
```
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo:18748525 129811 0 0 0 0 0 0 18748525 129811 0 0 0 0 0 0
eth0:1699369069 226296437 0 0 0 0 0 3555 4118745424 194001149 0 0 0 0 0 0
eth1: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
sit0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
How can I use Python to parse this output into key:value pairs for each interface? I have found [this forum topic](http://www.unix.com/shell-programming-scripting/90035-parsing-proc-net-dev-into-key-value-pairs-self-answered.html) for achieving it using shell scripting and there is [a Perl extension](http://cpansearch.perl.org/src/VSEGO/Linux-net-dev-1.00/dev.html) but I need to use Python. | this is pretty formatted input and you can easily get columns and data list by splitting each line, and then create a dict of of it.
here is a simple script without regex
```
lines = open("/proc/net/dev", "r").readlines()
columnLine = lines[1]
_, receiveCols , transmitCols = columnLine.split("|")
receiveCols = map(lambda a:"recv_"+a, receiveCols.split())
transmitCols = map(lambda a:"trans_"+a, transmitCols.split())
cols = receiveCols+transmitCols
faces = {}
for line in lines[2:]:
if line.find(":") < 0: continue
face, data = line.split(":")
faceData = dict(zip(cols, data.split()))
faces[face] = faceData
import pprint
pprint.pprint(faces)
```
it outputs
```
{' lo': {'recv_bytes': '7056295',
'recv_compressed': '0',
'recv_drop': '0',
'recv_errs': '0',
'recv_fifo': '0',
'recv_frame': '0',
'recv_multicast': '0',
'recv_packets': '12148',
'trans_bytes': '7056295',
'trans_carrier': '0',
'trans_colls': '0',
'trans_compressed': '0',
'trans_drop': '0',
'trans_errs': '0',
'trans_fifo': '0',
'trans_packets': '12148'},
' eth0': {'recv_bytes': '34084530',
'recv_compressed': '0',
'recv_drop': '0',
'recv_errs': '0',
'recv_fifo': '0',
'recv_frame': '0',
'recv_multicast': '0',
'recv_packets': '30599',
'trans_bytes': '6170441',
'trans_carrier': '0',
'trans_colls': '0',
'trans_compressed': '0',
'trans_drop': '0',
'trans_errs': '0',
'trans_fifo': '0',
'trans_packets': '32377'}}
``` | Does this help?
```
dev = open("/proc/net/dev", "r").readlines()
header_line = dev[1]
header_names = header_line[header_line.index("|")+1:].replace("|", " ").split()
values={}
for line in dev[2:]:
intf = line[:line.index(":")].strip()
values[intf] = [int(value) for value in line[line.index(":")+1:].split()]
print intf,values[intf]
```
Output:
```
lo [803814, 16319, 0, 0, 0, 0, 0, 0, 803814, 16319, 0, 0, 0, 0, 0, 0]
eth0 [123605646, 102196, 0, 0, 0, 0, 0, 0, 9029534, 91901, 0, 0, 0, 0, 0, 0]
wmaster0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
eth1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
vboxnet0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
pan0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
```
You could, of course, use the header names in `header_names` to construct a dict of dicts. | How can I parse the output of /proc/net/dev into key:value pairs per interface using Python? | [
"",
"python",
"linux",
"parsing",
""
] |
I need a reporting framework that would allow me to create reports with dynamic structure.
Unlike Jasper Reports working mode in which you create a template for how your report will look like, I need exactly the opposite: I need a framework that will allow me to create reports with varying structure (Programmatic).
The report is a table showing by which factors some result was calculated. The number of factors can vary, thus the number of columns in the table varies accordingly.
I would please like to know what reporting library can be used in the above described working mode.
Thank you for your time,
Maxim. | BIRT [Design Engine API](http://www.eclipse.org/birt/phoenix/deploy/designEngineAPI.php) was the tool I was looking for. | [DynamicJasper](http://dynamicjasper.sourceforge.net/index.html) may help you, here is an example extracted from [tutorial](http://dynamicjasper.sourceforge.net/docs/getting_started.html):
```
FastReportBuilder drb = new FastReportBuilder();
DynamicReport dr = drb.addColumn("State", "state", String.class.getName(),30)
.addColumn("Branch", "branch", String.class.getName(),30)
.addGroups(2)
.setTitle("November 2006 sales report")
.setSubtitle("This report was generated at " + new Date())
.setPrintBackgroundOnOddRows(true)
.setUseFullPageWidth(true)
.build();
JRDataSource ds = new JRBeanCollectionDataSource(TestRepositoryProducts.getDummyCollection());
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), ds);
JasperViewer.viewReport(jp); //finally display the report report
``` | Rending reports with dynamic structure (Not template based approach) | [
"",
"java",
"dynamic",
""
] |
Are there any libraries or methods to mock out the file system in C# to write unit tests? In my current case I have methods that check whether certain file exists and read the creation date. I may need more than that in future. | Edit: Install the NuGet package [`System.IO.Abstractions`](https://www.nuget.org/packages/System.IO.Abstractions).
This package did not exist when this answer was originally accepted. The original answer is provided for historical context below:
> You could do it by creating an interface:
>
> ```
> interface IFileSystem {
> bool FileExists(string fileName);
> DateTime GetCreationDate(string fileName);
> }
> ```
>
> and creating a 'real' implementation which uses
> System.IO.File.Exists() etc. You can then mock this interface using a
> mocking framework; I recommend [Moq](http://code.google.com/p/moq/).
>
> Edit: somebody's done this and kindly posted it online [here](http://bugsquash.blogspot.com/2008/03/injectable-file-adapters.html).
>
> I've used this approach to mock out DateTime.UtcNow in an IClock
> interface (really really useful for our testing to be able to control
> the flow of time!), and more traditionally, an ISqlDataAccess
> interface.
>
> Another approach might be to use [TypeMock](http://www.typemock.com/), this allows you to
> intercept calls to classes and stub them out. This does however cost
> money, and would need to be installed on your whole team's PCs and
> your build server in order to run, also, it apparently won't work for
> the System.IO.File, as it [can't stub mscorlib](http://www.typemock.com/community/viewtopic.php?p=1700#1700).
>
> You could also just accept that certain methods are not unit testable
> and test them in a separate slow-running integration/system tests
> suite. | [](https://i.stack.imgur.com/NtJAi.png)
This *imaginary* library exists now, there is a NuGet package for [System.IO.Abstractions](https://www.nuget.org/packages/System.IO.Abstractions), which abstracts away the System.IO namespace.
There is also a set of test helpers, System.IO.Abstractions.TestingHelpers which - at the time of writing - is only partially implemented, but is a very good starting point. | How do you mock out the file system in C# for unit testing? | [
"",
"c#",
"unit-testing",
"mocking",
""
] |
I grabbed this code form JCarousel and just trying to understand these lines below. I'm new to jQuery and not that great at JavaScript so I am not sure what is jQuery and which is JavaScript below
```
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);
```
It's setting some of the css to set state and either enabling or disabling the button that is in a but I want to modify this once I really understand it. I just can't make out exactly what it's doing 100%.
Trying to understand things such as [n ? 'bind' : 'unbind'] and just the chaining here also. There's a lot going on in those 4 lines.
The code comes from this plug-in: <http://sorgalla.com/projects/jcarousel/> | The first part to understand is symbol resolution. Javacript supports both dot-notation and bracket-notation.
Consider opening a new window.
```
window.open()
```
This is dot-notation in action. you're telling the interpreter that "open" can be found on "window". But there's another way to do this
```
window['open']()
```
Same thing, but with bracket notation. Instead of using the symbol name directly, we're using a string literal instead. What this means is that by using bracket-notation for symbol resolution, we can do it in a dynamic way, since we can choose or build strings on the fly, which is exactly what this snippet does.
```
this.buttonNext[n ? 'bind' : 'unbind'](...);
```
Is analagous to
```
if ( n )
{
this.buttonNext.bind(...);
} else {
this.buttonNext.unbind(...);
}
```
If you don't recognize the ?: syntax, that's the [conditional operator](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Conditional_Operator), or conditional expression
```
[expression] ? [valueIfTrue] : [valueIfFalse]
```
This is extremely often erroneously called the "ternary operator", when in fact it just *a* ternary operator (an operator with three operands). The reason for this is because in javascript (and most languages) is the *only* ternary operator, so that description usually flies.
Does that help? is there anything else you need cleared up? | ```
[n ? 'bind' : 'unbind']
```
Is an if statement, which can be rewritten as
```
if (n) // if n is true
{
'bind';
}
else
{
'unbind';
}
```
So if n is true, it would evaluate like this
```
this.buttonNext.bind((this.options.buttonNextEvent, this.funcNext))
```
because [ ] notation is the same as . notation.
```
buttonNext[bind] is the same as buttonNext.bind
```
To summarize what you posted, it checks the states of variables (n and p)
which holds the state of the button. If it is enabled, then when activated it disables it, adds the disabled classes, etc. If it's disabled, it sets it to enabled and removes the disabled class. | Help understanding jQuery button enable/disable code | [
"",
"javascript",
"jquery",
""
] |
> **Possible Duplicate:**
> [How do I specify the equivalent of volatile in VB.net?](https://stackoverflow.com/questions/929146/how-do-i-specify-the-equivalent-of-volatile-in-vb-net)
What is the VB.NET keyword equivalent of C# "volatile"?
If there is no keyword what mechanism is the equivalent? | There is no equivelent to C#'s volatile keywword in VB.NET. Volatile in C# just makes sure the compiler handles things differently when generating the IL, but the VB.NET compiler does not have this option.
You can work around it this way ([taken from this blog post](http://www.panopticoncentral.net/archive/2004/09/30/1721.aspx)):
```
Function VolatileRead(Of T)(ByRef Address As T) As T
VolatileRead = Address
Threading.Thread.MemoryBarrier()
End Function
Sub VolatileWrite(Of T)(ByRef Address As T, ByVal Value As T)
Threading.Thread.MemoryBarrier()
Address = Value
End Sub
``` | Use `Thread.VolatileRead()` and `VolatileWrite()` methods from the BCL.
<http://msdn.microsoft.com/en-us/library/system.threading.thread.volatileread.aspx> | Volatile equivalent in VB.NET | [
"",
"c#",
"vb.net",
"multithreading",
"volatile",
""
] |
I'm not sure how simple this would be, but I'm using a script which displays the files from a specific folder, however I'd like them to be displayed in alphabetical order, would it be hard to do this? Here's the code I'm using:
```
if ($handle = opendir($mainframe->getCfg( 'absolute_path' ) ."/images/store/")) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (($file != "index.html")&&($file != "index.php")&&($file != "Thumbs.db")) {
$strExt = end(explode(".", $file));
if ($strExt == 'jpg') {
$Link = 'index.php?option=com_shop&task=deleteFile&file[]='.$file;
$thelist .= '<tr class="row0"><td nowrap="nowrap"><a href="'.$Link.'">'.$file.'</a></td>'."\n";
$thelist .= '<td align="center" class="order"><a href="'.$Link.'" title="delete"><img src="/administrator/images/publish_x.png" width="16" height="16" alt="delete"></a></td></tr>'."\n";
}
}
}
}
closedir($handle);
}
echo $thelist;
```
:) | Instead of using `readdir` you could simply use `scandir` ([documentation](http://tw.php.net/manual/en/function.scandir.php)) which sorts alphabetically by default.
The return value of `scandir` is an array instead of a string, so your code would have to be adjusted slightly, to iterate over the array instead of checking for the final `null` return value. Also, `scandir` takes a string with the directory path instead of a file handle as input, the new version would look something like this:
```
foreach(scandir($mainframe->getCfg( 'absolute_path' ) ."/images/store/") as $file) {
// rest of the loop could remain unchanged
}
``` | That code looks pretty messy. You can separate the directory traversing logic with the presentation. A much more concise version (in my opinion):
```
<?php
// Head of page
$it = new DirectoryIterator($mainframe->getCfg('absolute_path') . '/images/store/'));
foreach ($it as $file) {
if (preg_match('#\.jpe?g$#', $file->getFilename()))
$files[] = $file->getFilename();
}
sort($files);
// Further down
foreach ($files as $file)
// display links to delete file.
?>
```
You don't even need to worry about opening or closing the handle, and since you're checking the filename with a regular expression, you don't need any of the explode or conditional checks. | PHP (folder) File Listing in Alphabetical Order? | [
"",
"php",
"file",
"directory",
"alphabetized",
""
] |
I'm new to Spring MVC, but not new to web development in Java. I'm attempting to create a simple form->controller example.
I have a form, a form controller (configured in a context XML pasted below) and my model (a simple bean). When I submit the form the value of my text input is always null, regardless. Any ideas?
Form controller spring configuration:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- controllers -->
<bean name="/home.html" class="atc.web.view.controller.HomeController" />
<!--bean name="/mirror.html" class="atc.web.view.controller.MirrorController" -->
<bean name="/url-cache.html" class="atc.web.view.controller.URLCacheFormController">
<property name="synchronizeOnSession" value="true" />
<!--property name="sessionForm" value="false"-->
<property name="commandName" value="urlForm"/>
<property name="commandClass" value="atc.web.view.model.URLBean"/>
<property name="validator">
<bean class="atc.web.view.validators.URLValidator"/>
</property>
<property name="formView" value="mirror"/>
<property name="successView" value="url-cache.html"/>
<property name="URLCachingService" ref="urlCachingService" />
</bean>
<!-- end controllers -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- custom beans -->
<bean id="breakcrumbInjectionFilter" class="atc.web.view.filter.BreadcrumbInjectionFilter">
<property name="contextPrefix" value="/home-web" />
</bean>
<!-- end custom beans -->
</beans>
```
The JSP that contains my form is as follows:
```
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/jspf/core/taglibs.jspf" %>
<html>
<head><title>Simple tools</title></head>
<style>
.error s {
color:#FF0000;
}
</style>
<body>
<%@ include file="/WEB-INF/jspf/nav/nav.jspf" %>
Errors: <form:errors path="url" cssClass="error"/>
<form:form method="post" commandName="urlForm">
<form:input path="url" />
<input type="submit" align="center" value="Execute" />
</form:form>
</body>
</html>
```
Here's the full source of my controller:
```
public class URLCacheFormController extends SimpleFormController {
private URLCachingService cachingService;
private static Logger log = Logger.getLogger(URLCacheFormController.class);
public ModelAndView onSubmit(Object command) throws ServletException {
log.debug(String.format("URLCachingFormController received request with object '%s'", command));
URLBean urlBean = (URLBean) command;
try {
URL url = new URL(urlBean.getUrl());
URLCache cache = cachingService.cacheURL(url);
cache.cacheToTempFile();
} catch (IOException e) {
log.error("Invalid URL...", e);
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
log.debug("formBackingObject() ");
return new URLBean();
}
public void setURLCachingService(URLCachingService cachingService) {
this.cachingService = cachingService;
}
}
```
All of the above produces the following HTML:
```
<html>
<head></head>
<body>
<div><span><a href="home.html">Home </a></span><span> | <a href="url-cache.html">Page Mirror</a></span></div>
<div id="breadcrumb"><span>Your trail:<a href=""/></span></div>Attrs:<div/>
<form id="urlForm" method="post" action="/home-web/url-cache.html">
<input id="url" type="text" value="" name="url"/>
<input type="submit" align="center" value="Execute"/>
</form>
</body>
</html>
```
I'm now overriding `doSubmitAction(Object command)` but I still do not hit the method. The form submits but the next thing I know I'm presented with the blank form (after `formBackingObject(HttpServletRequest request)` is called).
That's to say, when I submit, the logging call on line 1 of `doSubmitAction` in the form controller is never executed. **The validator executes, and fails (adds error messages correctly) because the value it's checking is always null *(or put correctly, it's never set)***. The call to `formBackingObject` always occurs however. The request attribute of my form (the form input 'url') is always null.
**Update:** OK, so after some serious debugging as suggested by serg555, and removing validation, I can confirm the issue seems to be with mapping the request parameters - such as the value of 'url' from the form - to my command/bean; i.e. the URL is never being set on my bean, or the bean is being recreated.
Please help? | The cause was the fact that my form bean was not adhering to the Java Bean contract - the setter returned instead of being void and thus couldn't be matched by Spring to invoke. | I don't know where is the problem, let me show you my controller that works and maybe you will be able to figure out what's wrong:
```
public class TestController extends SimpleFormController {
public TestController () {
setFormView("testView");
setSuccessView("testView");
setCommandClass(TestCmd.class);
setCommandName("cmd");
}
protected Object formBackingObject(HttpServletRequest request)throws Exception {
Object o = super.formBackingObject(request);
TestCmd cmd = (TestCmd) o;
return cmd;
}
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception {
TestCmd cmd = (TestCmd) obj;
log.debug("test value = " + cmd.getTestValue());
return super.onSubmit(request, response, obj, errors);
}
}
```
Form:
```
<form method="post" action="/test.html">
<form:input path="cmd.testValue"/>
<input type="submit">
</form>
```
Inside App-servlet.xml:
```
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/test.html">testController</prop>
</props>
</property>
</bean>
<bean id="testController"
class="com.sample.TestController">
<property name="synchronizeOnSession" value="true" />
<property name="validator">
<bean class="com.sample.TestValidator"/>
</property>
</bean>
```
Validator:
```
public class TestValidator implements Validator {
public boolean supports(Class clazz) {
return (TestCmd.class.equals(clazz));
}
public void validate(Object obj, Errors errors) {
TestCmd cmd = (TestCmd) obj;
if (obj == null) {
// nothing
} else {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "testValue", null, "<b>Value</b> is required");
}
}
}
```
Command:
```
public class TestCmd {
private String testValue;
public TestCmd() {
}
public String getTestValue() {
return testValue;
}
public void setTestValue(String testValue) {
this.testValue = testValue;
}
}
``` | Spring MVC form input value is always null | [
"",
"java",
"spring",
"jakarta-ee",
"spring-mvc",
""
] |
```
static void Main()
{
string str;
str = Console.ReadLine();
while (str != null)//HERE!
{
str = str.Remove(0, 1);
str = str.Remove(str.Length - 1, 1);
string[] value = str.Split(',');
int[] intval = new int[value.Length];
for (int i = 0; i < value.Length; ++i)
{
bool re = int.TryParse(value[i], out intval[i]);
Console.WriteLine(intval[i]);
}
str = Console.ReadLine();
}
}
```
Hi, in the program above, I want to judge whether there is stuff not read in the console using "str!=null".
However,the ReadLine() returned a "" to me instead of a null,
and the program can get into the while loop and generate a wrong result.
How can I fix it? | ```
while(!string.IsNullOrEmpty(str))
```
check it for both with the built in method
if it comes back empty they just pressed enter, and you've it your sentinel either way, so you can fail on that. | From the docs:
> If the CTRL+Z character is pressed when the method is reading input from the console, the method returns a null reference (Nothing in Visual Basic). This enables the user to prevent further keyboard input when the ReadLine method is called in a loop.
So you can indeed get a null reference back from calling ReadLine(). The String.IsNullOrEmpty method will check both cases for you though. | Question on Console.ReadLine() in C# | [
"",
"c#",
"console",
""
] |
I cant quite get my head around what the ^ is doing in my preg\_match.
```
if (preg_match('~^(\d\d\d\d)(-(\d{1,2})(-(\d{1,2}))?)?$~', trim($date), $dateParts)) {
echo the $dateparts and do some magic with them
} else {
tell me the date is formatted wrong
}
```
As I see it this is looking to see if the $date matches the format which I read as
4 decimals - 1 or 2 decimals - 1 or 2 decimals
if it does match then the IF statement displays the date, if it doesn't then it gives an error of incorrect date formatting.
However just passing it the year
$date = '1977' with nothing else (no day or month) it still goes through as true and displays the dateparts, I would thought it would throw an error?
Can someone point out what I'm missing in the regular expression? I'm guessing it's the ^ or possibly the ?$ at the end may mean only match part of it? | There is no need to group *absolutely everything*. This looks nicer and will do the same:
```
preg_match('~^\d{4}(-\d{1,2}(-\d{1,2})?)?$~', trim($date), $dateParts)
```
This also explains why "`1977`" is accepted - the month and day parts are *both* optional (the question mark makes something optional).
To do what you say ("4 decimals - 1 or 2 decimals - 1 or 2 decimals"), you need to remove both the optional groups:
```
preg_match('~^\d{4}-\d{1,2}-\d{1,2}$~', trim($date), $dateParts)
```
The "`^`" and "`$`" have nothing to do with the issue you are seeing. They are just start-of-string and end-of-string anchors, making sure that *nothing else* than what the pattern describes is in the checked string. Leave them off and `"blah 1977-01-01 blah"` will start to match. | Try this:
```
'~^(\d\d\d\d)-(\d{1,2})-(\d{1,2})$~'
```
The problem was the regex was allowing the month and day as optional by the '?' character. | Preg Match circumflex ^ in php | [
"",
"php",
"regex",
"preg-match",
""
] |
I'm creating a basic forum where every message contains the authors name, some text and the date it was created. I'd like the forum to update constantly through AJAX, and show new posts that were created on the fly.
I currently have a PHP file `getlatest.php?lastid=...` that retrieves all posts from the ID given to the most current.
It returns the data in HTML, like so (i've altered it so you can see the divs, stackoverflow throws them out):
```
foreach ($print as $value)
{
$readyText .= div id = $value->post_id;
$readyText .= $value->first_name.' '.$value->last_name.' posted the following:'.
$value->post_text.' The post was made about '.$time.' ago.
$readyText .= '/div>';
}
```
I have some AJAX code in jquery that retrieves every few moments
```
setInterval("update()", 3000);
function update()
{
$.get("getlatest.php",
{
id: latestmessage
},
function(response){
$("#forum_entries").prepend(response);
latestmessage = $.cookie('last_post_id'); //This is
//how I know what the latest post id is
}, "html");
```
I wanted to highlight all the new posts that were submitted using the (now very popular) yellow fade technique, like so
```
$("#somediv").effect("highlight", {}, 1500);
```
My question is - to what div to I apply this effect?
I should add that back in PHP, every forum post had a div id that was actually its PK in the database. | Change your function so that instead of using prepend, it uses [prependTo](http://docs.jquery.com/Manipulation/prependTo#selector). PrependTo will return the elements that were prepended and you can apply the highlight to those elements (using jQuery 1.3.2).
```
$.get('getlatest.php',
{ id: latestmessage },
function(response) {
$(response).prependTo('#forum_entries').effect('highlight',{},1500);
latestmessage = $.cookie('last_post_id');
}, 'html' );
``` | Just give your Div an active class:
```
<?php
foreach ($print as $value)
{
$readyText .= '<div id = "' . $value->post_id . '" class="active"';
$readyText .= $value->first_name.' '.$value->last_name.' posted the following:'.
$value->post_text.' The post was made about '.$time.' ago.
$readyText .= '</div>';
}
?>
setInterval("update()", 3000);
function update()
{
$.get("getlatest.php",
{
id: latestmessage
},
function(response){
$("#forum_entries").prepend(response);
latestmessage = $.cookie('last_post_id');
$("div.active").effect("highlight", {}, 1500);
$("div.active").toggleClass("active");
}, "html");
```
As I already suggested in an answer to your previous question it would really make sense for you to learn a little bit of JavaScript in combination with one of the popular Libraries/Frameworks (I'd recommend [jQuery](http://jquery.com/) which the example above uses). | selecting divs retrieved through AJAX in jquery | [
"",
"php",
"jquery",
"css",
"html",
""
] |
In general, I have the following scenario:
* Fetch product and its related data from database
* Convert fetched data to php 'product' object
* cache product object in session
The cache is readonly, i.e customers viewing products on the site.
But there are calls like `getProductIdsByCategory($categoryId)` and the productIds from these results are cached too, per user, not using the global cache that I've read about.
A problem is that if someone on the admin side adds a new product and relates it to a category, then customers will not have the new productId come up in their cached `getProductIdsByCategory` until a new session is started.
Is there a way to clear e.g `$_SESSION['x']` from ALL sessions on the server when a new product is added? I don't want to destroy all sessions because customers will then lose their logins etc.
Or should I move these cached productId searches to the global cache?
p.s am using a custom built cache, not memcached or similar.
Thanks | By default, the session data is just serialized files somewhere in your filesystem, and it is possible to go modify all of them to remove the information in question (respecting locking so that you don't step on any currently open sessions).
I don't really recommend it, though. What I would recommend is making a method of signalling that this cached data should be refreshed, like a database-stored timestamp that gets looked at when `session_start()` happens, and if the cached data is older than the timestamp, the cache is flushed. | Sounds to be like you could do with **real shared state** through a caching system like memcache.
The only other way that prints to mind is have the application check for flags for dirty cache data and delete it itself, or if your cache is in a database in a parsable serialized form write an **expensive** script to read them all, but that will create nasty lag with requests that have already read the data.
I would go with real shared state than checking for object copies. | Is there a way to clear some session data from ALL sessions? | [
"",
"php",
"session",
"caching",
"global",
""
] |
I have a asp:GridView which contains a asp:TextBox within a TemplateField. I would like to obtain it's ID for use in javascript. Something like this:
```
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="textDateSent" runat="server" />
<input type="button" value='Today'
onclick="setToday('<%# textDateSent.ClientID %>');" />
</ItemTemplate>
</asp:TemplateField>
```
But when I compile, I get an error:
> The name 'textDateSent' does not exist in the current context
Anybody know how to get the client ID of this TextBox? | Try this:
```
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="textDateSent" runat="server">
</asp:TextBox>
<input type="button" value='Today' onclick="setToday('<%# ((GridViewRow)Container).FindControl("textDateSent").ClientID %>');" />
</ItemTemplate>
</asp:TemplateField>
``` | Maybe you don't want to do it where you need the ClientID. Check out this post [here](http://blog.digitaltools.com/post/2009/07/14/How-to-Work-With-a-GridView-Row-in-JavaScript.aspx) where the controls in a row are referenced in a generic way. | How do I find the Client ID of control within an ASP.NET GridView? | [
"",
"asp.net",
"javascript",
"gridview",
"databound",
""
] |
Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if `self.a`, `self.b`, and `self.c` are greater than 0, which would mean that I have Angle, Angle, Angle.
Below you will see the code that checks for A and B, however when I use just `self.a != 0` then it works fine. I believe I'm not using `&` correctly. Any ideas? Here is how I am calling it: `print myTri.detType()`
```
class Triangle:
# Angle A To Angle C Connects Side F
# Angle C to Angle B Connects Side D
# Angle B to Angle A Connects Side E
def __init__(self, a, b, c, d, e, f):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
def detType(self):
#Triangle Type AAA
if self.a != 0 & self.b != 0:
return self.a
#If self.a > 10:
#return AAA
#Triangle Type AAS
#elif self.a = 0:
#return AAS
#Triangle Type ASA
#Triangle Type SAS
#Triangle Type SSS
#else:
#return unknown
``` | You should write :
```
if (self.a != 0) and (self.b != 0) :
```
"`&`" is the bit wise operator and does not suit for boolean operations. The equivalent of "`&&`" is "and" in Python.
A shorter way to check what you want is to use the "in" operator :
```
if 0 not in (self.a, self.b) :
```
You can check if anything is part of a an iterable with "in", it works for :
* Tuples. I.E : `"foo" in ("foo", 1, c, etc)` will return true
* Lists. I.E : `"foo" in ["foo", 1, c, etc]` will return true
* Strings. I.E : `"a" in "ago"` will return true
* Dict. I.E : `"foo" in {"foo" : "bar"}` will return true
**As an answer to the comments :**
Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.
For the triangle check, it's easier to read :
```
0 not in (self.a, self.b, self.c)
```
Than
```
(self.a != 0) and (self.b != 0) and (self.c != 0)
```
It's easier to refactor too.
Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs. | Use the keyword `and`, not `&` because `&` is a bit operator.
Be careful with this... just so you know, in Java and C++, the `&` operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is `&&`. Similarly `|` is a bit operator, and `||` is a boolean operator. In Python `and` and `or` are used for boolean comparisons. | Using the AND and NOT Operator in Python | [
"",
"python",
"operators",
""
] |
What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?
It shouldn't matter if the two Lists are the same instance or not, and it shouldn't matter if the type parameter of the Lists are different.
e.g.
```
List list1
List<String> list2;
// ... construct etc
list1.add("A");
list2.add("A");
// the function, given these two lists, should return true
```
There's probably something staring me in the face I know :-)
---
EDIT: To clarify, I was looking for the EXACT same elements and number of elements, in order. | If you care about order, then just use the equals method:
```
list1.equals(list2)
```
From the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#equals-java.lang.Object-):
> Compares the specified object with
> this list for equality. Returns true
> if and only if the specified object is
> also a list, both lists have the same
> size, and all corresponding pairs of
> elements in the two lists are equal.
> (Two elements e1 and e2 are equal if
> (e1==null ? e2==null :
> e1.equals(e2)).) In other words, two
> lists are defined to be equal if they
> contain the same elements in the same
> order. This definition ensures that
> the equals method works properly
> across different implementations of
> the List interface.
If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:
```
public static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
return new HashSet<>(list1).equals(new HashSet<>(list2));
}
```
A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if `list1` was ["A", "B", "A"] and `list2` was ["A", "B", "B"] the `Set` approach would consider them to be equal.
If you need to be insensitive to order but sensitive to the frequency of duplicates you can either:
* sort both lists (or copies) before comparing them, as done in [this answer to another question](https://stackoverflow.com/a/13501200/496289)
* or copy all elements to a [Multiset](http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/Multiset.java) | I posted a bunch of stuff in comments I think it warrants its own answer.
As everyone says here, using equals() depends on the order. If you don't care about order, you have 3 options.
**Option 1**
Use `containsAll()`. This option is not ideal, in my opinion, because it offers worst case performance, O(n^2).
**Option 2**
There are two variations to this:
**2a)** If you don't care about maintaining the order ofyour lists... use `Collections.sort()` on both list. Then use the `equals()`. This is O(nlogn), because you do two sorts, and then an O(n) comparison.
**2b)** If you need to maintain the lists' order, you can copy both lists first. THEN you can use solution **2a** on both the copied lists. However this might be unattractive if copying is very expensive.
This leads to:
**Option 3**
If your requirements are the same as part **2b**, but copying is too expensive. You can use a TreeSet to do the sorting for you. Dump each list into its own TreeSet. It will be sorted in the set, and the original lists will remain intact. Then perform an `equals()` comparison on both `TreeSet`s. The `TreeSets`s can be built in O(nlogn) time, and the `equals()` is O(n).
Take your pick :-).
***EDIT:*** I almost forgot the same caveat that [Laurence Gonsalves](https://stackoverflow.com/users/90848/laurence-gonsalves) points out. The TreeSet implementation will eliminate duplicates. If you care about duplicates, you will need some sort of sorted multiset. | Simple way to find if two different lists contain exactly the same elements? | [
"",
"java",
"collections",
""
] |
I found this script:
```
<script language="Javascript" TYPE="text/javascript">
var container = document.getElementById('dl');
var seconds = 10;
var timer;
function countdown() {
seconds--;
if(seconds > 0) {
container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
} else {
container.innerHTML = '<a href="download.php">Download</a>';
clearInterval(timer);
}
}
timer = setInterval(countdown, 1000);
</script>
```
and I'm trying to call it with:
```
<input type="button" onclick="countdown()" id="dl" value="Download" />
```
but nothing happens. What am I doing wrong? I have JavasScript enabled but nothing happens after I click the button. | The script is starting itself with the setInterval function call, and is assigning the countdown to the element with the innerHTML property.
If you want to show that in the button, you should use the value property of the element and change the behaviour (i.e.: the link will not work there) or use a span or div element instead the button. | I fixed the code you posted by putting the input type inside the div tags so it removes "download" button once you click it and the timer starts.
```
<div id="dl">
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Download" />
</div>
<script language="Javascript" TYPE="text/javascript">
var container = document.getElementById('dl');
var seconds = 10;
var timer;
function countdown() {
seconds--;
if(seconds > 0) {
container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
} else {
container.innerHTML = '<a href="File or Page Location">Download File</a>';
clearInterval(timer);
}
}
</script>
``` | Why isn't my JavaScript countdown function doing anything? | [
"",
"javascript",
""
] |
I've got a C++ project where we have loads and loads of dependencies. The project should work on Linux and Windows, so we've ported it to CMake. Most dependencies are now included right into the source tree and build alongside the project, so there are no problems with those.
However, we have one binary which depends on Fortran code etc. and is really complicated to build. For Linux, it's also not available as a package, but only as precompiled binaries or with full source (needs a BLAS library installed and several other dependencies). For windows, the same library is available as binary, building for Windows seems even more complicated.
The question is, how do you handle such dependencies? Just check in the binaries for the supported platforms, and require the user to set up his build environment otherwise (that is, manually point to the binary location), or would you really try to get them compiled along (even if it requires installing like 10 libraries -- BLAS libraries are the biggest pain here), or is there some other recommended way to handle that? | If the binary is independant of the other part of your build process, you definitively should check-in it. But as you cannot include every version of the binary (I mean for every platform and compile flags the user might use) the build from source seems mandatory.
I have done something similar. I have checked-in the source code archives of the libraries/binaries I needed. Then I wrote makefile/scripts to build them according to the targeted platform/flags in a specific location (no standard OS location) and make my main build process to point to the right location. I have done that to be able to handle the correct versions and options of the libraries/binaries I needed. It's quite a hard work to make things works for different platforms but it's worth the time !
Oh, and of course it's easier if you use crossplatform build tools :) | One question to you. Does the users need to modify this binary, or are they just happy it's there so the can use/access it? If they don't need to modify it, check in the binaries. | Handling binary dependencies across platforms | [
"",
"c++",
"cross-platform",
"dependencies",
""
] |
I'm creating a contact form for my company and I want to make it as spam-proof as possible. I've created a honey pot + session checking, but I also want to make it so that it's only possible to submit the form once every x minutes. In other words, banning the IP from using the form for x amount of time.
What is the best solution to do this?
I can think of a few but none of them seem ideal. | Store the users IP in a database every time the form is submitted, along with the timestamp. When a user submits the form, first check the database to see if they submitted within the timeframe.
Some problems could arise from large networks where users could the same IP though. It depends on the target audience, really. | Database. Store the IPs in there and timestamp them. | PHP Temporarily Banning An IP | [
"",
"php",
""
] |
Does Drupal parse (and/or run) hooks that are unrelated to the content being loaded by the current user?
For example, say I had a module `foo` installed and active with the following hooks:
```
<?php
// .. stuff ...
function foo_menu() {
$items = array();
$items['foo/show'] = array(
'title' => t('Foo!'),
'page callback' => 'foo_display_all',
'description' => 'All our foo are belong to you',
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function foo_display_all() {
// About 100 lines of code
}
// ... stuff ...
```
Would Drupal parse (and thus effect the load time) for pages that aren't listed in `foo_menu`? Put another way, would the length and complexity of `foo_display_all` effect how www.example.com/bar loads?
At risk of having two different questions here, I'll say I would be grateful for an explanation (or link to an explanation) of how and why Drupal does or does not parse, rather than a yes/no answer. | hook\_menu is used to tell drupal about what to do at specific urls, so the result of that is cached.
Drupal will only execute the content of the hooks themselves not the entire content of the file they are located in. So when hook menu is invoked in the above example, on the foo\_menu() function will be run.
You can take a look at the intro text at the [Hooks API](http://api.drupal.org/api/group/hooks)
Edit:
In order for PHP to execute the function, it needs to include the file where it is located. So when Drupal wants to execute a hook, PHP would need to parse the code in that file. That is just how PHP is designed, so haven't got much to do with Drupal.
This is also the reason why a lot of modules make a lot of inc files, to limit the amount of code needed to be parsed when hooks are fired. | Yes. As others have noted, splitting things out into include files that are loaded conditionally is the only way to cut that down. Starting in Drupal 6, it became possible to move theme\_whatever() functions, as well as hook\_menu() page callbacks, into separate include files. Drupal will automatically load them when they're needed without you doing any explicit require\_once() juggling.
See the [hook\_menu()](http://api.drupal.org/api/function/hook_menu) and [hook\_theme()](http://api.drupal.org/api/function/hook_theme) documentation for details.
It's also important to note that if you're running an opcode cache like APC, splitting things into a bunch of conditional includes is actually *worse* -- APC can do all of the parsing and compiling of the PHP source in one go and persist it between requests. Splitting things out conditionally just gives it multiple discrete 'codebases' to compile depending on what's being done.
In the currently-under-development Drupal 7, a general [Code registry](http://api.drupal.org/api/group/registry/7) has been added that allows any hook implementation to be split out into a separate include file. However, the overhead of managing that internal cache of functions and .inc locations, and loading them on the fly, eats up the performance gains of the smaller-to-parse codebase. The only real payoff is reduced memory usage for those on shared hosts with tight 12-16 meg memory limits; it's unclear whether the change will survive through to the final release of Drupal 7 given the tradeoffs.
**The upshot:** in Drupal 6, split out the menu callbacks that build custom pages into a separate .inc file, and it will only be loaded when those pages are built. Do the same with any theme functions. And *if you're using an opcode cache* like APC, remember that your separate .inc files are only good for organizational purposes -- they won't give you any performance boost. | Does Drupal parse hooks that aren't being used? | [
"",
"php",
"optimization",
"drupal",
"drupal-6",
"hook",
""
] |
I would like to know how to output an array of doubles to the hard drive.
edit:
for further clarification. I would like to output it to a file on the hard drive (I/O functions). Preferably in a file format that can be quickly translated back into an array of doubles in another program. It would also be nice if it was stored in a standard 4 byte configuration so that i can look at it through a hex viewer and see the actual values. | Hey... so you want to do it in a single write/read, well its not too hard, the following code should work fine, maybe need some extra error checking but the trial case was successful:
```
#include <string>
#include <fstream>
#include <iostream>
bool saveArray( const double* pdata, size_t length, const std::string& file_path )
{
std::ofstream os(file_path.c_str(), std::ios::binary | std::ios::out);
if ( !os.is_open() )
return false;
os.write(reinterpret_cast<const char*>(pdata), std::streamsize(length*sizeof(double)));
os.close();
return true;
}
bool loadArray( double* pdata, size_t length, const std::string& file_path)
{
std::ifstream is(file_path.c_str(), std::ios::binary | std::ios::in);
if ( !is.is_open() )
return false;
is.read(reinterpret_cast<char*>(pdata), std::streamsize(length*sizeof(double)));
is.close();
return true;
}
int main()
{
double* pDbl = new double[1000];
int i;
for (i=0 ; i<1000 ; i++)
pDbl[i] = double(rand());
saveArray(pDbl,1000,"test.txt");
double* pDblFromFile = new double[1000];
loadArray(pDblFromFile, 1000, "test.txt");
for (i=0 ; i<1000 ; i++)
{
if ( pDbl[i] != pDblFromFile[i] )
{
std::cout << "error, loaded data not the same!\n";
break;
}
}
if ( i==1000 )
std::cout << "success!\n";
delete [] pDbl;
delete [] pDblFromFile;
return 0;
}
```
Just make sure you allocate appropriate buffers! But thats a whole nother topic. | Use std::copy() with the stream iterators. This way if you change 'data' into another type the alterations to code would be trivial.
```
#include <algorithm>
#include <iterator>
#include <fstream>
int main()
{
double data[1000] = {/*Init Array */};
{
// Write data too a file.
std::ofstream outfile("data");
std::copy(data,
data+1000,
std::ostream_iterator<double>(outfile," ")
);
}
{
// Read data from a file
std::ifstream infile("data");
std::copy(std::istream_iterator<double>(infile),
std::istream_iterator<double>(),
data // Assuming data is large enough.
);
}
}
``` | How to output array of doubles to hard drive? | [
"",
"c++",
""
] |
I'm trying to glue together two web services by passing a value from one to the other, unfortunately there's no API or clear way of hacking up the search query so I need to set the value of a input inside an iframe.
Here's the markup for the horrible iframe.
```
<form id="searchForm" method="post" action="/search/initialSearch">
<fieldset class="searchFields">
<input type="text" name="searchTerm" value=""/>
<input type="submit" value="Find stops"/>
</fieldset>
</form>
```
I need to set the searchTerm text and then submit the form.
**Note: This is going over mobile, so I would prefer a really lightweight solution** | Isn't it as simple as:
```
myframe.document.getElementById("searchForm").searchTerm.value = 'hello';
myframe.document.getElementById("searchForm").submit();
```
Make sure your script runs AFTER the `iframe` is loaded. Your `iframe` tag has an `onload` event that you can use to determine when the page within the frame is loaded.
```
<iframe src="formPage.html" onload="loaded()" name="myframe" />
``` | just be aware that if your iframe's source is not coming from your server, it is impossible to access its contents with javascript from the page that contains the iframe. If you have access to the contents of the iframe that is coming from another server, then you can access all of the data from the parent page with:
```
window.top
```
If you do not have access to the iframe's page, then there is nothing you can do. | Set input text inside iframe and submit | [
"",
"javascript",
"html",
"forms",
"iframe",
""
] |
I have an issue with php where code works on on computer but wont work on another
```
function appendParam(&$req, $name, $value) {
if (req == null) {
return;
}
if (name == null) {
return;
}
if (value != null) {
$req[$name] = $value;
}
}
```
The above works on one computer and is capable of checking req and name against null properly and the variables is the if condition don't need dollar signs (when i put the dollar signs in they break on this computer)
but i need to use the following code on another computer to get the same end result
```
function appendParam(&$req, $name, $value) {
if ($value != null) {
$req[$name] = $value;
}
if ($name == null) {
return;
}
if ($req == null) {
return;
}
}
```
on this other computer it isn't capable of checking name or req against null (it breaks)
and i need the dollar signs on the variables in the if condition.
As a side note it also seems that this computer can't read from an array index that isn't already initialized.
Any help is appreciated | The 2 machines might have different warning levels or error reporting levels.
I'm confused, surely you should have the $ prefix before any php variable name otherwise you're not actually checking on the variable? What are you trying to achieve by not using the $ prefix | This code makes very little sense to me:
```
function appendParam(&$req, $name, $value) {
if ($value != null) {
$req[$name] = $value;
}
if ($name == null) {
return;
}
if ($req == null) {
return;
}
}
```
It should be written like so:
```
function appendParam(&$req, $name, $value)
{
if(empty($name) || empty($value) || empty($req))
return;
$req[$name] = $value;
}
```
When you say it "breaks" can you give a specific example/error you're getting and how you're using the function? I'm thinking you're using it incorrectly. | PHP acts differently depending on computer | [
"",
"php",
"arrays",
"pass-by-reference",
""
] |
I've sometimes seen code written like this :
```
public class B1
{
}
public class B2
{
private B1 b1;
public B1 B1
{
get { return b1; }
set { b1 = value; }
}
}
```
i.e. class B2 has a property named "B1", which is also of type "B1".
My gut instinct tells me this is not a good idea, but are there any technical reasons why you should avoid giving a property the same name as its class ?
(I'm using .net 2.0, in case that matters). | It's fine. The canonical example here is
```
public Background {
public Color Color { get; set; }
}
```
There are rare issues (corner cases) that come up here, but not enough to warrant avoiding this device. Frankly, I find this device quite useful. I would not enjoy not being able to do the following:
```
class Ticker { ... }
public StockQuote {
public Ticker Ticker { get; set; }
}
```
I don't want to have to say `Ticker StockTicker` or `Ticker ThisTicker` etc. | The [Microsoft Naming Guideline for Members](http://msdn.microsoft.com/en-us/library/ms229012.aspx) state:
> **Consider giving a property the same name as its type.**
>
> When you have a property that is strongly typed to an enumeration, the name of the property can be the same as the name of
> the enumeration. For example, if you have an enumeration named
> `CacheLevel`, a property that returns one of its values can also be
> named `CacheLevel`.
Though I admit there is a little ambiguity whether they are just recommending this for Enums or for properties in general. | Should a property have the same name as its type? | [
"",
"c#",
".net",
"naming-conventions",
""
] |
I am generating 10 random floats between 6 and 8 (all for good reason), and writing them to a mysql database in a serialized form. But one quirk seems to emerge at the storage time:
Before storing I'm just outputting the same data to see what it looks like, and this is the result I get
```
a:10:{i:0;d:6.20000000000000017763568394002504646778106689453125;i:1;d:7.5999999999999996447286321199499070644378662109375;i:2;d:6.4000000000000003552713678800500929355621337890625;..}
```
As you can see, I'm getting long numbers like 6.20000000000000017763568394002504646778106689453125
instead of what I'd really to like see, just 6.2. This is happening only when I serialize the data, if I just output the array, I do get the floats to one decimal.
Here is my code:
```
function random_float ($min,$max) {
return ($min+lcg_value()*(abs($max-$min)));
}
$a1 = random_float(6, 8);
$a1 = round($a1, 1);
$a2 = random_float(6, 8);
$a2 = round($a2, 1);
$a3 = random_float(6, 8);
$a3 = round($a3, 1);
...
$array = array($a1, $a2, $a3, $a4, $a5, $a6, $a7, $a8, $a9, $a10);
echo serialize($array);
``` | A number like 6.2 can't be represented exactly using floating-point math in computers as there is no finite base-2 representation of it. What you are seeing when `echo`-ing the number is something intended for human reading, and thus the value will be rounded to what floats can provide in accuracy (about 6 decimal places for 32-bit and 17 for 64-bit FP values).
When serializing those values, however, you really want the exact value (i. e. all bits that are in there) and not just the nearest "nice" value. There could be more than one float/double representation which evaluates to approximately 6.2 and when serializing you usually *really* want to store he exact values to the last bit you are having in order to restore them correctly. That's why you're getting ridiculous "accuracy" in values there. It's all just to preserve the exact bit representation of what you started with.
But why exactly do you want to control the serialized output that tightly? I mean, it's just there so you can round-trip your data structure and read it back in later. You certainly don't want to use that serialized representation somewhere in output for humans or so. So if it's just about "nice-looking" values, you shouldn't use serialize which has an entirely different purpose. | Store them as strings after using [number\_format](http://php.net/number_format):
```
$number = number_format($float, 2);
``` | PHP - Serialize floating points | [
"",
"php",
"serialization",
"random",
"floating-point",
""
] |
Recently I discovered, that if I need to see if variable is even ( or odd ), I could just see if last bit of variable equals 0. This discovery, when implemented, replaced few *modulo 2* calculations and thus, whole function ran faster.
Are there any other "tricks" like this one, where working with bits could replace other calculations, leading to improved function execution time? | I doubt that replacing the use of modulo-two calculations by the equivalent bitwise operation produced faster execution times. Any C++ compiler worth its grain of salt will compile `n % 2` and `n & 1` to identical machine instructions.
Beware of using bit-twiddling hacks as an optimization. First, it's not always clear that the function you are optimizing is a bottleneck. Second, the resulting code is usually harder to maintain and more likely to be incorrect or have subtle bugs. This is what is meant in the famous quote Knuth quote "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." Save your effort.
If you truly must pursue this subject, [Bit Twiddling Hacks](http://www.graphics.stanford.edu/~seander/bithacks.html) contains a nice list of interesting hacks. | Well, there is a great book on this topic: [Hacker's Delight](http://books.google.gr/books?id=iBNKMspIlqEC&dq=hackers+delight&printsec=frontcover&source=bn&hl=el&ei=A_1FSorYGZCasgbgqbQR&sa=X&oi=book_result&ct=result&resnum=4) (Google books).
On Amazon.com: [Hacker's Delight](https://rads.stackoverflow.com/amzn/click/com/0201914654). | Checking if number is even by looking at the last bit - are there any other "tricks" like this one? | [
"",
"c++",
"bit-manipulation",
""
] |
Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file. | Take a look at Python Eggs: <http://peak.telecommunity.com/DevCenter/PythonEggs>
Or, you can use regular zips: <http://docs.python.org/library/zipimport.html> | After looking for a solution to the same problem, I ended up writing a simple tool which combines multiple .py files into one: [PyBreeder](http://pagekite.net/wiki/Floss/PyBreeder/)
It will only work with pure-Python modules and may require some trial-and-error to get the order of modules right, but it is quite handy whenever you want to deploy a script with some dependencies as a single .py. Comments/patches/critique are very welcome! | Combining module files in Python | [
"",
"python",
"packaging",
""
] |
I have just seen this
```
// Check to see if the request is a XHR call
if (request::is_ajax())
{
// Send the 403 header
header('HTTP/1.1 403 Forbidden');
return;
}
```
I have not seen a simple `return` before, and I have never used it. My only guess is that it simply acts the same as any `return 'something'` (halting the function), except doesn't actually return a result.
Furthermore, what would happen in this situation?
```
function text($var)
{
if ( ! $var) {
return;
}
do_something();
}
$var = text('');
```
I know it's a bad example (it should probably return false or throw an exception), but would it be an error, or would the `$var` simply be null or blank? | ```
function text($var)
{
if ( ! $var) {
return;
}
do_something();
}
$var = text('');
echo gettype($var);
echo is_bool($var) ? "true" : "false";
echo is_string($var) ? "true" : "false";
echo is_null($var) ? "true" : "false";
```
returns:
NULL
false
false
true | PHP is dynamically typed, so returning no value is equivalent to returning a null value in any type. | Does a simple `return` in a PHP function simply end the function prematurely? | [
"",
"php",
"function",
""
] |
I want to open a file from a Class in C# using a Process, located in a directoy I asked the user.
```
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "EXCEL.EXE";
startInfo.Arguments = Here goes the directory I asked
Process.Start(startInfo);
```
The problem, is that when the location of the file indicated by the user has an space," ", excel thinks that I'm sending two sepparate locations. For example with C:\Users\dj\Desktop\da ba excel tries to open " C:\Users\dj\Desktop\da" as one file, and at the same time "ba" as another file. How can I send a location to excel which has an space, without having this error? with an addres like C:\Users\dj\Desktop\daba without an space it works perfectly. | Try using a string literal
```
startInfo.Arguments = @"C:\Users\un\Desktop\file with space"
``` | Try quoting your path:
```
startInfo.Arguments = "\"" + "C:\Users\dj\Desktop\da ba.xls" + "\"";
```
Tim | Executing excel from C# Application | [
"",
"c#",
"excel",
"process",
""
] |
I have a class called `Picture` and that has a name and `size` (`int`) property.
I was going to sort them using size, but not the displayed file name which is the item name in the `listview`.
I implemented `IComparer<Picture>` for the `Picture` type, and then when I write this:
```
this.PicList.ListViewItemSorter = AllPictures[0];
```
or
```
this.PicList.ListViewItemSorter = Picture;
```
they don't compile.
How do I do this? On MSDN it shows a separate class for the sorter but can I do it built-in with the used type `Picture`? | you need to give it an actual instance of your Picture class, not the type. Also, your ListViewItemSorter will actually call the Comparer by passing it the ListViewItem not the Picture class, you can add an instance of the Picture class to the Tag property of your ListViewItem.
Something like this, this is a very rough implementation, just to give you an idea. You can implement your own error handling.
```
Picture test1 = new Picture() { Name = "Picture #1", Size = 54 };
Picture test2 = new Picture() { Name = "Picture #2", Size = 10 };
this.listView1.ListViewItemSorter = test1;
this.listView1.Items.Add(new ListViewItem(test1.Name) { Tag = test1 });
this.listView1.Items.Add(new ListViewItem(test2.Name) { Tag = test2 });
public class Picture : IComparer
{
public string Name { get; set; }
public int Size { get; set; }
#region IComparer Members
public int Compare(object x, object y)
{
Picture itemA = ((ListViewItem)x).Tag as Picture;
Picture itemB = ((ListViewItem)y).Tag as Picture;
if (itemA.Size < itemB.Size)
return -1;
if (itemA.Size > itemB.Size)
return 1;
if (itemA.Size == itemB.Size)
return 0;
return 0;
}
```
The output is:
* Picture #2
* Picture #1
Here is an [MSDN Link](http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.listviewitemsorter.aspx) | Another implementation you can try is to associate each `ListViewItem` index with your custom class/struct instance stored in a `Dictionary<int, Picture>` instance. Your custom list view sorter class could be written with that in mind like so:
```
public partial class Form1 : Form
{
public Form1()
{
...
ListView lv = new ListView();
lv.ListViewItemSorter = new MyCustomSorter(this);
}
private Dictionary<int, Picture> _pictures = new Dictionary<int,Picture>();
private class MyCustomSorter : IComparer
{
private Form1 _parent;
internal MyCustomSorter(Form1 form)
{
_parent = form;
}
#region IComparer Members
public int Compare(object x, object y)
{
ListViewItem item1 = x as ListViewItem;
ListViewItem item2 = y as ListViewItem;
if (x != null)
{
if (y != null)
{
Picture p1 = _parent._pictures[item1.Index];
Picture p2 = _parent._pictures[item2.Index];
return string.Compare(p1.Location, p2.Location);
}
// X is deemed "greater than" y
return 1;
}
else if (y != null)
return -1; // x is "less than" y
return 0;
}
#endregion
}
}
public class Picture
{
private string _location;
public string Location{
get { return _location; }
}
}
``` | Implementing a custom sort for WinForms ListView | [
"",
"c#",
".net",
"winforms",
"listview",
""
] |
How can I rotate the text within an HSSFCell class of Apache POI? | Use HSSFCellStyle, that class has a method called setRotation(short rotation) which will rotate the text. All you do is apply the cell style to a cell:
```
HSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short)90);
HSSFCell c = row.createCell(columnNumber);
c.setCellStyle(myStyle);
``` | ```
CellStyle cssVertical = wb.createCellStyle();
cssVertical.setFont(f);
cssVertical.setRotation((short)90);
``` | How to rotate text in a spreadsheet cell using Apache POI? | [
"",
"java",
"apache",
"excel",
"api",
"spreadsheet",
""
] |
I am using VSTS 2008 + C# + .Net 3.5 + SQL Server 2008 + ADO.Net. If I load a table from a database by using a DataTable of ADO.Net, and in the database table, I defined a couple of indexes on the table. My question is, whether on the ADO.Net DataTable, there is related index (the same as the indexes I created on physical database table) to improve certain operation performance on DataTable?
thanks in advance,
George | George,
The answer is no.
Actually, some sort of indexing may be used internally, but only as an implementation detail. For instance, if you create a foreign key constraint, maybe that's assisted by an index. But it doesn't matter to a developer. | Actually George's question is not so "bad" as some people insist it is. (I am more and more convinced that there's no such thing as, "*a bad question*").
I have a rather big table which I load into the memory, in a DataTable object. A lot of processing is done on lines from this table, a lot of times, on various (and different) subsets which I can easily describe as "WHERE ..." of SELECT clauses. Now with this DataTable I can run Select() - a method of DataTable class - but it is quite inefficient.
In the end, I decided to load the DataTable sorted by specific columns and implemented my own
quick search, instead of using the Select() function. It proved to be much faster, but of course it works only on those sorted columns. The trouble would have been avoided, had a DataTable had indexes. | Do ADO.Net DataTables have indexes? | [
"",
"c#",
".net",
"sql-server",
"ado.net",
"datatable",
""
] |
I am wondering why I'm not able to allocate more that 1,000 MB of memory in my 32-bit .NET process. The following mini application throws an OutOfMemoryException after having allocated 1,000 MB. Why 1,000 MB, and not say 1.8 GB? Is there a process-wide setting I could change?
```
static void Main(string[] args)
{
ArrayList list = new ArrayList();
int i = 0;
while (true)
{
list.Add(new byte[1024 * 1024 * 10]); // 10 MB
i += 10;
Console.WriteLine(i);
}
}
```
PS: Garbage collecting does not help.
**Edit, to clarify what I want:** I have written a server application which deals with very large amounts of data before writing to database/disk. Instead of creating temporary files for everything, I have written an in-memory cache, which makes the whole thing super-fast. But memory is limited, and so I tried to find out what the limits are. And wondered why my small test program threw the OutOfMemoryException after exactly 1,000 MB. | The virtual address space limit of a Win32 process is 1.5GB (not entirely true). Additionally in the .NET frameworks there is a limiter to the % of memory a .NET process can consume. The machine.config has a processModel element with an attribute memoryLimit which is the % of available memory a process can consume. The default value is 60%.
If the machine you're running on has 2GB of memory or you haven't enabled the /3GB switch in your BOOT.INI then you're going to get ~1.3GB of memory per process.
I can't find the KB article but if I remember correctly .NET 1.x cannot address beyond the 1.5GB (1.8GB?) limit regardless of your settings.
<http://blogs.msdn.com/tmarq/archive/2007/06/25/some-history-on-the-asp-net-cache-memory-limits.aspx>
<http://social.msdn.microsoft.com/Forums/en-US/clr/thread/c50ea343-b41b-467d-a457-c5a735e4dfff>
<http://www.guidanceshare.com/wiki/ASP.NET_1.1_Performance_Guidelines_-_Caching#Configure_the_Memory_Limit> | Having enormous blocks of memory is never a good idea, even in 64bit. You get big problems with contiguous memory and fragmentation.
The problem here is finding a contiguous block. You could try enabling 3gb mode (which might help it find a few more bytes) but I **really** advise against it. The answers here are:
* use less memory
* use a database/file system
* use x64
You might also want to read [Eric Lippert's](http://blogs.msdn.com/ericlippert/archive/2009/06/08/out-of-memory-does-not-refer-to-physical-memory.aspx) blog (he seems to have a blog entry for every common .NET question...) | Allocating more than 1,000 MB of memory in 32-bit .NET process | [
"",
"c#",
".net",
"memory",
"out-of-memory",
"large-object-heap",
""
] |
I have this query which works correctly in MySQL. More background on it [here](https://stackoverflow.com/questions/1051927/sql-to-find-most-popular-category/1055859#1055859).
```
SELECT c.*, SUM(ABS(v.vote)) AS score
FROM categories c,items i, votes v
WHERE c.id = i.category_id
AND i.id = v.voteable_id
AND v.created_at > '#{1.week.ago}'
GROUP BY c.id
ORDER BY score DESC LIMIT 8;
```
I tried running it in PostgreSQL, and it failed with this error message.
> PGError: ERROR: column "c.name" must
> appear in the GROUP BY clause or be
> used in an aggregate function
I wasn't sure what this meant, so I tried changing "c.id" to "c.name" in the group by clause (both work in MySQL the same, assuming the name of an item is unique).
However this just produced another similar error
> PGError: ERROR: column "c.id" must
> appear in the GROUP BY clause or be
> used in an aggregate function
How can this problem be resolved? | You have to list column names in SELECT which you are grouping in:
```
SELECT c.id, c.name, SUM(ABS(v.vote)) AS score
FROM categories c,items i, votes v
WHERE c.id = i.category_id
AND i.id = v.voteable_id
AND v.created_at > '#{1.week.ago}'
GROUP BY c.id, c.name
ORDER BY score DESC LIMIT 8;
```
"It is not permissible to include column names in a SELECT clause that are not referenced in the GROUP BY clause." | I just had that issue but going from MySQL to SQL Server. I thought the fact that it is allowed it was strange!
Yes, in most databases, when you have a GROUP BY clause you can only select aggregates of columns or columns that appear in the GROUP BY clause. This is because it has no way of knowing if the other columns you're selecting are truly unique or not.
Just put the columns you want in the GROUP BY if they are indeed unique. This was a "feature" of MySQL that was questionable.
You can read about MySQL's behavior and how it is different [here](http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html).
Example:
```
SELECT c.*, SUM(ABS(v.vote)) AS score
FROM categories c,items i, votes v
WHERE c.id = i.category_id
AND i.id = v.voteable_id
AND v.created_at > '#{1.week.ago}'
GROUP BY c.id, c.name, c.whatever_else
ORDER BY score DESC LIMIT 8;
``` | Converting MySQL select to PostgreSQL | [
"",
"mysql",
"sql",
"postgresql",
""
] |
I'm having some trouble with the output of a DateTime value. My computer's current culture is set to de-AT (Austria).
The following code
```
string s1 = DateTime.Now.ToString("d");
string s2 = string.Format("{0:d}", DateTime.Now);
```
results in s1 and s2 both having the correct value of "30.06.2009".
But when using the same format in XAML
```
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat=d}"/>
```
the output is `"6/30/2009". It seems the XAML StringFormat ignores the current culture settings. This happens on both Vista and XP.
I don't want to specify a custom format, because the output should be formatted in the user's preferred culture setting.
Anybody with the same problem? Is this a bug in WPF? | Please [see my answer on StringFomat Localization problem](https://stackoverflow.com/questions/520115/stringfomat-localization-problem/520334#520334) | To apply the solution mentioned [here](https://www.nbdtech.com/Blog/archive/2009/02/22/wpf-data-binding-cheat-sheet-update-the-internationalization-fix.aspx) do the following:
(1) Add a Startup event handler to the Application class in app.xaml:
```
<Application x:Class="MyApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
...
Startup="ApplicationStartup">
```
(2) Add the handler function:
```
private void ApplicationStartup(object sender, StartupEventArgs e)
{
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
}
```
WPF strings should then be formatted correctly according to culture. | WPF XAML StringFormat DateTime: Output in wrong culture? | [
"",
"c#",
"wpf",
"xaml",
"datetime",
""
] |
I have a page with urls with descriptions listed one under another (something like bookmarks/list of sites). How do I use php to get all urls from that page and write them to txt file (one per line, only url without description)?
Page looks like this:
[Some description](http://link.com)
[Other description](http://link2.com)
[Another one](http://link3.com)
And I would like script's txt output to look like this:
<http://link.com>
<http://link2.com>
<http://link3.com> | one way
```
$url="http://wwww.somewhere.com";
$data=file_get_contents($url);
$data = strip_tags($data,"<a>");
$d = preg_split("/<\/a>/",$data);
foreach ( $d as $k=>$u ){
if( strpos($u, "<a href=") !== FALSE ){
$u = preg_replace("/.*<a\s+href=\"/sm","",$u);
$u = preg_replace("/\".*/","",$u);
print $u."\n";
}
}
``` | Another way
```
$url = "http://wwww.somewhere.com";
$html = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($html); //helps if html is well formed and has proper use of html entities!
$xpath = new DOMXpath($doc);
$nodes = $xpath->query('//a');
foreach($nodes as $node) {
var_dump($node->getAttribute('href'));
}
``` | How to get all urls from page (php) | [
"",
"php",
""
] |
I'm exploring a few PHP frameworks and the current front runner is Kohana.
Having a Rails background I've become used to what the rails community calls "RESTful" routes. So a "GET /posts" displays all posts and is handled by the index method of the Posts Controller. A "POST /posts" creates a new post object and is handled by a different method of the Posts Controller.
Since the path in both these 2 requests is identical, the router needs to make decisions based on the HTTP method.
Is the router in Kohana capable of doing this? | Kohana does not support RESTful routes by default, but there is a [RESTful](http://dev.kohanaphp.com/projects/restful) module that adds support for it. See the [RESTful wiki](http://dev.kohanaphp.com/wiki/restful) for usage.
Kohana v3.x supports RESTful controllers directly. Just extend `Controller_REST` instead of `Controller` and all the route action will be the request method. (A `POST` request would be targeted to `action_post`, etc.) | You could also add these lines to your controller's before() method:
```
if ($this->request->method() == "POST")
{
$this->request->action("post_".$this->request->action());
}
```
so GET /controller/posts will be handled by the action\_posts() method in your controller, while POST /controller/posts will be handled by the action\_post\_posts() method.
PS: The built-in Controller\_REST was removed in Kohana 3.2 | Can I setup routes in Kohana to only match particular HTTP methods (GET/POST/etc) | [
"",
"php",
"rest",
"kohana",
""
] |
I found the following code somewhere, but I am not understanding the code properly.
```
ArticleVote.submitVote('no');return false;
```
Is `ArticleVote` a class and `submitVote()` a function of that class?
Or what does the above code mean? And is there any concept of classes and objects in jQuery or in traditional JavaScript? How to create them? Please share some reference links or code. | ## Everything is an object in JavaScript
As opposed to other purportedly pure OOP languages. Functions are objects too, but they may just as well be constructor of objects.
```
var ObjectCreator = function () {
};
```
The above is a function which if called appropriately, creates an object. *Called appropriately* means that you have to use the `new` operator:
```
var obj = new ObjectCreator;
```
So while JavaScript does not have classes per se, has means to emulate that behavior. For example:
```
class Foo {
public void bar() {}
}
Foo foo = new Foo();
```
is equivalent to the following JS code:
```
var Foo = function () {
// constructor
};
Foo.prototype.bar = function () {}
var foo = new Foo;
```
## Inheritance is different
The real difference comes when you want to use inheritance, which is a different type of inheritance (prototypal). So, given two pseudo-classes Foo and Bar, if we want Bar to extend from Foo, we would have to write:
```
var Foo = function () {};
var Bar = function () {};
Bar.prototype = new Foo; // this is the inheritance phase
var bar = new Bar;
alert(bar instanceof Foo);
```
## Object literals
While constructor functions are useful, there are times when we only need **only one** instance of that object. Writing a constructor function and then populate its prototype with properties and methods is somehow tedious. So JavaScript has object literals, which are some kind of hash tables, only that they're self-conscious. By *self-conscious* I mean that they know about the `this` keyword. Object literals are a great way to implement the Singleton pattern.
```
var john = {
age : 24,
isAdult : function () {
return this.age > 17;
}
};
```
The above, using a constructor function would be equivalent to the following:
```
var Person = function (age) {
this.age = age;
};
Person.prototype.isAdult = function () {
return this.age > 17;
};
var john = new Person(24);
```
## What about that `prototype` thingy
As many have said, in JavaScript objects inherit from objects. This thing has useful aspects, one of which may be called, *parasitic inheritance* (if I remember correctly the context in which Douglas Crockford mentioned this). Anyway, this prototype concept is associated with the concept of *prototype chain* which is similar to the parent -> child chain in classical OO languages. So, the inheritance stuff. If a `bar` method is called on a `foo` object, but that object does not have a `bar` method, a member lookup phase is started:
```
var Baz = function () {};
Baz.prototype.bar = function () {
alert(1);
};
var Foo = function () {};
Foo.prototype = new Baz;
var foo = new Foo;
/*
* Does foo.bar exist?
* - yes. Then execute it
* - no
* Does the prototype object of the constructor function have a bar
* property?
* - yes. Then execute it
* - no
* Is there a constructor function for the prototype object of
* the initial construct function? (in our case this is Baz)
* - yes. Then it must have a prototype. Lookup a bar
* member in that prototype object.
* - no. OK, we're giving up. Throw an error.
*/
foo.bar();
```
## Hold on, you said something about parasitic inheritance
There is a key difference between classical OO inheritance and prototype-based inheritance. When objects inherit from objects, they also **inherit state**. Take this example:
```
var Person = function (smart) {
this.smart = smart;
};
var Adult = function (age) {
this.age = age;
};
Adult.prototype = new Person(true);
var john = new Adult(24);
alert(john.smart);
```
We could say that `john` is a parasite of an anonymous Person, because it merciless sucks the person intelligence. Also, given the above definition, all future adults will be smart, which unfortunately is not always true. But that doesn't mean object inheritance is a bad thing. Is just a tool, like anything else. We must use it as we see fit.
In classical OO inheritance we can't do the above. We could emulate it using static fields though. But that would make all instances of that class having the same value for that field. | Javascript supports **objects** but not *classes* - it uses a [**prototype-based**](http://en.wikipedia.org/wiki/Prototype-based_programming) object system. | Does jQuery or JavaScript have the concept of classes and objects? | [
"",
"javascript",
"jquery",
"html",
"class",
""
] |
I wanted to know How OS actually makes a program in to process. what are steps Os engages to make program a process.
I mean How a Program becomes a Process, what are the parameter OS adds to kernel datastructure before making a program a process
Thank you in advance. | Every operating system is going to do this in a different manner.
However, in general the following steps will occur in a modern operating system:
* New address space created
* Program image loaded into an agreed upon address
+ This may involve [relocation](http://en.wikipedia.org/wiki/Relocatable_code) of the image, or a dependency.
* Execution "context" setup
+ Includes stack, and a call into an agreed upon "main" function by a logical thread of execution
I'm glossing over lots of nasty little details, but that's a basic overview. | [](https://i.stack.imgur.com/P85Wx.jpg)
[Operating System Concepts](https://rads.stackoverflow.com/amzn/click/com/0471250600) | How Program Becomes a Process. How OS makes Program a process | [
"",
"c++",
"c",
"process",
"operating-system",
""
] |
I'm trying to take a `VARCHAR(MAX)` with data in it as follows:
"00001001010001010111010101..." etc.
Then encode it as hexadecimal for more efficient return to the client.
Is it possible to do this? Either directly or converting the string into a real binary column first before calling `master.dbo.fn_varbintohexstr`?
As an example, given the string:
```
0000100101000101011101011110
```
We should end up with:
```
0000 = 0
1001 = 9
0100 = 4
0101 = 5
0111 = 7
0101 = 5
1110 = E
```
094575E.
Or if there is an even more efficient method (reading binary directly?) then that would be even better. SQL Server 2000 compatible solutions are preferable. | Given your previous question, you're generating this string as part of another query. Why on Earth are you generating a string of ones and zeros when you can just multiply them by the appropriate power of 2 to make an `INT` out of them instead of a string? Converting from `INT` to hex string is trivial. | You can always split the string in 4 char groups (starting from end!), using [SUBSTRING](http://msdn.microsoft.com/en-us/library/ms187748.aspx), and cast the 4 char groups to the hex digit, eg. '0011' to '3' in a big CASE statement. There are only 16 switch cases in the CASE, so is more than manageable. But all you get is a 4 times reduction in length, not sure if it worth the (significant) server overhead just to reduce the traffic. | How can I convert a character-encoded binary string to hexadecimal in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
In Linux after text selecting it copies to buffer, so than we could paste it by clicking middle button of the mouse. I think that there is a special buffer for this thing. I want to use it. How could i get data of selected text?
* OS: Linux
* Programming language: c++
* Own libraries: Qt
Thanks. | Just a more accurate answer than Paul Dixon's that answers your needs:
```
QClipboard* clipboard = QApplication::clipboard();
QString selectedText = clipboard->text(QClipboard::Selection);
``` | You need to distinguish between selection and clipboard. The `QClipboard` documentation has this in the [Notes for X11 Users](http://doc.trolltech.com/4.5/qclipboard.html#notes-for-x11-users) section:
> The X11 Window System has the concept
> of a separate selection and clipboard.
> When text is selected, it is
> immediately available as the global
> mouse selection. The global mouse
> selection may later be copied to the
> clipboard. By convention, the middle
> mouse button is used to paste the
> global mouse selection.
With `QClipboard::Mode` you can select which type (clipboard or selection) you want to access. The important part is that you need to be aware about the difference between selection and clipboard. | Linux and clipboard | [
"",
"c++",
"qt",
"clipboard",
""
] |
What's the best way to iterate over the items in a [`HashMap`](https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html)? | Iterate through the [`entrySet()`](http://www.java2s.com/Code/JavaAPI/java.util/HashtableentrySet.htm) like so:
```
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
```
Read more about [`Map`](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html). | If you're only interested in the keys, you can iterate through the [`keySet()`](https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Map.html#keySet%28%29) of the map:
```
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
```
If you only need the values, use [`values()`](https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Map.html#values%28%29):
```
for (Object value : map.values()) {
// ...
}
```
Finally, if you want both the key and value, use [`entrySet()`](https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Map.html#entrySet%28%29):
```
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
```
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see [karim79's answer](https://stackoverflow.com/questions/1066589/java-iterate-through-hashmap/1066603#1066603)). However, changing item values is OK (see [`Map.Entry`](https://docs.oracle.com/javase/6/docs/api/java/util/Map.Entry.html)). | Iterate through a HashMap | [
"",
"java",
"loops",
"hashmap",
"iteration",
""
] |
I'm trying to compile shared library on solaris 2.7 using gcc 3.4.6 and
which is linking to a statically linked c .a and .o files.
Please note that it is using Sun ld from path "/usr/ccs/bin/ld"
At linking time i got a long list of symbols and following error
```
ld: fatal: relocations remain against allocatable but non-writable sections
collect2: ld returned 1 exit status
```
Then i tried to build it passing -z textoff option to ld. but i'm getting follwing error
```
ld: fatal: option -ztextoff and -ztext are incompatible
ld: fatal: Flags processing errors
```
Is there any other way where i don't need to recompile gcc and still modify the options getting passed to ld. | The errors are the result of linking position-dependent code into a shared library. Such code will result in the library not being shareable, and thus wasting RAM.
If you can rebuild all the objects you are trying to link into the shared library, the simplest (and most correct) solution is to rebuild all of them with `-fPIC` flag.
However, sometimes you really must link non-PIC object code which you can't rebuild into a shared library, and therefore you need to get rid of the `-ztext` option. To do that, add `-mimpure-text` option to your link line. | Are you using make or some other build system to invoke the compiler?
If you change the options in the build system to specifically use the linker during the link phase rather than using the compiler.
Step 1: Find flags passed by gcc
Add the -v flag. It makes gcc verbose.
> CXXFLAGS += -v
Step 2: Modify the link stage to explicitly use the tool that gcc was invoking. | How to modify options being passed to ld , without recompiling gcc | [
"",
"c++",
"gcc",
"solaris",
""
] |
I am trying to apply a method to an existing object which involves using its private variables. The object is setup like so:
```
function a(given_id)
{
var id= given_id;
}
```
now I want to apply some new method to it like so
```
my_obj = new a('some_id');
my_obj.myMethod = function(){
alert(id);
}
```
now if I go my\_obj.myMethod() I get an error saying id is undefined.
This same code works if I change id from being private to public.
I don't understand why this is happening because if myMethod was defined originally in a as a privileged method it would work. The only thing I can think of is that myMethod is being added as a public method, instead of a privileged one.
Any information on this would be much appreciated. | use this.id = ... instead of var id = ... (var will give you function scope only aka local variable).
{edit} try:
```
function Foo(givenId)
{
var id = givenId;
this.Bar = function() {
WScript.Echo(id); //change this to alert(...)
}
}
var foo = new Foo(52);
foo.Bar();
```
Again, var in a function has function scope (local variable). If you want to have access to it, declare your privilege function as an inner function to the outer function and use closure to get access to it. | I think that you are trying to create a "Privileged Method", basically a method that is able to access the private variables:
```
function a(given_id) {
var id= given_id;
this.myMethod = function()
{
alert(id);
}
}
```
You cannot declare privileged methos outside the constructor, because if you do so, they wont have access to the constructor's closure.
Recommended reads:
* [JavaScript Private Members](http://www.crockford.com/javascript/private.html)
* [JavaScript Closures](http://www.jibbering.com/faq/faq_notes/closures.html) | applying methods to object and private variables in javascript | [
"",
"javascript",
"function",
"object",
""
] |
I'm trying to make a small program that could intercept the open process of a file.
The purpose is when an user double-click on a file in a given folder, windows would inform to the software, then it process that petition and return windows the data of the file.
Maybe there would be another solution like monitoring Open messages and force Windows to wait while the program prepare the contents of the file.
One application of this concept, could be to manage desencryption of a file in a transparent way to the user.
In this context, the encrypted file would be on the disk and when the user open it ( with double-click on it or with some application such as notepad ), the background process would intercept that open event, desencrypt the file and give the contents of that file to the asking application.
It's a little bit strange concept, it could be like "Man In The Middle" network concept, but with files instead of network packets.
Thanks for reading. | The best way to do it to cover all cases of opening from any program would be via a [file system filter driver](https://web.archive.org/web/20100127105044/https://www.microsoft.com/whdc/driver/filterdrv/default.mspx). This may be too complex for your needs though. | You can use the trick that [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) uses to replace itself with task manager. Basically create a key like this:
`HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe`
Where you replace `'taskmgr.exe'` with the name of the process to intercept. Then add a string value called `'Debugger'` that has the path to your executable. E.g:
`Debugger -> "C:\windows\system32\notepad.exe"`
Every a process is run that matches the image name your process will actually be called as a debugger for that process with the path to the actual process as an argument. | Intercept windows open file | [
"",
"c++",
"windows",
"winapi",
"events",
"file-io",
""
] |
I have a Java application using the Substance LookAndFeel with Windows as the the target platform and I want to increase the DPI setting of my application *without* changing the system setting.
I want to do this because I don't want to force the user to restart Windows and because many Windows applications seem to have problems with very high DPI settings (> 120)
PS: I'm aware that the Substance LaF allows to scale the font size at runtime, but that way only the height of my controls are scaled, not the width. I want my GUI fully scaled as it would happen if I set the system's DPI setting. | Don't know if that is possible. The look&feel would have to support it, and as far as I know, the Windows Look&Feel does not. Here's a hack which you may consider: Iterate through all the fonts defined in your look&feel and redefine them to be slighly bigger. Here is a code snippet that does this:
```
for (Iterator i = UIManager.getLookAndFeelDefaults().keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
if(key.endsWith(".font")) {
Font font = UIManager.getFont(key);
Font biggerFont = font.deriveFont(2.0f*font.getSize2D());
// change ui default to bigger font
UIManager.put(key,biggerFont);
}
}
```
I suppose you could take this one step further and redefine scale borders proportionally as well, but that gets very complicated very quickly | So the actual answer seems to be: no you can't. That really is a bummer because it's a pain to test. | Can I set the DPI resolution of my Java Swing application without changing the systems' DPI setting? | [
"",
"java",
"swing",
"testing",
"accessibility",
"dpi",
""
] |
Sorry for the not so great title, but I'm curious how people build a category table in SQL given the following example
Two columns:
ID,
CATEGORY
Which of these ways would you name the columns?
ID,
CATEGORY
ID,
DESCRIPTION
CAT\_ID,
CAT\_DESC
Or something else? Just wondering what other people do. Sorry if this is less than clear. I hope it's worth answering because feedback would be great. | I personally don't like the "CAT\_ID" "CAT\_DESC" nomenclature, I much rather prefer "DESCRIPTION" and "ID".
However, the downside to this is that if you are doing joins on tables which have the same column names, in the projection, you have to rename the columns to indicate which attribute is from which underlying table.
The downside to the "CAT\_ID", etc, etc approach is that you can come up with names which don't have a simple singular meaning.
Your usage of the table and the types of queries/joins/projections should help you determine which is best suited for what you are doing. | * The table name is category - that itself is telling you something.
* The column names can be simple "ID", and "DESCRIPTION"
* category.id, and category.description look clean and simple | How to build a category table | [
"",
"sql",
"database-design",
""
] |
Does anyone know the best way to create a SQL Server CE (Compact 3.5) table based on the schema of a `DataTable` at runtime? I don’t want to have to formulate a `CREATE TABLE` statement based on all the different possible datatypes, etc.
As a bonus – do you then know how to fill it directly from a datatable? | I coded a reasonable solution, but was hoping to avoid case statements for the SQL types:
Firstly a neat trick to convert from a .NET type to a SqlDBType:
```
/// <summary>
/// Gets the correct SqlDBType for a given .NET type. Useful for working with SQL CE.
/// </summary>
/// <param name="type">The .Net Type used to find the SqlDBType.</param>
/// <returns>The correct SqlDbType for the .Net type passed in.</returns>
public static SqlDbType GetSqlDBTypeFromType(Type type)
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(DbType));
if (/*tc.CanConvertFrom(type)*/ true)
{
DbType dbType = (DbType)tc.ConvertFrom(type.Name);
// A cheat, but the parameter class knows how to map between DbType and SqlDBType.
SqlParameter param = new SqlParameter();
param.DbType = dbType;
return param.SqlDbType; // The parameter class did the conversion for us!!
}
else
{
throw new Exception("Cannot get SqlDbType from: " + type.Name);
}
}
```
A case statement for the types for use in SQL Statements:
```
/// <summary>
/// The method gets the SQL CE type name for use in SQL Statements such as CREATE TABLE
/// </summary>
/// <param name="dbType">The SqlDbType to get the type name for</param>
/// <param name="size">The size where applicable e.g. to create a nchar(n) type where n is the size passed in.</param>
/// <returns>The SQL CE compatible type for use in SQL Statements</returns>
public static string GetSqlServerCETypeName(SqlDbType dbType, int size)
{
// Conversions according to: http://msdn.microsoft.com/en-us/library/ms173018.aspx
bool max = (size == int.MaxValue) ? true : false;
bool over4k = (size > 4000) ? true : false;
switch (dbType)
{
case SqlDbType.BigInt:
return "bigint";
case SqlDbType.Binary:
return string.Format("binary ({0})", size);
case SqlDbType.Bit:
return "bit";
case SqlDbType.Char:
if (over4k) return "ntext";
else return string.Format("nchar({0})", size);
ETC...
```
Then finally the CREATE TABLE statement:
```
/// <summary>
/// Genenerates a SQL CE compatible CREATE TABLE statement based on a schema obtained from
/// a SqlDataReader or a SqlCeDataReader.
/// </summary>
/// <param name="tableName">The name of the table to be created.</param>
/// <param name="schema">The schema returned from reader.GetSchemaTable().</param>
/// <returns>The CREATE TABLE... Statement for the given schema.</returns>
public static string GetCreateTableStatement(string tableName, DataTable schema)
{
StringBuilder builder = new StringBuilder();
builder.Append(string.Format("CREATE TABLE [{0}] (\n", tableName));
foreach (DataRow row in schema.Rows)
{
string typeName = row["DataType"].ToString();
Type type = Type.GetType(typeName);
string name = (string)row["ColumnName"];
int size = (int)row["ColumnSize"];
SqlDbType dbType = GetSqlDBTypeFromType(type);
builder.Append(name);
builder.Append(" ");
builder.Append(GetSqlServerCETypeName(dbType, size));
builder.Append(", ");
}
if (schema.Rows.Count > 0) builder.Length = builder.Length - 2;
builder.Append("\n)");
return builder.ToString();
}
``` | I've used and updated the Code from Ben Breen:
* Changed GetSqlServerCETypeName to work with all types
* Added a function fow a whole Dataset
* And some minor tweaks
GetSqlDBTypeFromType
```
/// <summary>
/// Gets the correct SqlDBType for a given .NET type. Useful for working with SQL CE.
/// </summary>
/// <param name="type">The .Net Type used to find the SqlDBType.</param>
/// <returns>The correct SqlDbType for the .Net type passed in.</returns>
public static SqlDbType GetSqlDBTypeFromType(Type type)
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(DbType));
if (/*tc.CanConvertFrom(type)*/ true)
{
DbType dbType = (DbType)tc.ConvertFrom(type.Name);
// A cheat, but the parameter class knows how to map between DbType and SqlDBType.
SqlCeParameter param = new SqlCeParameter();
param.DbType = dbType;
return param.SqlDbType; // The parameter class did the conversion for us!!
}
else
{
throw new Exception("Cannot get SqlDbType from: " + type.Name);
}
}
```
GetSqlServerCETypeName
```
/// <summary>
/// The method gets the SQL CE type name for use in SQL Statements such as CREATE TABLE
/// </summary>
/// <param name="dbType">The SqlDbType to get the type name for</param>
/// <param name="size">The size where applicable e.g. to create a nchar(n) type where n is the size passed in.</param>
/// <returns>The SQL CE compatible type for use in SQL Statements</returns>
public static string GetSqlServerCETypeName(SqlDbType dbType, int size)
{
// Conversions according to: http://msdn.microsoft.com/en-us/library/ms173018.aspx
bool max = (size == int.MaxValue) ? true : false;
bool over4k = (size > 4000) ? true : false;
if (size>0)
{
return string.Format(Enum.GetName(typeof(SqlDbType), dbType)+" ({0})", size);
}
else
{
return Enum.GetName(typeof(SqlDbType), dbType);
}
}
```
GetCreateTableStatement
```
/// <summary>
/// Genenerates a SQL CE compatible CREATE TABLE statement based on a schema obtained from
/// a SqlDataReader or a SqlCeDataReader.
/// </summary>
/// <param name="tableName">The name of the table to be created.</param>
/// <param name="schema">The schema returned from reader.GetSchemaTable().</param>
/// <returns>The CREATE TABLE... Statement for the given schema.</returns>
public static string GetCreateTableStatement(DataTable table)
{
StringBuilder builder = new StringBuilder();
builder.Append(string.Format("CREATE TABLE [{0}] (", table.TableName));
foreach (DataColumn col in table.Columns)
{
SqlDbType dbType = GetSqlDBTypeFromType(col.DataType);
builder.Append("[");
builder.Append(col.ColumnName);
builder.Append("]");
builder.Append(" ");
builder.Append(GetSqlServerCETypeName(dbType, col.MaxLength));
builder.Append(", ");
}
if (table.Columns.Count > 0) builder.Length = builder.Length - 2;
builder.Append(")");
return builder.ToString();
}
```
CreateFromDataset
```
public static void CreateFromDataset(DataSet set, SqlCeConnection conn)
{
conn.Open();
SqlCeCommand cmd;
foreach (DataTable table in set.Tables)
{
string createSql = copyDB.GetCreateTableStatement(table);
Console.WriteLine(createSql);
cmd = new SqlCeCommand(createSql, conn);
Console.WriteLine(cmd.ExecuteNonQuery());
}
conn.Close();
}
}
``` | Programmatically create a SQL Server CE table from DataTable | [
"",
"c#",
".net",
"sql-server",
"sql-server-ce",
""
] |
I'm able to read the Manifest file inside of my Java code, but I would also like to know if it's possible, and if it is, how to open up a JAR file from the command line and view its Manifest.MF file, or at the very least be able to specify a property of the Manifest.MF file and view it's value. | From [here](http://javahowto.blogspot.com/2006/07/something-you-may-not-know-about-jar.html):
You can extract selected entries from a jar file. For instance, if you only want to view the meta-inf/manifest.mf file, you can
```
C:\Sun\AppServer\lib>jar xvf j2ee.jar META-INF/MANIFEST.MF
inflated: META-INF/MANIFEST.MF
```
Or using a backslash instead of a forward slash:
```
C:\Sun\AppServer\lib>jar xvf j2ee.jar META-INF\MANIFEST.MF
inflated: META-INF/MANIFEST.MF
```
The entry names are case sensitive, and so the following will not extract anything:
```
C:\Sun\AppServer\lib>jar xvf j2ee.jar meta-inf/manifest.mf
```
Of course, you can always double-click the entry to view it in WinZip, fileroller, or other tools. | Something like this should work:
```
jar -xf <jarfile.jar> META-INF/MANIFEST.MF
``` | Using tools that the JDK and/or JRE provide, is there a way to view the Manifest file for a given JAR? | [
"",
"java",
"jar",
"manifest",
"manifest.mf",
""
] |
I'm always struggling with generics. I don't know why this makes my go crazy. I have an old problem I've got several times.
```
class Father {
...
}
class Child1 extends Father {
...
}
class Child2 extends Father {
...
}
public class TestClass {
private static Class<? extends Father>[] myNiceClasses = new Class<? extends Father>[] {
Child1.class,
Child2.class
}
}
```
That does **not** work. The compiler complains like this:
```
Cannot create a generic array of Class<? extends Father>
```
If I change the (faulty) array line to
```
private static Class<Father>[] myNiceClasses = new Class<Father>[] {
```
the same error message occurs, but also this message is added:
```
Type mismatch: cannot convert from Class<Child1> to Class<Father>
```
The only working version is this line:
```
private static Class<?>[] myNiceClasses = new Class<?>[] {
```
This solution is not satisfying, because you cannot cast so easily.
So my question is: How to solve this problem? Where's the knot in my brain? | This is because java does not support generic array creation. Generics work best with Collections. So you can use ArrayList to solve your problem:
```
ArrayList<Class<? extends Father>> myNiceClasses = new ArrayList<Class<? extends Father>>();
myNiceClasses.add(Child1.class);
myNiceClasses.add(Child2.class);
``` | What quant\_dev's linked thread is saying is that generic arrays cannot be created because they cannot guarantee type safety. You can end up with things in the array the generics don't allow. The cleanest way I know of to do it anyway is:
```
private static Class<? extends Father>[] myNiceClasses =
(Class<? extends Father>[]) new Class<?>[] {};
``` | Struggling with generics and classes | [
"",
"java",
"arrays",
"generics",
""
] |
I'm a total newb to LINQ.
Here is the code I have so far:
```
public class Folder
{
public Folder(string path)
{
string[] files = Directory.GetFiles(path);
IList<FileInfo> fis = new List<FileInfo>();
files.SomeMethod(x => fis.Add(new FileInfo(x)));
}
}
```
What is the correct method name to replace SomeMethod with this to get it to work?
I'd basically just like a more concise way of writing a loop here. | sounds like you're looking for something like the ForEach function in List. You could do the following...
```
files.ToList().ForEach(x => fis.Add(new FileInfo(x)));
```
or you could do something like this as a more direct approach
```
IList<FileInfo> fis = (from f in Directory.GetFiles(path)
select new FileInfo(f)).ToList();
```
or...
```
IList<FileInfo> fis = Directory.GetFiles(path).Select(s => new FileInfo(s)).ToList();
// or
IList<FileInfo> fis = Directory.GetFiles(path)
.Select(s => new FileInfo(s))
.ToList();
```
Or - without using any linq at all, how about this one?...
```
IList<FileInfo> fis = new List<FileInfo>(new DirectoryInfo(path).GetFiles());
``` | You *could* use the static ForEach method:
```
Array.ForEach(x => fis.Add(new FileInfo(x)));
```
However, you can easily replace the entire function with this one line:
```
IList<FileInfo> fis = Directory.GetFiles(path).
Select(f => new FileInfo(f)).ToList();
``` | .NET / C# - Proper Method to Use Here - LINQ | [
"",
"c#",
".net",
"linq",
"loops",
""
] |
I translated this code(it has bad side effect that it just capture the outer variable):
```
foreach (TaskPluginInfo tpi in Values)
{
GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { tpi.ShowTask() });
}
```
To this code(because the above is not working):
```
foreach (TaskPluginInfo tpi in Values)
{
// must capture the variable
var x = tpi;
GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { x.ShowTask(); });
}
```
What's the correct terminology for that work-around on that little known side effect? For now, I commented "must capture the variable." Is the word capture, the correct terminology? | Well, both tpi and x are variables (of different sorts) that get captured in one of the examples... the main point here is that you want to restrict the **scope** of the captured variable (ideally `x`) to inside the loop.
So, perhaps; "capture the **value** of the iteration variable; not the iteration variable itself" | What you're actually doing is creating a closure context containing the value of the iterator for each iteration. This context will remain available to the delegate as long as the delegate exists.
How would you call the statement you're referring to? I think "capture" is a good verb to use. In the end, as long as it's clear to everyone what you mean, it's ok :-) | Terminology when copying the captured variable for a lambda/ anon-method | [
"",
"c#",
"lambda",
"foreach",
"anonymous-methods",
""
] |
I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.
For example, I would call
```
python agent.py
```
and agent.py has a number of imports, including:
```
import checks
```
where checks is in a file in the same directory as agent.py
```
agent/agent.py
agent/checks.py
```
When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.
How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.
```
python /home/bob/scripts/agent/agent.py
``` | Actually your example works because checks.py is in the same directory as agent.py, but say checks.py was in the preceeding directory, eg;
```
agent/agent.py
checks.py
```
Then you could do the following:
```
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if not path in sys.path:
sys.path.insert(1, path)
del path
```
Note the use of `__file__`. | **You should NOT need to fiddle with sys.path.** To quote from the Python 2.6 docs for sys.path:
> As initialized upon program startup, the first item of this list,
> path[0], is the directory containing the script that was used to
> invoke the Python interpreter. If the script directory is not
> available (e.g. if the interpreter is invoked interactively or if the
> script is read from standard input), path[0] is the empty string,
> which directs Python to search modules in the current directory first.
> Notice that the script directory is inserted before the entries
> inserted as a result of PYTHONPATH.
```
=== amod.py ===
def whoami():
return __file__
=== ascript.py ===
import sys
print "sys.argv", sys.argv
print "sys.path", sys.path
import amod
print "amod __file__", amod.whoami()
=== result of running ascript.py from afar ===
C:\somewhere_else>\python26\python \junk\timport\ascript.py
sys.argv ['\\junk\\timport\\ascript.py']
sys.path ['C:\\junk\\timport', 'C:\\WINDOWS\\system32\\python26.zip', SNIP]
amod __file__ C:\junk\timport\amod.py
```
and if it's re-run, the last line changes of course to ...amod.pyc. This appears not to be a novelty, it works with Python 2.1 and 1.5.2.
Debug hints for you: Try two simple files like I have. Try running Python with -v and -vv. Show us the results of your failing tests, including full traceback and error message, and your two files. Tell us what platform you are running on, and what version of Python. Check the permissions on the checks.py file. Is there a checks.something\_else that's causing interference? | Importing Python modules from different working directory | [
"",
"python",
""
] |
I'm currently using the Microsoft ADO.NET provider for Oracle (`System.Data.OracleClient`). I'm aware that it is certainly not the best Oracle provider available and that it [will soon be deprecated](http://blogs.msdn.com/adonet/archive/2009/06/15/system-data-oracleclient-update.aspx), I should be using Oracle's ODP.NET instead. The reason why I still use the MS provider is because **ODP.NET binds parameters by position**, not by name. This can really be a PITA when you use many parameters in a query, because you have to be careful to add them in the right order, which can easily lead to bugs. It's also annoying when you use the same parameter multiple times in the same query, for instance :
```
SELECT A,B,C FROM FOO WHERE X = :PARAM_X OR :PARAM_X = 0
```
With ODP.NET, I have to add two parameters to the `OracleCommand`, which I think is stupid...
ODP.NET's `OracleCommand` has a property to change that default behavior : `BindByName`. When set to true, the parameters are bound by name, which is what I want. Unfortunately this doesn't really help me, because :
* It is set to false by default
* I almost never use concrete ADO.NET classes explicitly, I prefer to use ADO.NET 2.0 abstraction layer (`DbProviderFactory`, `DbConnection`, `DbCommand`...) to reduce coupling to any specific RDBMS. So I don't have access to the `BindByName` property, unless I cast explicitly to `OracleCommand`, losing all the benefits or the abstraction.
* When using an ASP.NET SqlDataSource, I don't create the DbCommand myself, so I don't get a chance to set `BindByName` to true (I could do it in the Selecting event, but it really is a pain to do it for each SqlDataSource...)
How am I supposed to handle that issue ? Is there a `BindByNameByDefault` setting somewhere ? (I didn't find anything like that, but I may have missed it...) | I think you can create your own provider that uses the defaults you want to use. You could create that provider easily by inheriting all the classes from odp.net, just adjust some properties like BindByName.
The DbProviderfactory will create your classes instead of the normal odp.net classes. | Use indirection and inheritance! If you're performing data access through an abstract Database class, require the Database implementation handle parameter binding.
```
public abstract class Database
{
private readonly DbProviderFactory factory;
protected Database(DbProviderFactory factory)
{
this.factory = factory;
}
public virtual DbCommand CreateCommand(String commandText)
{
return CreateCommand(CommandType.Text, commandText);
}
public virtual DbCommand CreateCommand(CommandType commandType, String commandText)
{
DbCommand command = factory.CreateCommand();
command.CommandType = commandType;
command.Text = commandText;
return command;
}
public virtual void BindParametersByName(DbCommand command)
{
}
}
```
And choose to create an Oracle specific implementation that overrides default command creation or provides the option to bind parameters by name.
```
public class OracleDatabase : Database
{
public OracleDatabase()
: base(OracleClientFactory.Instance)
{
}
public override DbCommand CreateCommand(CommandType commandType, String commandText)
{
DbCommand command = base.CreateCommand(commandType, commandText);
BindParametersByName(command);
return command;
}
public override void BindParametersByName(DbCommand command)
{
((OracleCommand)command).BindByName = true;
}
}
```
*Code based on the [Data Access Application Block](http://msdn.microsoft.com/en-us/library/dd203144.aspx) in the [Enterprise Library](http://msdn.microsoft.com/en-us/library/cc467894.aspx).* | Binding query parameters by name with ODP.NET | [
"",
"c#",
"oracle",
"ado.net",
"odp.net",
""
] |
let's say i have directory paths looking like this:
```
this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b
```
In Python, how can i split these paths up so they will look like this instead:
```
a/include
b/include
a
b
```
If i run os.path.split(path)[1] it will display:
```
include
include
a
b
```
What should i be trying out here, should i be looking at some regex command or can this be done without it? Thanks in advance.
EDIT ALL: I solved it using regular expressions, damn handy tool :) | Perhaps something like this, depends on how hardcoded your prefix is:
```
def removePrefix(path, prefix):
plist = path.split(os.sep)
pflist = prefix.split(os.sep)
rest = plist[len(pflist):]
return os.path.join(*rest)
```
Usage:
```
print removePrefix("this/is/the/basedir/path/b/include", "this/is/the/basedir/path")
b/include
```
Assuming you're on a platform where the directory separator (`os.sep`) really is the forward slash).
This code tries to handle paths as something a little more high-level than mere strings. It's not optimal though, you could (or should) do more cleaning and canonicalization to be safer. | what about [partition](http://docs.python.org/library/stdtypes.html?highlight=partition#str.partition)?
It Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
```
data = """this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b"""
for line in data.splitlines():
print line.partition("this/is/the/basedir/path/")[2]
#output
a/include
b/include
a
b
```
Updated for the new comment by author:
It looks like u need rsplit for different directories by whether the directory endswith "include" of not:
```
import os.path
data = """this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b"""
for line in data.splitlines():
if line.endswith('include'):
print '/'.join(line.rsplit("/",2)[-2:])
else:
print os.path.split(line)[1]
#or just
# print line.rsplit("/",1)[-1]
#output
a/include
b/include
a
b
``` | Question about paths in Python | [
"",
"python",
"operating-system",
""
] |
I want to make movement such as the tail command with PHP,
but how may watch append to the file? | I don't believe that there's some magical way to do it. You just have to continuously poll the file size and output any new data. This is actually quite easy, and the only real thing to watch out for is that file sizes and other stat data is cached in php. The solution to this is to call `clearstatcache()` before outputting any data.
Here's a quick sample, that doesn't include any error handling:
```
function follow($file)
{
$size = 0;
while (true) {
clearstatcache();
$currentSize = filesize($file);
if ($size == $currentSize) {
usleep(100);
continue;
}
$fh = fopen($file, "r");
fseek($fh, $size);
while ($d = fgets($fh)) {
echo $d;
}
fclose($fh);
$size = $currentSize;
}
}
follow("file.txt");
``` | ```
$handle = popen("tail -f /var/log/your_file.log 2>&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer\n";
flush();
}
pclose($handle);
``` | How To watch a file write in PHP? | [
"",
"php",
"tail",
""
] |
Code Snippet:
```
ShippingPeriod[] arrShippingPeriods;
.
.
.
List<ShippingPeriod> shippingPeriods = ShippingPeriodList.ToList<ShippingPeriod>();
```
The Last line won't compile and the error I get is:
"'ShippingPeriod[]' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)' has some invalid arguments" | try this:
```
ShippingPeriod [] arrShippingPeriods;
//init and populate array
IList<ShippingPeriods> lstShippingPeriods =
arrShippingPeriods.ToList<ShippingPeriods>();
```
You need to call **ToList** on the array object not the class of objects contained in array. | As others have said, you need to call `ToList` on your array. You haven't shown what `ShippingPeriodList` is.
However, when you get that bit right, note that you won't need to provide the type argument, as type inference will do it for you. In other words, this should work fine:
```
List<ShippingPeriod> list = arrShippingPeriods.ToList();
``` | C# - Convert a Type Array to a Generic List | [
"",
"c#",
""
] |
I have this code:
```
$.getJSON("Featured/getEvents",
function(data){
$.each(data.events, function(i,event){
var title = event.title.substr(0,20);
$("#title-"+i).text("Text");
if ( i == 4 ) return false;
});
});
```
I am doing this in conjuction with a php loop to render a div 5 times, I want to place my content into the ID's from the JSON using var and the .text(), but it is not working, How do I get a var, in this case title into the jquery text() so it can place it in the corresponding div?
This is the corresponding php(partial) that this connects to:
```
<?php for($i = 0; $i <= 4; $i++)
{ ?>
<div id="event-item-<?= $i?>" class="event">
<div class="column-left">
<div class="title"><h3><a href="" id="title-<?= $i?>"></a></h3></div>
```
This is the rendered version:
```
<div id="event-item-0" class="event">
<div class="column-left">
<div class="title"><h3><a href="" id="title-0"></a></h3></div>
<div class="inner-left">
<img src="http://philly.cities2night.com/event/85808/image_original" class="image" width="133" height="100">
<p class="author">Posted by: <br> <a href="#">Brendan M. (22 Events)</a></p>
</div>
<div class="inner-middle">
<p class="description" id="description-0"></p>
<p class="notify"><img src="images/recommened_ico.png" alt="Recommened Event" width="98" height="21"></p>
<p class="links">
<!-- AddThis Button BEGIN -->
<a href="http://www.addthis.com/bookmark.php?v=250&pub=philly2night" onmouseover="return addthis_open(this, '', '[URL]', '[TITLE]')" onmouseout="addthis_close()" onclick="return addthis_sendto()"><img src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" style="border: 0pt none ;" width="125" height="16"></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=philly2night"></script>
<!-- AddThis Button END -->
<a href="#" class="button">View Event</a></p>
</div>
</div>
<div class="column-right">
<ul id="event-options">
<li class="total-attending"><span><a href="#">502</a>Attending</span></li>
<li class="rsvp"><span><a href="#">RSVP</a></span></li>
<li id="like" class="notlike"><span>(3) Likes <br><span class="message"><a href="javascript:;" class="likeon">Do You Like it?</a></span></span></li>
<li class="comment"><span><a href="#">Comments (200)</a></span></li>
<li class="location"><span><a href="#">Location Name</a></span></li>
</ul>
</div>
</div>
...
</div>
``` | It should be as simple as referencing the variable.
```
$("#title-"+i).text( title );
```
or, if your title includes mark up,
```
$("#title-"+i).html( title );
```
If this doesn't work, make sure that you aren't getting any javascript errors that prevent the code from running.
**EDIT**: This may or may not be related, but I would avoid using event as a variable name. Too easy to confuse with the window.event object and it may cause other problems. Generally, I'd use evt in this case.
Other possibilities: You aren't running the getJSON method after the document is done loading or the method isn't relative to the current page. If the simple things don't seem to be getting you anywhere, you may try using Firefox/Firebug to step through the code and see what it is doing. My simple example with your mark up and just using jQuery to set the text of the anchor worked fine so I don't think the problem is in the code where the text is being set.
```
$(function() {
$.getJSON("/Featured/getEvents",
function(data){
$.each(data.events, function(i,evt){
var title = evt.title.substr(0,20);
$("#title-"+i).text(title);
if ( i == 4 ) return false;
});
});
});
``` | You want to use [.html(val)](http://docs.jquery.com/Attributes/html#val).
Edit: Actually, [.text(val)](http://docs.jquery.com/Attributes/text#val) will place the text inside the element as-is. Using [.html(val)](http://docs.jquery.com/Attributes/html#val) will let any HTML you are adding render appropriately. | jquery and json pull data from var | [
"",
"php",
"jquery",
"json",
""
] |
I've tried many functions already, but I simply can't figure this out. The right way, anyway.
In a form field called description, I can expect all kinds of characters. These need to be formatted into HTML entities before they're submitted to the db.
Now, my code:
```
$formdesc = htmlentities($_POST['formdesc'], ENT_QUOTES);
```
For a MySQL query, I simply add a "safe" function to slash the ' off the string:
```
mysql_real_escape_string($formdesc);
```
However, this sometimes doesn't work. "é," for instance, becomes é instead of é.
There must be a normal function for this. Does anyone know what I mean? | You need to specify the encoding for the [`htmlentities` function](http://docs.php.net/htmlentities) (here UTF-8):
```
$formdesc = htmlentities($_POST['formdesc'], ENT_QUOTES, 'UTF-8');
```
Otherwise the default value `ISO-8859-1` is used and the character `é` in your example encoded in UTF-8 as 0xC3A9 would be interpreted as two characters (`Ã` and `©`).
But why do you use `htmlentities` anyway? If you just want to escape the HTML special characters like `&`, `<`, `>`, `"` and `'` [`htmlspecialchars`](http://docs.php.net/htmlspecialchars) will suffice. | have you tried looking at [htmlspecialchars()](http://uk.php.net/manual/en/function.htmlspecialchars.php) and [htmlspecialchars\_decode()](http://uk.php.net/manual/en/function.htmlspecialchars-decode.php)
Josh | Conversion of special characters in PHP | [
"",
"php",
"string",
"character-encoding",
""
] |
I learnt HTML/CSS a good few years back, then PHP a little later. I've recently become interesting in web development again, just started playing with frameworks like Django and RoR. I'm curious as to how much time/effort I should spend learning straight JS before looking at frameworks. I've been reading through a let of articles called [Mastering AJAX by Brett McLaughlin](http://www.ibm.com/developerworks/views/web/libraryview.jsp?search_by=Mastering+Ajax) which seems quite good, but I'm seeing a lot of stuff (such as cross browser compatibility - even for things like XMLHttpRequest) coming up which look like they would be non-issues if using a framework.
So, should I keep reading through these articles and try to build stuff using basic JS, or should I just start looking into jQuery and the like?
Also, I've been watching a few videos regarding GWT from Google I/O. I've been learning Java over the last year, built a few medium sized apps in it. I'm wondering if GWT is something that's worth going straight to, along with gQuery? | Starting with the basics of JavaScript is a good idea, IMHO.
Read [**JavaScript: The Good Parts**](http://oreilly.com/catalog/9780596517748/), by **Douglas Crockford**. Very, very good book.

You should also check out [Douglas Crockford's web site](http://www.crockford.com).
I also had to come back here and mention this in an update:
Douglas Crockford presented an illuminating talk about JavaScript - past, present, future - at the Microsoft MIX10 conference earlier this year. You'll find the full video for Crockford's talk at [**Microsoft MIX10 - The Tale of JavaScript. I Mean ECMAScript**](http://live.visitmix.com/MIX10/Sessions/EX39). | No.
Just as when you are learning to program you are taught first C/Pascal then Java/C++ and finally Python/Ruby/Smalltalk/Lisp, and when learning any language you start with simple language constructs, you should first learn ECMAScript, then learn DOM and finally frameworks.
Why? Because you'll have a deeper understanding of the language, and will be able to debug things that might seem odd unless you've got that learning experience.
If you are a seasoned developer, you can speed up each phase, but don't skip them, or you **will** have problems due to not fully understanding the small oddities.
Javascript is an interesting and *fun* language, but can act rather odd at times (`Date` has bitten me a couple of times in the ass).
Use frameworks to avoid repetitive tasks and to simplify your code, but not as a starting point. Simplicity is a final goal, not the starting point, and frameworks are for that, simplicity, not for learning a language. Frameworks are intended for simplifying things for experienced developers.
---
Learning the differences between browsers (DOM implementations) will allow you to debug your framework. That is priceless.
---
> I've been learning Java over the last
> year...
[Javascript](http://www.crockford.com/javascript/javascript.html) [is **not**](http://kb.mozillazine.org/JavaScript_is_not_Java) [Java](http://www.ericgiguere.com/articles/javascript-is-not-java.html). Never was never will.
Even if you can *compile to* Javascript from Java, it's still a framework, don't jump into it unless you already know what you are doing. | Learning JavaScript... Should I skip straight to the good stuff (the frameworks)? | [
"",
"javascript",
"jquery",
"gwt",
"frameworks",
""
] |
How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | This is as close as you can get to full screen in JavaScript:
```
<script type="text/javascript">
window.onload = maxWindow;
function maxWindow() {
window.moveTo(0, 0);
if (document.all) {
top.window.resizeTo(screen.availWidth, screen.availHeight);
}
else if (document.layers || document.getElementById) {
if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth) {
top.window.outerHeight = screen.availHeight;
top.window.outerWidth = screen.availWidth;
}
}
}
</script>
``` | In newer browsers such as Chrome 15, Firefox 10, Safari 5.1, IE 10 this is possible. It's also possible for older IE's via ActiveX depending on their browser settings.
Here's how to do it:
```
function requestFullScreen(element) {
// Supports most browsers and their versions.
var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
if (requestMethod) { // Native full screen.
requestMethod.call(element);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
var elem = document.body; // Make the body go full screen.
requestFullScreen(elem);
```
The user obviously needs to accept the fullscreen request first, and there is not possible to trigger this automatically on pageload, it needs to be triggered by a user (eg. a button)
Read more: <https://developer.mozilla.org/en/DOM/Using_full-screen_mode> | How to make the window full screen with Javascript (stretching all over the screen) | [
"",
"javascript",
"fullscreen",
""
] |
It seems simple, but I can't get it work.
I have a string which look like 'NNDDDDDAAAA', where 'N' is non digit, 'D' is digit, and 'A' is anything. I need to replace each A with a space character. Number of 'N's, 'D's, and 'A's in an input string is always different.
I know how to do it with two expressions. I can split a string in to two, and then replace everything in second group with spaces. Like this
```
Pattern pattern = Pattern.compile("(\\D+\\d+)(.+)");
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
return matcher.group(1) + matcher.group(2).replaceAll(".", " ");
}
```
But I was wondering if it is possible with a single regex expression. | I know you asked for a regex, but why do you even need a regex for this? How about:
```
StringBuilder sb = new StringBuilder(inputString);
for (int i = sb.length() - 1; i >= 0; i--) {
if (Character.isDigit(sb.charAt(i)))
break;
sb.setCharAt(i, ' ');
}
String output = sb.toString();
```
You might find [this post](http://www.codinghorror.com/blog/archives/001016.html) interesting. Of course, the above code assumes there will be at least one digit in the string - all characters following the last digit are converted to spaces. If there are no digits, every character is converted to a space. | Given your description, I'm assuming that after the `NNDDDDD` portion, the first `A` will actually be a `N` rather than an `A`, since otherwise there's no solid boundary between the `DDDDD` and `AAAA` portions.
So, your string actually looks like `NNDDDDDNAAA`, and you want to replace the `NAAA` portion with spaces. Given this, the regex can be rewritten as such: `(\\D+\\d+)(\\D.+)`
Positive lookbehind in Java requires a fixed length pattern; You can't use the `+` or `*` patterns. You can instead use the curly braces and specify a maximum length. For instance, you can use `{1,9}` in place of each `+`, and it will match between 1 and 9 characters: `(?<=\\D{1,9}\\d{1,9})(\\D.+)`
The only problem here is you're matching the NAAA sequence as a single match, so using `"NNNDDDDNAAA".replaceAll("(?<=\\D{1,9}\\d{1,9})(\\D.+)", " ")` will result in replacing the entire `NAAA` sequence with a single space, rather than multiple spaces.
You could take the beginning delimiter of the match, and the string length, and use that to append the correct number of spaces, but I don't see the point. I think you're better off with your original solution; Its simple and easy to follow.
If you're looking for a little extra speed, you could compile your Pattern outside the function, and use StringBuilder or StringBuffer to create your output. If you're building a large String out of all these NNDDDDDAAAAA elements, work entirely in StringBuilder until you're done appending.
```
class Test {
public static Pattern p = Pattern.compile("(\\D+\\d+)(\\D.+)");
public static StringBuffer replace( String input ) {
StringBuffer output = new StringBuffer();
Matcher m = Test.p.matcher(input);
if( m.matches() )
output.append( m.group(1) ).append( m.group(2).replaceAll("."," ") );
return output;
}
public static void main( String[] args ) {
String input = args[0];
long startTime;
StringBuffer tests = new StringBuffer();
startTime = System.currentTimeMillis();
for( int i = 0; i < 50; i++)
{
tests.append( "Input -> Output: '" );
tests.append( input );
tests.append( "' -> '" );
tests.append( Test.replace( input ) );
tests.append( "'\n" );
}
System.out.println( tests.toString() );
System.out.println( "\n" + (System.currentTimeMillis()-startTime));
}
}
```
**Update:**
I wrote a quick iterative solution, and ran some random data through both. The iterative solution is around 4-5x faster.
```
public static StringBuffer replace( String input )
{
StringBuffer output = new StringBuffer();
boolean second = false, third = false;
for( int i = 0; i < input.length(); i++ )
{
if( !second && Character.isDigit(input.charAt(i)) )
second = true;
if( second && !third && Character.isLetter(input.charAt(i)) )
third = true;
if( second && third )
output.append( ' ' );
else
output.append( input.charAt(i) );
}
return output;
}
``` | Regex to replace part of the string with spaces | [
"",
"java",
"regex",
""
] |
Has anyone been able to implement a scrollable table in HTML where the TOP row and LEFT columns are frozen, but the rest of the table is scrollable? A perfect example of this is:
[Google Squared](http://www.google.com/squared/search?q=US%20presidents&suggest=1)
I tried to reverse engineer the code for the google squared table, but I have been unsuccessful so far.
**Note: I need the ability to FREEZE the TOP ROW and the LEFT COLUMN at the same time.** | There's a working example at <http://ajaxian.com/archives/freeze-pane-functionality> that should be easy to duplicate. Be sure to note the comments -- many of the users have made helpful suggestions for improving the script.
Per @Nirk's request, a direct link to the active demo is at <http://www.disconova.com/open_source/files/freezepanes.htm>. | Go with a basic structure like this-
```
table
row
column (blank)
column
table (1 row high, column headers)
row
column
table (1 column wide, row headers)
column
div (fixed height & width, overflow auto)
table (actual data)
```
Set a fixed table-layout and specify column widths in pixels explicitly. You should be able to achieve the same effect. | Scrollable HTML table with top row and left column frozen | [
"",
"javascript",
"html",
"scrollable-table",
""
] |
I have a PHP script that does the following:
* Uses file\_get\_contents() to get content of html file
* Echos a JSON object
The issue is that the value obtained from file\_get\_contents is multi line. It needs to be all on one line in order to be in correct JSON format.
For example
PHP File:
```
$some_json_value = file_get_contents("some_html_doc.html");
echo "{";
echo "\"foo\":\"$some_json_value\"";
echo "}";
```
The resulting html document looks like:
```
{
foo: "<p>Lorem ipsum dolor
sit amet, consectetur
adipiscing elit.</p>"
}
```
My goal is to get the resulting html document to look like this (value is one line, not three)
```
{
foo: "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>"
}
```
How can this be done. I realize that the content will be one line if the original html doc is one line; however, I'm trying to avoid that solution.
**Update**
The question was answered correctly. Here is the complete, working code:
```
$some_json_value = file_get_contents("some_html_doc.html");
$some_json_value = json_encode($some_json_value); // this line is the solution
echo "{";
echo "\"foo\":\"$some_json_value\"";
echo "}";
``` | There are characters other than line-breaks which will cause you problems (double quotes and backslashes for example) and so rather than just strip out line-breaks, it would be better to encode your JSON properly. For PHP >= 5.2 there's the built-in `json_encode` function and there are libraries available for older versions of PHP (see e.g., <http://abeautifulsite.net/notebook/71>) | Do a simple replace?
```
$content = str_replace(
array("\r\n", "\n", "\r"),
'',
file_get_contents('some_html_doc.html')
);
```
But a better idea would be to do a [json\_encode()](https://www.php.net/json_encode) right away;
```
$content = json_encode(file_get_contents('some_html_doc.html'));
``` | Remove line breaks and new lines from PHP variable value? | [
"",
"php",
"json",
"file-get-contents",
""
] |
I know Java's generics are somewhat inferior to .Net's.
I have a generic class `Foo<T>`, and I really need to instantiate a `T` in `Foo` using a parameter-less constructor. How can one work around Java's limitation? | One option is to pass in `Bar.class` (or whatever type you're interested in - any way of specifying the appropriate `Class<T>` reference) and keep that value as a field:
```
public class Test {
public static void main(String[] args) throws IllegalAccessException,
InstantiationException {
Generic<Bar> x = new Generic<>(Bar.class);
Bar y = x.buildOne();
}
}
public class Generic<T> {
private Class<T> clazz;
public Generic(Class<T> clazz) {
this.clazz = clazz;
}
public T buildOne() throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
}
public class Bar {
public Bar() {
System.out.println("Constructing");
}
}
```
Another option is to have a "factory" interface, and you pass a factory to the constructor of the generic class. That's more flexible, and you don't need to worry about the reflection exceptions. | And this is the Factory implementation, as [Jon Skeet suggested](https://stackoverflow.com/questions/1090458/instantiating-a-generic-class-in-java/1090488#1090488):
```
interface Factory<T> {
T factory();
}
class Araba {
//static inner class for Factory<T> implementation
public static class ArabaFactory implements Factory<Araba> {
public Araba factory() {
return new Araba();
}
}
public String toString() { return "Abubeee"; }
}
class Generic<T> {
private T var;
Generic(Factory<T> fact) {
System.out.println("Constructor with Factory<T> parameter");
var = fact.factory();
}
Generic(T var) {
System.out.println("Constructor with T parameter");
this.var = var;
}
T get() { return var; }
}
public class Main {
public static void main(String[] string) {
Generic<Araba> gen = new Generic<Araba>(new Araba.ArabaFactory());
System.out.print(gen.get());
}
}
```
Output:
```
Constructor with Factory<T> parameter
Abubeee
``` | Instantiating a generic class in Java | [
"",
"java",
"generics",
""
] |
Why is an array called a derived data type? | None of the base datatypes provide u to store more than 1 value [ Eg : int, char, float etc ]
An array is nothing but, an extended form of the base data type, holding N items of the base data type. So, due to this, array is called the derived data type. | The reason is that they are derived from the fundamental data types. (Actually, the [version of the standard I looked up](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf) puts them under **Compound types**.) | Derived data type | [
"",
"c++",
"types",
""
] |
If I have a Windows Service that needs to execute a task every 30 seconds which is better to use; the Timer() class or a loop that executes the task then sleeps for a number of seconds?
```
class MessageReceiver
{
public MessageReceiver()
{
}
public void CommencePolling()
{
while (true)
{
try
{
this.ExecuteTask();
System.Threading.Thread.Sleep(30000);
}
catch (Exception)
{
// log the exception
}
}
}
public void ExecutedTask()
{
// do stuff
}
}
class MessageReceiver
{
public MessageReceiver()
{
}
public void CommencePolling()
{
var timer = new Timer()
{
AutoReset = true,
Interval = 30000,
Enabled = true
};
timer.Elapsed += Timer_Tick;
}
public void Timer_Tick(object sender, ElapsedEventArgs args)
{
try
{
// do stuff
}
catch (Exception)
{
// log the exception
}
}
}
```
The windows service will create an instance of the MessageReciever class and execute the CommencePolling method on a new thread. | I think it really depends on your requirement.
**case 1.**
Suppose you want to run `this.ExecuteTask()` every five minutes starting from 12:00AM (i.e., 12:00, 12:05, ...) and suppose the execution time of `this.ExecuteTask()` varies (for example, from 30 sec to 2 min), maybe using timer instead of Thread.Sleep() seems to be an easier way of doing it (at least for me).
However, you can achieve this behavior with `Thread.Sleep()` as well by calculating the offset while taking timestamps on a thread wake-up and on a completion of `this.ExecuteTask()`.
**case 2.**
Suppose you want to perform the task in the next 5 min just after completion of `this.ExecuteTask()`, using `Thread.Sleep()` seems to be easier. Again, you can achieve this behavior with a timer as well by reseting the timer every time while calculating offsets on every time `this.ExecuteTask()` completes.
**Note1**, for the case 1, you should be very careful in the following scenario: what if `this.ExecuteTask()` sometimes takes more than the period (i.e. it starts at 12:05 and completes 12:13 in the example above).
1. What does this mean to your application and how will it be handled?
a. Total failure - abort the service or abort the current(12:05) execution at 12:10 and launch 12:10 execution.
b. Not a big deal (skip 12:10 one and run `this.ExecuteTask()` at 12:15).
c. Not a big deal, but need to launch 12:10 execution immediately after 12:05 task finishes (what if it keeps taking more than 5 min??).
d. Need to launch 12:10 execution even though 12:05 execution is currently running.
e. anything else?
2. For the policy you select above, does your choice of implementation (either timer or `Thread.Sleep()`) easy to support your policy?
**Note2**. There are several timers you can use in .NET. Please see the following document (even though it's bit aged, but it seems to be a good start): [Comparing the Timer Classes in the .NET Framework Class Library](http://msdn.microsoft.com/en-us/magazine/cc164015.aspx) | Are you doing anything else during that ten second wait? Using Thread.sleep would block, preventing you from doing other things. From a performance point of view I don't think you'd see too much difference, but I would avoid using Thread.sleep myself.
There are three timers to choose from - System.Windows.Forms.Timer is implemented on the main thread whereas System.Timers.Timer and System.Threading.Timer are creating seperate threads. | Windows service scheduled execution | [
"",
"c#",
"windows-services",
""
] |
i am tring to add "翻訳するテキストやWebページ " into a PostgreSQL table, but its shown like this:
```
"& #32763;""& #35379;"す& #12427;テ& #12461;& #12473;& #12488;& #12420;Web& #12506;& #12540;& #12472;
```
How can I insert that in proper format?
```
<?php
$db = pg_connect("host=localhost port=5432 dbname=lang user=password=") or die(":(");
pg_set_client_encoding($db , "UTF-8");
#pg_exec($db,"SET NAMES 'UTF-8'");
#pg_exec($db,"SET CLIENT_ENCODING TO 'UTF-8'");
//$lan=iconv("UTF-8",'ISO-8859-1//TRANSLIT',$_REQUEST['lan']);
$lan=$_REQUEST['lan'];
echo $lan;
if(array_key_exists('sub',$_REQUEST))
{
$sql="INSERT INTO table1 (japan) VALUES('{$lan}')";
pg_query($sql) or die("errot");
}
?>
<html>
<body>
<form action="" method="">
<input type="text" name="lan" />
<input type="submit" name="sub" />
</form>
</body>
</html>
``` | what you have will work as long as `table1` has the right collation
see <http://www.postgresql.org/docs/8.1/static/sql-createdatabase.html> for setting the encoding (database-wide)
see <http://www.postgresql.org/docs/8.1/static/multibyte.html> for the character support available and how to use them
**edit**
note that php provides a [pg\_set\_client\_encoding()](https://www.php.net/manual/en/function.pg-set-client-encoding.php) to change the encoding, however, like the direct sql query that does the same, it converts **from** the backend encoding **to** the requested client encoding and doesn't help with inserts. For that to work, the database/postreSQL must have the correct encoding set (see the first two references).
(note: mysql handles collations *much* better so if you aren't too far along and you require multiple collations then it may be a good idea to switch) | It seem that the issue is not related to the database at all.
Simply your HTML lacks encoding declaration (in practice there's no reliable default encoding for HTML and you will get garbage).
Add appropriate `<meta>` tag or send `Content-Type` header with `charset` parameter.
---
BTW: you've got SQL injection vulnerability in the code. Don't put request variables in queries. Use prepared statements or at least always use `pg_quote()`. | How to insert Japanese text into a Postgres table using PHP? | [
"",
"php",
"postgresql",
"unicode",
""
] |
I am running some profiling tests, and usleep is an useful function. But while my program is sleeping, this time does not appear in the profile.
eg. if I have a function as :
```
void f1() {
for (i = 0; i < 1000; i++)
usleep(1000);
}
```
With profile tools as gprof, f1 does not seems to consume any time.
What I am looking is a method nicer than an empty while loop for doing an active sleep, like:
```
while (1) {
if (gettime() == whatiwant)
break;
}
``` | What kind of a system are you on? In UNIX-like systems you can use setitimer() to send a signal to a process after a specified period of time. This is the facility you would need to implement the type of "active sleep" you're looking for.
Set the timer, then loop until you receive the signal. | Because when you call usleep the CPU is put to work to something else for 1 second. So the current thread does not use any processor resources, and that's a very clever thing to do.
An active sleep is something to absolutely avoid because it's a waste of resources (ultimately damaging the environment by converting electricity to heat ;) ).
Anyway if you really want to do that you must give some real work to do to the processor, something that will not be factored out by compiler optimizations. For example
```
for (i = 0; i < 1000; i++)
time(NULL);
``` | How to do an active sleep? | [
"",
"c++",
"c",
"profiling",
"sleep",
""
] |
Is it possible in Eclipse to create a separate Folder in a package? When select "new --> folder", my eclipse version always creates a package. But i want the new folder to be in the old package.
How can this be achieved?
Thanks in advance...
Patrick | What you might want to do, if you aren't putting code in that folder, is remove the folder from the build path. Right-click on the offending folder in eclipse and choose 'exclude from build path.'
Or, you may want a different effect:
Right click on your project and choose add new source folder.
Then in that folder, add the correct package folder structure.
You can have files in the same package located in different folders. | You need to exclude the folder from the source path | Creating a separate Folder in the same package... [ECLIPSE] | [
"",
"java",
"eclipse",
"ide",
""
] |
What is the best way to read in a tab delimited file in C++ and store each line as a record? I have been looking for an open source library to help with this, but have been unsuccessful so it looks like I will have to write my own. | ```
typedef vector<vector<string> > Rows;
Rows rows;
ifstream input("filename.csv");
char const row_delim = '\n';
char const field_delim = '\t';
for (string row; getline(input, row, row_delim); ) {
rows.push_back(Rows::value_type());
istringstream ss(row);
for (string field; getline(ss, field, field_delim); ) {
rows.back().push_back(field);
}
}
```
This will get you started. It doesn't do any checking that each row has the same number of fields, allow for escaping `field_delim`, etc. | There is no problem in using iostreams - you could read each line with getline into string, and then use stringstream on that string to iterate over fields. | Reading delimited files in C++ | [
"",
"c++",
"open-source",
"csv",
""
] |
May be I am getting old, but I can't find it... | linux package manager (which ever you are using). It will save you a lot of hassle. | It is never so easy to find what you want at that site, but luckily today I have found it ;).
<https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jdk-6u14-oth-JPR@CDS-CDS_Developer> | Where do I download a Java 6 JDK for Linux? | [
"",
"linux",
"sdk",
"java",
""
] |
I use this query to display a list of songs and show what songs have been clicked as a favorite by a user.
```
$query = mysql_query(
sprintf("
SELECT
s.*,
UNIX_TIMESTAMP(`date`) AS `date`,
f.userid as favoritehash
FROM
songs s
LEFT JOIN
favorites f
ON
f.favorite = s.id
AND f.userid = %s",
$userhash)
);
```
The `songs` table is setup as: `id artist title duration` etc. etc.
The `favorites` table is setup as: `id favorite userid`
The `userid` is a hashed value stored in a cookie to reference a unique user.
The query works fine but for some reason if I mark a song as a favorite in one browser. And then mark the same song as favorite in another browser to simulate multiple users the song will be displayed twice... once for each time it is marked favorite but the favorite indicator a <3 will still display correctly.
Any ideas?
Well got it to work via removign the sprintf() but curious to know why this is if anyone has any ideas. | You are using sprintf and %s (string), but you are not enclosing the resulting string value in quotes. If the user ID is a string, then you need to enclose it in quotes, otherwise use %d instead of %s. Since it works fine when you remove sprintf, that would seem to be the problem. | I had a similar issue I think if you change the And F.userid = %s to Where f.userid = %s it should fix it?. | join query returning odd results | [
"",
"php",
"mysql",
""
] |
been taxing my brain trying to figure out how to perform a linq xml query.
i'd like the query to return a list of all the "product" items where the category/name = "First Category" in the following xml
```
<catalog>
<category>
<name>First Category</name>
<order>0</order>
<product>
<name>First Product</name>
<order>0</order>
</product>
<product>
<name>3 Product</name>
<order>2</order>
</product>
<product>
<name>2 Product</name>
<order>1</order>
</product>
</category>
</catalog>
``` | Like so:
```
XDocument doc = XDocument.Parse(xml);
var qry = from cat in doc.Root.Elements("category")
where (string)cat.Element("name") == "First Category"
from prod in cat.Elements("product")
select prod;
```
or perhaps with an anonymous type too:
```
XDocument doc = XDocument.Parse(xml);
var qry = from cat in doc.Root.Elements("category")
where (string)cat.Element("name") == "First Category"
from prod in cat.Elements("product")
select new
{
Name = (string)prod.Element("name"),
Order = (int)prod.Element("order")
};
foreach (var prod in qry)
{
Console.WriteLine("{0}: {1}", prod.Order, prod.Name);
}
``` | Here's an example:
```
string xml = @"your XML";
XDocument doc = XDocument.Parse(xml);
var products = from category in doc.Element("catalog").Elements("category")
where category.Element("name").Value == "First Category"
from product in category.Elements("product")
select new
{
Name = product.Element("name").Value,
Order = product.Element("order").Value
};
foreach (var item in products)
{
Console.WriteLine("Name: {0} Order: {1}", item.Name, item.Order);
}
``` | "where" query using linq xml | [
"",
"c#",
"xml",
"linq",
""
] |
This is a C# WinForm question. I have a MDI child form, when the form is opened, it will generate many tables to display in a DataGridView. The tables can be big and I use DataBinding to connect the tables to the DataGridView. When I close the form, I notice that the memory taken by the form is reclaimed timely.
I use the normal way of showing the MDI child form as:
```
var f = new FormBigMemory(objPassedIn);
f.Show();
```
As shown here, I cannot explicitly call the Dispose() method of the form. I assume that when f is out of its life circle, .net will automatically reclaim the memory it takes.
Since the form takes a lot memory, I want to explicitly call GC.Collect(); (I know it may not be a good idea to do so). In order to do this, I change the code to show the form in dialog model using the following code:
```
using(var f = new FormBigMemoryDialog(objPassedIn);
{
f.ShowDialog();
}
GC.Collect();
```
I am very disappointed to see that the memory taken by the form isn't reclaimed after GC.Collect() is called. I use memory profiler tool to get the snapshot of the memory after the form is closed and GC.Collect() is called. The biggest memory is held up by a BindingList! I really don't understand: if the whole form is disposed, why the BindingList still exists in the memory. I have checked my code and there is no where the BindingList reference is leaked out of the form.
Any idea why this wired thing happens to me? Many thanks to any suggestion and tips on .net memory management.
**Edit:**
Thanks for many answers. Let me clear some points.
1. I don't mean to dispose the BindingList. A BindingList is used as an array in my code so I would expect to see the reclaim of the memory held by the BindingList. My bad not to say clearly.
2. I understand not to call the GC action myself. But in my case, I want to explicitly see the reclaim of memory held up by the form immediately after the form is closed, anyway to do that? Example code?
3. In my problem, I can repeatedly open the same form multiple times and each time I close the form, the memory consumption increases, until the OutOfMemory throws. This is obviously not right. What I expect to see is, after the form is closed, the memory drops back to the original level and I can repeatedly open the form and close it without increasing the memory (dramatically).
**Edit 2:**
I further investigated the code. The biggest array (a BindingList) is not released after the form is closed. It is referred by a BindingSource and the BindingSource is referred by EventHandler, CurrencyManager, and a user control. The BindingSource and the user control are both referred by the (closed) form and the (closed) form is referred by some event handlers.
The above is the memory snapshot after I closed the form. I use dialog model to open the form and after it is closed, its Dispose() method is called and after that I also call GC.Collect() to force the memory to be reclaimed. Why after this the form instance still exists in my memory snapshot?? | Never call GC.Collect unless you have a very good reason to do so.
I don't know the details, but this is what I know:
* Something is removed after **all** references are removed.
* The GC won't try to remove all stuff at once, it doesn't want to disturb the program from running.
* There is a good chance the form is just hidden, instead of closed. How do you close the form?
* As [Mitch Wheat says](https://stackoverflow.com/questions/1113962/when-winform-releases-its-resources-c/1114127#1114127), Event Handlers can be stubborn, as you often forget to remove them.
* Dispose does not make the form being removed from memory, it calls a plain method inside the form, maybe you can insert your own cleanup logic inside it. | Are you sure that you are unwiring all event handlers that the form uses?
Update in response to question in comments: Whenever an object adds an event handler to an event (+= EventHandler) there should be a corresponding (-= EventHandler) when you are finished with the object instance. Otherwise, it will act as a root object in the heap, and garbage collection will not reclaim. | When WinForm releases its resources? (C#) | [
"",
"c#",
".net",
"winforms",
""
] |
in languages like PHP or Python there are convenient functions to turn an input string into an output string that is the HEXed representation of it.
I find it a very common and useful task (password storing and checking, checksum of file content..), but in .NET, as far as I know, you can only work on byte streams.
A function to do the work is easy to put on (eg <http://blog.stevex.net/index.php/c-code-snippet-creating-an-md5-hash-string/>), but I'd like to know if I'm missing something, using the wrong pattern or there is simply no such thing in .NET.
Thanks | The method you linked to seems right, a slightly different method is showed on the [MSDN C# FAQ](http://blogs.msdn.com/csharpfaq/archive/2006/10/09/How-do-I-calculate-a-MD5-hash-from-a-string_3F00_.aspx)
A comment suggests you can use:
```
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(string, "MD5");
``` | Yes you can only work with bytes (as far as I know). But you can turn those bytes easily into their hex representation by looping through them and doing something like:
```
myByte.ToString("x2");
```
And you can get the bytes that make up the string using:
```
System.Text.Encoding.UTF8.GetBytes(myString);
```
So it could be done in a couple lines. | C#: String -> MD5 -> Hex | [
"",
"c#",
"hash",
"md5",
""
] |
My C# class MyClass (below) has members a, b, c, d, e, and f.
I'd like to use reflection to obtain a list of the data types of those members;
for example (borrowing from Python notation): [ char[], ushort, char, byte, uint, ulong ].
```
class MyClass
{
public char [ ] a ;
public ushort b ;
public char c ;
public byte d ;
public uint e ;
public ulong f ;
}
class MainClass
{
public static void Main ( string [] args )
{
// get an array (or some kind of list) of MyClass' fields' data types ...
// for example: { char[], ushort, char, byte, uint, ulong }
// I've tried the following, but can't get a column of just the data types, alone ...
MemberInfo[] theMemberInfoArray = typeof(MyClass).GetMembers() ;
foreach (MemberInfo mi in theMemberInfoArray)
if (mi.MemberType == MemberTypes.Field)
Console.WriteLine ( "<" + mi.MemberType + ">\t"
+ "<" + mi.GetType() + ">\t"
+ "<" + mi.Name + ">\t" + mi ) ;
}
```
}
Program output appears as below:
```
<Field> <System.Reflection.RtFieldInfo> <a> Char[] a
<Field> <System.Reflection.RtFieldInfo> <b> UInt16 b
<Field> <System.Reflection.RtFieldInfo> <c> Char c
<Field> <System.Reflection.RtFieldInfo> <d> Byte d
<Field> <System.Reflection.RtFieldInfo> <e> UInt32 e
<Field> <System.Reflection.RtFieldInfo> <f> UInt64 f
```
I would like program output to appear as:
```
<Field> <System.Reflection.RtFieldInfo> <a> <Char[]> Char[] a
<Field> <System.Reflection.RtFieldInfo> <b> <UInt16> UInt16 b
<Field> <System.Reflection.RtFieldInfo> <c> <Char> Char c
<Field> <System.Reflection.RtFieldInfo> <d> <Byte> Byte d
<Field> <System.Reflection.RtFieldInfo> <e> <UInt32> UInt32 e
<Field> <System.Reflection.RtFieldInfo> <f> <UInt64> UInt64 f
``` | this is how I did it, you want the FieldType which actually returns a Type instance.
```
var members = typeof(TestMe).GetFields().Select(m => new
{
Name = m.Name,
MemType = m.MemberType,
RtField = m.GetType(),
Type = m.FieldType
});
foreach (var item in members)
Console.WriteLine("<{0}> <{1}> <{2}> <{3}> {3} {2}", item.MemType, item.RtField, item.Name, item.Type, item.Type, item.Name);
public class TestMe
{
public string A;
public int B;
public byte C;
public decimal D;
}
```
This is the output:
```
<Field> <System.Reflection.RtFieldInfo> <A> <System.String> System.String A
<Field> <System.Reflection.RtFieldInfo> <B> <System.Int32> System.Int32 B
<Field> <System.Reflection.RtFieldInfo> <C> <System.Byte> System.Byte C
<Field> <System.Reflection.RtFieldInfo> <D> <System.Decimal> System.Decimal D
``` | I'm not sure that MemberInfo has the information you want. You might want to look at `GetFields()` and the `FieldInfo` class, or `GetProperties()` and the `PropertyInfo` class.
`GetMembers()` returns all fields, properties and methods, so if your class contained these they would be enumerated as well. | Reflection in C# -- want a list of the data types of a class' fields | [
"",
"c#",
"reflection",
"types",
"field",
""
] |
I want to be able to find out if an event is hooked up or not. I've looked around, but I've only found solutions that involved modifying the internals of the object that contains the event. I don't want to do this.
Here is some test code that I thought would work:
```
// Create a new event handler that takes in the function I want to execute when the event fires
EventHandler myEventHandler = new EventHandler(myObject_SomeEvent);
// Get "p1" number events that got hooked up to myEventHandler
int p1 = myEventHandler.GetInvocationList().Length;
// Now actually hook an event up
myObject.SomeEvent += m_myEventHandler;
// Re check "p2" number of events hooked up to myEventHandler
int p2 = myEventHandler.GetInvocationList().Length;
```
Unfort the above is dead wrong. I thought that somehow the "invocationList" in myEventHandler would automatically get updated when I hooked an event to it. But no, this is not the case. The length of this always comes back as one.
Is there anyway to determine this from outside the object that contains the event? | There is a subtle illusion presented by the C# `event` keyword and that is that an event has an invocation list.
If you declare the event using the C# `event` keyword, the compiler will generate a private delegate in your class, and manage it for you. Whenever you subscribe to the event, the compiler-generated `add` method is invoked, which appends the event handler to the delegate's invocation list. There is no explicit invocation list for the event.
Thus, the only way to get at the delegate's invocation list is to preferably:
* Use reflection to access the compiler-generated delegate OR
* Create a non-private delegate (perhaps internal) and implement the event's add/remove methods manually (this prevents the compiler from generating the event's default implementation)
Here is an example demonstrating the latter technique.
```
class MyType
{
internal EventHandler<int> _delegate;
public event EventHandler<int> MyEvent;
{
add { _delegate += value; }
remove { _delegate -= value; }
}
}
``` | If the object concerned has specified the event keyword, then the only things you can do are add (`+=`) and remove (`-=`) handlers, nothing more.
I believe that comparing the invocation list length would work, but you need to be operating *inside* the object to get at it.
Also, keep in mind that the `+=` and `-=` operators return a new event object; they don't modify an existing one.
Why do you want to know if a particular event is hooked up? Is it to avoid registering multiple times?
If so, the trick is to remove the handler first (`-=`) as removing a handler that's not there is legal, and does nothing. Eg:
```
// Ensure we don't end up being triggered multiple times by the event
myObject.KeyEvent -= KeyEventHandler;
myObject.KeyEvent += KeyEventHandler;
``` | C# How to find if an event is hooked up | [
"",
"c#",
"hook",
"event-handling",
""
] |
I was wondering whether it is possible to limit the number of characters we enter in a float.
I couldn't seem to find any method. I have to read in data from an external interface which sends float data of the form xx.xx. As of now I am using conversion to char and vice-versa, which is a messy work-around. Can someone suggest inputs to improve the solution? | Rounding a `float` (that is, *binary* floating-point number) to 2 *decimal* digits doesn't make much sense because you won't be able to round it exactly in some cases anyway, so you'll still get a small delta which will affect subsequent calculations. If you really need it to be precisely 2 places, then you need to use decimal arithmetic; for example, using IBM's [decNumber++](http://www.alphaworks.ibm.com/tech/decnumberplusplus) library, which implements [ISO C/C++ TR 24773 draft](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2849.pdf) | If you always have/want only 2 decimal places for your numbers, and absolute size is not such a big issue, why not work internally with integers instead, but having their meaning be "100th of the target unit". At the end you just need to convert them back to a float and divide by 100.0 and you're back to what you want. | Fixed Length Float in C/C++? | [
"",
"c++",
"c",
""
] |
For performance purposes I want to write to memory, where an external application can read. I can't link both applications together, so I think the only way is by writing a file. But writing it to a physical disk isn't fast enough. I want to mount a virtual partition so any application can access it. How to do it? | You could use a named pipe to transfer the data between applications. | You don't need to go as far as creating a virtual disk to share memory between processes on Windows - you can create a shared memory block, and multiple processes can then access that memory.
See this MSDN article: [Creating Named Shared Memory](http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx) | Can I create a virtual disk in memory programatically? | [
"",
"c#",
".net",
"virtual-disk",
""
] |
I'm working on a multithreaded application, and I want to debug it using GDB.
Problem is, one of my threads keeps dying with the message:
```
pure virtual method called
terminate called without an active exception
Abort
```
I know the cause of that message, but I have no idea where in my thread it occurs. A backtrace would really be helpful.
When I run my app in GDB, it pauses every time a thread is suspended or resumed. I want my app to continue running normally until one of the threads dies with that exception, at which point everything should halt so that I can get a backtrace. | You can try using a "catchpoint" (`catch throw`) to stop the debugger at the point where the exception is generated.
The following [excerpt](http://www.delorie.com/gnu/docs/gdb/gdb_31.html) From the gdb manual describes the catchpoint feature.
---
5.1.3 Setting catchpoints
You can use catchpoints to cause the debugger to stop for certain kinds of program events, such as C++ exceptions or the loading of a shared library. Use the catch command to set a catchpoint.
* catch *event*
> Stop when *event* occurs. event can be any of the following:
+ throw
> The throwing of a C++ exception.
+ catch
> The catching of a C++ exception.
+ exec
> A call to exec. This is currently only available for HP-UX.
+ fork
> A call to fork. This is currently only available for HP-UX.
+ vfork
> A call to vfork. This is currently only available for HP-UX.
+ load *or* load libname
> The dynamic loading of any shared library, or the loading of the library libname. This is currently only available for HP-UX.
+ unload *or* unload libname
> The unloading of any dynamically loaded shared library, or the unloading of the library libname. This is currently only available for HP-UX.
* tcatch event
> Set a catchpoint that is enabled only for one stop. The catchpoint is automatically deleted after the first time the event is caught.
Use the `info break` command to list the current catchpoints.
There are currently some limitations to C++ exception handling (catch throw and catch catch) in GDB:
* If you call a function interactively, GDB normally returns control to you when the function has finished executing. If the call raises an exception, however, the call may bypass the mechanism that returns control to you and cause your program either to abort or to simply continue running until it hits a breakpoint, catches a signal that GDB is listening for, or exits. This is the case even if you set a catchpoint for the exception; catchpoints on exceptions are disabled within interactive calls.
* You cannot raise an exception interactively.
* You cannot install an exception handler interactively.
Sometimes catch is not the best way to debug exception handling: if you need to know exactly where an exception is raised, it is better to stop before the exception handler is called, since that way you can see the stack before any unwinding takes place. If you set a breakpoint in an exception handler instead, it may not be easy to find out where the exception was raised.
To stop just before an exception handler is called, you need some knowledge of the implementation. In the case of GNU C++, exceptions are raised by calling a library function named \_\_raise\_exception which has the following ANSI C interface:
```
/* addr is where the exception identifier is stored.
id is the exception identifier. */
void __raise_exception (void **addr, void *id);
```
To make the debugger catch all exceptions before any stack unwinding takes place, set a breakpoint on \_\_raise\_exception (see section Breakpoints; watchpoints; and exceptions).
With a conditional breakpoint (see section Break conditions) that depends on the value of id, you can stop your program when a specific exception is raised. You can use multiple conditional breakpoints to stop your program when any of a number of exceptions are raised. | Only below one worked for me with gdb 8.3:
```
break _Unwind_RaiseException
```
"catch throw" or "break \_\_cxx\_throw" didn't work for me. | Run an Application in GDB Until an Exception Occurs | [
"",
"c++",
"debugging",
"gdb",
"polymorphism",
"multicore",
""
] |
Am I correct in assuming that if you have an object that is contained inside a Java Set<> (or as a key in a Map<> for that matter), any fields that are used to determine identity or relation (via `hashCode()`, `equals()`, `compareTo()` etc.) cannot be changed without causing unspecified behavior for operations on the collection? (edit: as alluded to in [this other question](https://stackoverflow.com/questions/214714/mutable-vs-immutable-objects))
(In other words, these fields should either be immutable, or you should require the object to be removed from the collection, then changed, then reinserted.)
The reason I ask is that I was reading the [Hibernate Annotations reference guide](http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e2770) and it has an example where there is a `HashSet<Toy>` but the `Toy` class has fields `name` and `serial` that are mutable and are also used in the `hashCode()` calculation... a red flag went off in my head and I just wanted to make sure I understood the implications of it. | The javadoc for `Set` says
> Note: Great care must be exercised if
> mutable objects are used as set
> elements. The behavior of a set is not
> specified if the value of an object is
> changed in a manner that affects
> equals comparisons while the object is
> an element in the set. A special case
> of this prohibition is that it is not
> permissible for a set to contain
> itself as an element.
This simply means you can use mutable objects in a set, and even change them. You just should make sure the change doesn't impact the way the `Set` finds the items. For `HashSet`, that would require not changing the fields used for calculating `hashCode()`. | That is correct, it can cause some problems locating the map entry. Officially the behavior is undefined, so if you add it to a hashset or as a key in a hashmap, you should not be changing it. | mutable fields for objects in a Java Set | [
"",
"java",
"collections",
"identity",
"mutable",
""
] |
I'm closing in on finishing a Windows Desktop Gadget that downloads plugins from my web server. I'm wondering how I can track the use of these plugins for reporting purposes like seeing which plugins are popular in which countries, how many times a plugin is used per day/month/week and other stuff like that.
Logging this on every user action could cause my server problems as there'd be constant requests. Is it best to keep a local log and upload it to the server on a regular basis or is it possible to use something like Google Analytics or another provider for this sort of thing? | If you are using javascript to create your gadget, it should be possible to include the Google Analytics scripts. You can then call the function [`_trackPageview`](http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55597) whenever your user does something you want to track.
It is also possible to use Google's analytics [without javascript](http://www.vdgraaf.info/google-analytics-without-javascript.html).
The trick is that Google's scripts normally put the image <http://www.google-analytics.com/__utm.gif> into your web pages. Parameters can be passed to the image via the query string. You can find a list of the parameters you can pass to the query string [here](http://www.vdgraaf.info/wp-content/uploads/image-url-explained.txt). What you'd have to do is figure out what the query string should be and have your client make the request to google's image every time the user does something (after setting up your google analytics account, of course). | I would suggest you to use Deskmetrics a [desktop analytics](http://deskmetrics.com) app, very similar to GA. It's awesome. | Tracking user actions - analytics for applications | [
"",
"javascript",
"analytics",
"tracking",
"windows-desktop-gadgets",
""
] |
I want to match the pattern: Starts with 0 or more spaces, followed by "ABC", then followed by anything.
So things like `" ABC " " ABC111111" "ABC"` would be matched.
But things like `" AABC" "SABC"` would not be matched.
I tried:
```
String Pattern = "^\\s*ABC(.*)";
```
But it does not work.
Any ideas? This is in C# by the way. | The `\\` usually puts in a literal backslash so that's probably where your solution is failing. Unless you are doing a replace you don't need the parentheses around the `.*`
Also `\s` matches characters besides the space character `[ \t\n\f\r\x0B]` or space, tab, newline, formfeed, return, and Vertical Tab.
I would suggest:
```
String Pattern = @"^[ ]*ABC.*$";
``` | Try
```
string pattern = @"\s*ABC(.*)"; // Using @ makes it easier to read regex.
```
I verified that this works on regexpl.com | How to construct this in regular expression | [
"",
"c#",
"regex",
""
] |
A few years ago, I did a survey of DbC packages for Java, and I wasn't wholly satisfied with any of them. Unfortunately I didn't keep good notes on my findings, and I assume things have changed. Would anybody care to compare and contrast different DbC packages for Java? | There is a nice overview on
[WikiPedia about Design by Contract](http://en.wikipedia.org/wiki/Design_by_contract), at the end there is a section regarding [languages with third party support libraries](http://en.wikipedia.org/wiki/Design_by_contract#Languages_with_third-party_support), which includes a nice serie of Java libraries. Most of these Java libraries are based on Java Assertions.
In the case you only need [Precondition Checking](http://en.wikipedia.org/wiki/Precondition) there is also a lightweight [Validate Method Arguments](http://www.javapractices.com/topic/TopicAction.do?Id=5) solution, at SourceForge under [Java Argument Validation](http://java-arg-val.sourceforge.net/introduction.html) (Plain Java implementation).
Depending on your problem, maybe the [OVal](http://oval.sourceforge.net/) framework, for field/property Constraints validation is a good choice. This framework lets you place the Constraints in all kind of different forms (Annotations, POJO, XML). Create customer constraints through POJO or scripting languages (JavaScript, Groovy, BeanShell, OGNL, MVEL). And it also party implements [Programming by Contract](http://en.wikipedia.org/wiki/Design_by_contract). | Google has a open source library called [contracts for java](http://google-opensource.blogspot.com/2011/02/contracts-for-java.html).
> Contracts for Java is our new open source tool. Preconditions,
> postconditions, and invariants are added as Java boolean expressions
> inside annotations. By default these do nothing, but enabled via a JVM
> argument, they’re checked at runtime.
>
> ```
> • @Requires, @Ensures, @ThrowEnsures and @Invariant specify contracts as Java boolean expressions
> • Contracts are inherited from both interfaces and classes and can be selectively enabled at runtime
> ```
[contracts for java](http://code.google.com/p/cofoja/). | A good Design-by-Contract library for Java? | [
"",
"java",
"design-by-contract",
""
] |
Can someone explain to me why I cannot use document.getElementById('id').value inside of a function?
I was trying to make a simple multiplication script (im learning JS, its actually kinda fun) and realized quickly how annoying typing that whole line of code just to return a value is, so I wrote a small function:
```
<script type="text/javascript">
function value(elementid){
return document.getElementById(elementid).value
}
</script>
```
However, this does not function and will simply break my whole script's functionality. I wanted to simply type value('id') to return the value of the element.
To fix it, a friend suggested I take out the .value in the function and add it to the end of each line where I call the function instead, like value('id').value.
Why didn't my first way work?
Thanks for the help! | Change your function name to something like '**getValue**'.
This code works on my machine :P
```
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript">
function getvalue(id) {return document.getElementById(id).value;}
</script>
</head>
<body>
<input type="text" id="Text1" />
<input type="button" onclick="alert(getvalue('Text1'))" /> <br />
<input type="text" id="Text2" />
<input type="button" onclick="alert(getvalue('Text2'))" /> <br />
<input type="text" id="Text3" />
<input type="button" onclick="alert(getvalue('Text3'))" /> <br />
</body>
</html>
``` | Are you sure the element that you are getting has a value property and not something else like .text or ...?
If it is an INPUT tag, you can get away with .value and some other HTML controls element also, but for regular DIV, SPAN, etc. I don't think they expose a .value property. Check the tag documentation to see if they support .value. | Returning values inside a JS function | [
"",
"javascript",
"return-value",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.