Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I am facing strange issue on Windows CE:
Running 3 EXEs
1)First exe doing some work every 8 minutes unless exit event is signaled.
2)Second exe doing some work every 5 minutes unless exit event signaled.
3)Third exe while loop is running and in while loop it do some work at random times.
This while loop continues until exit event signaled.
Now this exit event is global event and can be signaled by any process.
The Problem is
When I run First exe it works fine,
Run second exe it works fine,
run third exe it works fine
When I run all exes then only third exe runs and no instructions get executed in first and second.
As soon as third exe gets terminated first and second starts get processing.
It that can be the case that while loop in third exe is taking all CPU cycles?
I havn't tried putting Sleep but I think that can do some tricks.
But OS should give CPU to all processes ...
Any thoughts ???
|
Put the while loop in the third EXE to Sleep each time through the loop and see what happens. Even if it doesn't fix this particular probem, it isn't ever good practice to poll with a while loop, and even using Sleep inside a loop is a poor substitute for a proper timer.
|
(From Memory) Processes in Windows CE run until completion if there are no higher priority processes running, or they run for their time slice (100ms) if there are other processes of equal priority running. I'm not sure if Windows CE gives the process with the active/foreground window a small priority boost (just like desktop Windows), or not.
In your situation the first two processes are starved of processor time so they never run until the third process exits. Some ways to solve this are:
* Make the third process wait/block on some multi-process primitives (mutex, semaphore, etc) and a short timeout. Using WaitForMultipleObjects/WaitForSingleObject etc.
* Make the third process wait using a call to Sleep every time around the processing loop.
* Boost the priority of the other processes so when they need to run they will interrupt the third process and actually run. I would probably make the least often called process have the highest priority of the three processes.
The other thing to check is that the third process does actually complete its tasks in time, and does not peg the CPU trying to do its thing normally.
|
Strange issue running infinite while loop in EXE
|
[
"",
"c++",
"windows-mobile",
""
] |
I know about code-behind files, but what is the best real-world way of Designers that are using DreamWeaver or other Design Tools to work with Visual Studio programmers?
For example, say you have a basic website with user interface forms hitting the database... the database work is definitely done by the developer but how to tie the designed forms with the database coding or client-side logic that may involve events on controls, or other GUI related tie-ins. Are the graphic designers also controlling application flow? There seems to be a large disconnect that needs addressed - especially when it comes time to tweak the design after it's been implemented.
|
Use another approach like [MVC](http://en.wikipedia.org/wiki/Model-view-controller), separate your design from your logic. Like this every member (designer / developer) of the team can focus on what they do best.
MVC implementations: [link](http://www.asp.net/mvc/) / [link](http://www.castleproject.org/monorail/index.html)
|
The best way is to make sure that your designers have some knowledge of what kind of HTML they will be working with.
Every ASP.NET developer is aware of MS-HTML, that lovely nesting of HTML tables, but designers aren't. Designers have their own requirements to meet and they'll do them in the best manner possible. Sadly it's not often good for us.
I am always frustrated when I receive a design from our UI team which shows radio-buttons nicely layed out in a grid using floating div's. Then I have to shatter their dreams that no, I can't generate you that HTML (ok, I can with the use of ControlAdapters, but every time they are different designs!).
Try and have a 90%/ 10% rule, where 90% of the design is done before the ASP.NET starts and the 10% is done once the ASP.NET is completed, and done against ASP.NET generated HTML.
And make sure you're using source control! Code doesn't exist unless it's in source control! And thanks to the latest TFS PowerTools there's a lovely Windows Shell integration component so you don't need to use VS to check in and out now more :D
|
What's the best way to integrate Designers using Dreamweaver with Visual Studio C# developers?
|
[
"",
"c#",
"dreamweaver",
""
] |
I'm making a Java application with an application-logic-thread and a database-access-thread.
Both of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need *both* of them to work).
However, on startup, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method `dbthread.isReady()`).
I wouldn't mind if app thread blocks until the db thread was ready.
`Thread.join()` doesn't look like a solution - the db thread only exits at app shutdown.
`while (!dbthread.isReady()) {}` kind of works, but the empty loop consumes a lot of processor cycles.
Any other ideas? Thanks.
|
I would really recommend that you go through a tutorial like [Sun's Java Concurrency](http://java.sun.com/docs/books/tutorial/essential/concurrency/) before you commence in the magical world of multithreading.
There are also a number of good books out (google for "Concurrent Programming in Java", "Java Concurrency in Practice".
**To get to your answer:**
In your code that must wait for the `dbThread`, you must have something like this:
```
//do some work
synchronized(objectYouNeedToLockOn){
while (!dbThread.isReady()){
objectYouNeedToLockOn.wait();
}
}
//continue with work after dbThread is ready
```
In your `dbThread`'s method, you would need to do something like this:
```
//do db work
synchronized(objectYouNeedToLockOn){
//set ready flag to true (so isReady returns true)
ready = true;
objectYouNeedToLockOn.notifyAll();
}
//end thread run method here
```
The `objectYouNeedToLockOn` I'm using in these examples is preferably the object that you need to manipulate concurrently from each thread, or you could create a separate `Object` for that purpose (I would not recommend making the methods themselves synchronized):
```
private final Object lock = new Object();
//now use lock in your synchronized blocks
```
**To further your understanding:**
There are other (sometimes better) ways to do the above, e.g. with `CountdownLatches`, etc. Since Java 5 there are a lot of nifty concurrency classes in the `java.util.concurrent` package and sub-packages. You really need to find material online to get to know concurrency, or get a good book.
|
Use a [CountDownLatch](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html) with a counter of 1.
```
CountDownLatch latch = new CountDownLatch(1);
```
Now in the app thread do-
```
latch.await();
```
In the db thread, after you are done, do -
```
latch.countDown();
```
|
How to make a Java thread wait for another thread's output?
|
[
"",
"java",
"multithreading",
""
] |
I have a quite big XML output from an application. I need to process it with my program and then feed it back to the original program. There are pieces in this XML which needs to be filled out our replaced. The interesting part looks like this:
```
<sys:customtag sys:sid="1" sys:type="Processtart" />
<sys:tag>value</sys:tag>
here are some other tags
<sys:tag>value</sys.tag>
<sys:customtag sys:sid="1" sys:type="Procesend" />
```
and the document contains several pieces like this.
I need to get all XML pieces inside these tags to be able to make modifications on it. I wrote a regular expression to get those pieces but it does not work:
```
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"output.xml");
Regex regExp = new Regex(@"<sys:customtag(.*?)Processtart(.*?)/>(.*?)<sys:customtag (.*?)Procesend(.*?)/>", RegexOptions.Multiline & RegexOptions.IgnorePatternWhitespace & RegexOptions.CultureInvariant);
MatchCollection matches = regExp.Matches(xmlDoc.InnerXml);
```
If I leave the whole stuff in one line and call this regexp without the multiline option, it does find every occurences. By leaving the file as it is and set the multiline option, it does not work. What is the problem, what should I change? Or is there any easier way to get the XML parts between these tags without regexp?
|
i believe the option to use is `RegexOptions.Singleline` instead of `RegexOptions.Multiline` ([src](http://www.regular-expressions.info/dot.html)). allowing (.) to match newlines should work in your case.
> ...the mode where the dot also matches newlines is called "single-line mode". This is a bit unfortunate, because it is easy to mix up this term with "multi-line mode". Multi-line mode only affects anchors, and single-line mode only affects the dot ... When using the regex classes of the .NET framework, you activate this mode by specifying RegexOptions.Singleline, such as in Regex.Match("string", "regex", RegexOptions.Singleline).
|
The regex char "." never matches a newline, even with `MultiLine` option is set.
instead, you should use `[\s\S]` or other combination with matches anything.
The `MultiLine` option only modifies the behaviour of ^ (begin-of-line instead fo begin-of-string) and $ (end-of-line instead of end-of-string)
BTW: Indeed, regex is not the right way to scan an HTML...
|
Cannot get regular expression work correctly with multiline
|
[
"",
"c#",
"regex",
"multiline",
""
] |
Not wanting to re-invent the wheel or anything, I was wondering if there's a plugin out there a field or form validation plugin that works with Prototype that you can recommend from your own experience and why?
|
I like Ben Keen's Really Simple Validation component.
Features I like:
All the validation rules can be kept within javascript so you're not adding class="required" to your HTML code.
You can display error messages in a javascript alert box or with HTML text.
Adding your own extensions is easy.
<http://www.benjaminkeen.com/software/rsv/>
Note that I've only used the jQuery version, but a Prototype version is also available.
|
I like [wforms](http://www.formassembly.com/wForms/). Example:
```
<input type="text" name="myDate" class="validate-date"/>
```
|
What is the best field validation plugin for Prototype?
|
[
"",
"javascript",
"forms",
"validation",
"prototypejs",
""
] |
If I have the string `.....ZZ..ZZ.....` or `.Z.1.Z.23Z.4.Z55`,
Is there an easy way of shifting all `Z`characters in the string one space right of the current position?
Some additional test strings are:
* `.Z`
* `Z.`
* `ZZ.`
* `.ZZ`
* `Z`
* `ZZ`
* `ZZZ`
I think a few of the higher voted answers to this question (including the currently accepted one) do not work on these tests.
|
Just iterate through the text and swap characters:
```
int main ()
{
char text[] = "...Z.Z.Z...", temp;
int text_len = strlen (text), i;
for (i = text_len - 1; i >= 0; i--)
{
if (text[i] == 'Z')
{
temp = text[i+1];
text[i+1] = text[i];
text[i] = temp;
}
}
printf ("%s\n", text);
return 0;
}
```
Produces:
```
[~]$ gcc zshift.c && ./a.out
....Z.Z.Z..
```
---
There's a lot of discussion in the comments about a possible off-by-1 error in the above code. However, simple testing / stepping through is enough to show that this is not the case.
```
zshift "Z." -> ".Z"
zshift ".Z" -> "."
zshift "Z" -> ""
```
I think the behavior of "dropping" trailing Zs when shifting off the end of the string is sensible. After all, if you shift the bits of an integer, bits that end up outside the bounds of the integer are dropped.
If another behavior is desired -- for example, shifting only within the string -- the change to the algorithm is minimal:
```
temp = text[i+1];
if (temp == 0) continue;
text[i+1] = text[i];
text[i] = temp;
```
|
Building on previously posted code here. Function gets str and strlen, overwrites str. Works also with subsequent Z. Going forward for speed improvement with subsequent Z.
```
void move_z_right (char* str, int strlen) {
for (unsigned int i = 0; i < strlen - 1; ++i)
{
if (str[i] == 'Z')
{
unsigned int j = i+1;
while (str[j] == 'Z' && j < strlen - 1) ++j;
if (j == strlen) break; // we are at the end, done
char tmp = str[j];
str[j] = str[i];
str[i] = tmp;
i = j; // continue after new Z next run
}
}
}
```
Note that John Millikin's solution is nicer to read and also correct.
|
Easy way to shift specific characters in a string in C++?
|
[
"",
"c++",
"string",
"character",
""
] |
I can't figure out how to define the default constructor (when it exists overloads) for a type in StructureMap (version 2.5) by code.
I want to get an instance of a service and the container has to inject a Linq2Sql data context instance into it.
I wrote this in my 'bootstrapper' method :
```
ForRequestedType<MyDataContext>().TheDefault.Is.OfConcreteType<MyDataContext>();
```
When I run my app, I got this error :
> StructureMap Exception Code: 202
> No Default Instance defined for PluginFamily MyNamespace.Data.SqlRepository.MyDataContext, MyNamespace.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
If I comment out all Linq2Sql generated contructors that I don't need, it works fine.
Update : Oh, and I forgot to say that I would not use the `[StructureMap.DefaultConstructor]` attribute.
|
You can specify a constructor with the ConstructedBy(). Please try this:
```
ForRequestedType<MyDataContext>().TheDefault.
Is.ConstructedBy(() => new MyDataContext());
```
This worked for me.
|
I'm assuming you'd also need to set the object lifetime (InstanceScope) if you are using Linq2Sql. I'd suggest using this code because it give you a little more flexibility.
```
ForRequestedType< MyDataContext >()
.CacheBy( InstanceScope.PerRequest )
.TheDefault.Is.OfConcreteType< MyDataContext >()
SelectConstructor< MyDataContext >( () => new MyDataContext());
```
With this code you can also further inject interfaces definitions into the MyDataContext constructor like this
```
SelectConstructor< MyDataContext >( () => new MyDataContext((IDatabaseFactory)null ));
```
Just remember to define the concrete type with StructureMap for your IDatabaseFactory instance.
|
How to define a default constructor by code using StructureMap?
|
[
"",
"c#",
"inversion-of-control",
"structuremap",
""
] |
I may be going about this backwards...
I have a class which is like a document and another class which is like a template. They both inherit from the same base class and I have a method to create a new document from a template (or from another document, the method it is in the base class).
So, if I want to create a new document from a template, I just instantiate the template and call GetNewDoc() on it;
```
Document doc = mytemplate.GetNewDoc();
```
In the Document class I have a blank constructor creating a new, blank document as well as another constructor that takes a document ID so I can load the document from the database. However, I would also like a constructor that takes a Template ID. This way I can do
```
Document doc = New Document(TemplateID)
```
Because the template class already has the ability to return a document, I'd like the constructor to do something like
```
Template temp = new Template(TemplateID);
this = temp.GetNewDoc();
```
Of course, I can't do this as "this" is read-only - and it feels odd anyway. I have a feeling I am being very stupid here so feel free to shout :)
The thing is that the object in question is pretty complex with several collections of child objects and database persistence over multiple tables so i don't want to duplicate too much code. Though, I guess I could just get the new document from the template and then copy the fields/properties across as the collections should follow easily enough - it just seems like duplication.
A more elaborate code example:
```
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// This just creates the object and assigns a value
Instance inst = new Instance();
inst.name = "Manually created";
Console.WriteLine("Direct: {0}", inst.name);
//This creates a new instance directly from a template
MyTemplate def = new MyTemplate();
Instance inst2 = def.GetInstance(100);
Console.WriteLine("Direct from template: {0}", inst2.name);
Instance inst3 = new Instance(101);
Console.WriteLine("Constructor called the template: {0}", inst3.name);
Console.ReadKey();
}
}
public class Instance
{
public string name;
public Instance(int TemplateID)
{
MyTemplate def = new MyTemplate();
//If I uncomment this line the build will fail
//this = def.GetInstance(TemplateID);
}
public Instance()
{
}
}
class MyTemplate
{
public Instance GetInstance(int TemplateID)
{
Instance inst = new Instance();
//Find the template in the DB and get some values
inst.name = String.Format("From template: {0}", TemplateID.ToString());
return inst;
}
}
}
```
|
If you want to be able to do anything other than create a new object just from the code in the constructor, don't use a constructor in the first place.
Do you really need an Instance constructor taking an int? Why not turn it into a static factory method:
```
public static Instance CreateInstance(int id)
{
MyTemplate def = new MyTemplate();
return def.GetInstance(id);
}
```
Static methods have various advantages over constructors - although some disadvantages too. (There's a [separate SO question](https://stackoverflow.com/questions/194496) on that - worth a look.)
|
You cannot recreate 'this' from either the constructor or any other method. You can create another object and copy contents, but I would instead make the factory public. Define a factory class that has three createDocument() methods, one for a blank document, one for a document from the DB and a third one from a template:
```
public class Factory {
public static Document createBlankDocument();
public static Document createDocument( DocumentId id );
public static Document createDocumentFromTemplate( TemplateId id );
}
```
|
Call a factory from Constructor to get a new version of "this"
|
[
"",
"c#",
"constructor",
""
] |
Let's say I have a **Base** class and several **Derived** classes. Is there any way to cast an object to one of the derived classes without the need to write something like this :
```
string typename = typeid(*object).name();
if(typename == "Derived1") {
Derived1 *d1 = static_cast< Derived1*>(object);
}
else if(typename == "Derived2") {
Derived2 *d2 = static_cast < Derived2*>(object);
}
...
else {
...
}
```
|
Don't.
Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented.
Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses.
You left out the most important part of your example. The useful, polymorphic work.
```
string typename = typeid(*object).name();
if(typename == "Derived1") {
Derived1 *d1 = static_cast< Derived1*>(object);
d1->doSomethingUseful();
}
else if(typename == "Derived2") {
Derived2 *d2 = static_cast < Derived2*>(object);
d2->doSomethingUseful();
}
...
else {
...
}
```
If every subclass implements doSomethingUseful, this is all much simpler. And polymorphic.
```
object->doSomethingUseful();
```
|
You can use `dynamic_cast` and test for NULL, but I'd **strongly** consider refactoring the code instead.
If you need subclass-specific handling, [Template Method](http://en.wikipedia.org/wiki/Template_method_pattern) might be helpful, but without knowing what you're trying to achive, it's only a vague guess.
|
C++ casting programmatically : can it be done?
|
[
"",
"c++",
"casting",
""
] |
I'm trying to setup the Entity Framework with SQL Server 2008. I'm using Guids for the keys on my tables. Is there a way to set it up so the keys are automatically generated by the database? I tried setting "RowGuid" to true and also set the column's default value to be "(newid())". Either way the mapped class still needs me to give it a Guid on the C# side. Any ideas?
|
[Not yet](http://blogs.msdn.com/dsimmons/pages/ef-faq-entity-services.aspx#Section_17):
> **17.4.Can I use a server-generated guid as my entity key?**
>
> Unfortunately, in v1 of the EF this is not supported. While it is possible with SQL Server to have a column of type “uniqueidentifier” and to set it’s default value to be “newid()”, with SQL Server 2000 there’s no good way to extract the value that the server generated at the time you do the insert. This can be done on more recent versions of SQL Server, though, so the intent is that we should find a clean way to special case this support in future versions of the EF so it can be supported on those databases that allow it and not on others. For now, the work around is to generate the guid on the client (ideally in the constructor of your object) rather than on the server.
|
Personally, I think that anyone who is using EF would be willing to give up compatibility with SQL Server 2000 to get the features they need. It seems like every halfway non-trivial thing that I need to do in EF is unsupported due to the fact that they have to keep compatibility with SQL Server 2000.
When will it ever end!
|
Entity Framework Guid
|
[
"",
"c#",
"asp.net",
"entity-framework",
""
] |
I am building a PHP application in CodeIgniter. CodeIgniter sends all requests to the main controller: `index.php`. However, I don't like to see `index.php` in the URI. For example, `http://www.example.com/faq/whatever` will route to `http://www.example.com/index.php/faq/whatever`. I need a reliable way for a script to know what it's address is, so it will know what to do with the navigation. I've used `mod_rewrite`, as per CodeIgniter documentation.
The rule is as follows:
```
RewriteEngine on
RewriteCond $1 !^(images|inc|favicon\.ico|index\.php|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
```
Normally, I would just check `php_self`, but in this case it's always `index.php`. I can get it from `REQUEST_URI`, `PATH_INFO`, etc., but I'm trying to decide which will be most reliable. Does anyone know (or know where to find) the real difference between `PHP_SELF`, `PATH_INFO`, `SCRIPT_NAME`, and `REQUEST_URI`? Thanks for your help!
**Note**: I've had to add spaces, as SO sees the underscore, and makes it italic for some reason.
**Updated**: Fixed the spaces.
|
The [PHP documentation](http://ca.php.net/manual/en/reserved.variables.server.php) can tell you the difference:
> *'PHP\_SELF'*
> > The filename of the currently executing script, relative to the document root. For instance, *$\_SERVER['PHP\_SELF']* in a script at the address *http://example.com/test.php/foo.bar* would be */test.php/foo.bar*. The [\_\_FILE\_\_](http://ca.php.net/manual/en/language.constants.predefined.php) constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
> *'SCRIPT\_NAME'*
> > Contains the current script's path. This is useful for pages which need to point to themselves. The [\_\_FILE\_\_](http://ca.php.net/manual/en/language.constants.predefined.php) constant contains the full path and filename of the current (i.e. included) file.
> *'REQUEST\_URI'*
> > The URI which was given in order to access this page; for instance, *'/index.html'*.
> *'PATH\_INFO'*
> > Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URI <http://www.example.com/php/path_info.php/some/stuff?foo=bar>, then *$\_SERVER['PATH\_INFO']* would contain */some/stuff*.
|
Some practical examples of the differences between these variables:
Example 1.
PHP\_SELF is different from SCRIPT\_NAME *only* when requested url is in form:
<http://example.com/test.php/foo/bar>
```
[PHP_SELF] => /test.php/foo/bar
[SCRIPT_NAME] => /test.php
```
(this seems to be the only case when PATH\_INFO contains sensible information [PATH\_INFO] => /foo/bar)
Note: this used to be different in some older PHP versions (<= 5.0 ?).
Example 2.
REQUEST\_URI is different from SCRIPT\_NAME when a non-empty query string is entered:
<http://example.com/test.php?foo=bar>
```
[SCRIPT_NAME] => /test.php
[REQUEST_URI] => /test.php?foo=bar
```
Example 3.
REQUEST\_URI is different from SCRIPT\_NAME when server-side redirecton is in effect (for example mod\_rewrite on apache):
<http://example.com/test.php>
```
[REQUEST_URI] => /test.php
[SCRIPT_NAME] => /test2.php
```
Example 4.
REQUEST\_URI is different from SCRIPT\_NAME when handling HTTP errors with scripts.
Using apache directive ErrorDocument 404 /404error.php
<http://example.com/test.php>
```
[REQUEST_URI] => /test.php
[SCRIPT_NAME] => /404error.php
```
On IIS server using custom error pages
<http://example.com/test.php>
```
[SCRIPT_NAME] => /404error.php
[REQUEST_URI] => /404error.php?404;http://example.com/test.php
```
|
PHP_SELF vs PATH_INFO vs SCRIPT_NAME vs REQUEST_URI
|
[
"",
"http",
"php",
"codeigniter",
""
] |
What is the best way to build a loopback URL for an AJAX call? Say I have a page at
```
http://www.mydomain.com/some/subdir/file.php
```
that I want to load with an AJAX call. In Firefox, using jQuery this works fine:
```
$.post('/some/subdir/file.php', ...);
```
Safari/WebKit tries to interpret this as a location on the local filesystem (so it ends up translating to 'file://some/subdir/file.php'). Not only does this not point to anything useful, it also results in a security error.
Is there a way to accomplish this without hard-coding the domain into the URL? I'd like to make this as domain-independent as possible.
**Update**
I ended up parsing out the base url from location.href and throwing it into an accessible jQuery function like this:
```
/**
* Retrieves the current root URL.
*
* @return string the root URL
*/
$.fn.rootUrl = function() {
var url = location.href;
return url.substring(0, url.indexOf('/', 7));
};
```
|
Wow, that's pretty poor of Safari/WebKit, IMO.
You could observe document.href, count the slashes, and add that many "../" to the beginning of your URL.
|
You could have the server insert its own URL as a javascript variable when it serves up the page, then use that variable as part of your Ajax calls. It would then be both secure and automatic.
|
Loopback jQuery AJAX Request
|
[
"",
"javascript",
"jquery",
"ajax",
""
] |
since JTree & TreeModel don't provide tooltips straight out-of-the-box, what do you think, what would be the best way to have item-specific tooltips for JTree?
Edit: (Answering my own question afterwards.)
@Zarkonnen: Thanks for the getTooltipText idea.
I found out another (maybe still a bit nicer) way with overriding DefaultTreeCellRenderer and thought to share it:
```
public class JTreeWithToolTips {
private static class OwnRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
setToolTipText("foobar" + row);
return super.getTreeCellRendererComponent(tree, value, sel,
expanded, leaf, row, hasFocus);
}
}
public static void main(String[] args) {
JTree tree = new JTree(new Object[] { "foo", "bar", "foobar" });
tree.setCellRenderer(new OwnRenderer());
ToolTipManager.sharedInstance().registerComponent(tree);
JFrame frame = new JFrame();
frame.getContentPane().add(tree);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
```
|
See [getTooltipText](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTree.html#getToolTipText(java.awt.event.MouseEvent)) on JTree. This should allow you to show tooltips depending on what in the tree is being hovered over. (Do read the docs though, you need to register the JTree with the ToolTipManager.)
|
Yeah, you can use `onMouseMoved` and then use a method (I don't remember the name) that tells you in which node you are over. If you get null, obviously then you are not over a node.
|
Best way to implement tooltips for JTree?
|
[
"",
"java",
"swing",
"tooltip",
"jtree",
""
] |
Need a function like:
```
function isGoogleURL(url) { ... }
```
that returns true iff URL belongs to Google. No false positives; no false negatives.
Luckily there's [this](http://www.google.com/supported_domains) as a reference:
> .google.com .google.ad .google.ae .google.com.af .google.com.ag .google.com.ai .google.am .google.it.ao .google.com.ar .google.as .google.at .google.com.au .google.az .google.ba .google.com.bd .google.be .google.bg .google.com.bh .google.bi .google.com.bn .google.com.bo .google.com.br .google.bs .google.co.bw .google.com.by .google.com.bz .google.ca .google.cd .google.cg .google.ch .google.ci .google.co.ck .google.cl .google.cn .google.com.co .google.co.cr .google.com.cu .google.cz .google.de .google.dj .google.dk .google.dm .google.com.do .google.dz .google.com.ec .google.ee .google.com.eg .google.es .google.com.et .google.fi .google.com.fj .google.fm .google.fr .google.ge .google.gg .google.com.gh .google.com.gi .google.gl .google.gm .google.gp .google.gr .google.com.gt .google.gy .google.com.hk .google.hn .google.hr .google.ht .google.hu .google.co.id .google.ie .google.co.il .google.im .google.co.in .google.is .google.it .google.je .google.com.jm .google.jo .google.co.jp .google.co.ke .google.com.kh .google.ki .google.kg .google.co.kr .google.kz .google.la .google.li .google.lk .google.co.ls .google.lt .google.lu .google.lv .google.com.ly .google.co.ma .google.md .google.mn .google.ms .google.com.mt .google.mu .google.mv .google.mw .google.com.mx .google.com.my .google.co.mz .google.com.na .google.com.nf .google.com.ng .google.com.ni .google.nl .google.no .google.com.np .google.nr .google.nu .google.co.nz .google.com.om .google.com.pa .google.com.pe .google.com.ph .google.com.pk .google.pl .google.pn .google.com.pr .google.pt .google.com.py .google.com.qa .google.ro .google.ru .google.rw .google.com.sa .google.com.sb .google.sc .google.se .google.com.sg .google.sh .google.si .google.sk .google.sn .google.sm .google.st .google.com.sv .google.co.th .google.com.tj .google.tk .google.tl .google.tm .google.to .google.com.tr .google.tt .google.com.tw .google.co.tz .google.com.ua .google.co.ug .google.co.uk .google.com.uy .google.co.uz .google.com.vc .google.co.ve .google.vg .google.co.vi .google.com.vn .google.vu .google.ws .google.rs .google.co.za .google.co.zm .google.co.zw .google.cat
Any ideas how to do this elegantly?
**Some Clarifications:**
* I need this for a greasemonkey script I wrote that currently only works for google.com (and should work for all other TLDs as well). [Here](http://userscripts.org/scripts/show/6415) is the script (it modifies Google Reader to work on wide screens better).
* It should work on URLs that belong to the above domains (not blogger.com, etc.).
|
Here is an updated version of Prestaul's answer which solves the two problems I mentioned in the comment there.
```
var GOOGLE_DOMAINS = ([
'.google.com',
'.google.ad',
'.google.ae',
'.google.com.af',
'.google.com.ag',
'.google.com.ai',
'.google.am',
'.google.it.ao',
'.google.com.ar',
'.google.as',
'.google.at',
'.google.com.au',
'.google.az',
'.google.ba',
'.google.com.bd'
]).join('\n');
function isGoogleUrl(url) {
// get the 2nd level domain from the url
var domain = /^https?:\/\/[^\///]*(google\.[^\/\\]+)\//i.exec(url);
if(!domain) return false;
domain = '.'+domain[1];
// create a regex to check to see if the domain is supported
var re = new RegExp('^' + domain.replace(/\./g, '\\.') + '$', 'mi');
return re.test(GOOGLE_DOMAINS);
}
alert(isGoogleUrl('http://www.google.ba/the/page.html')); // true
alert(isGoogleUrl('http://some_mal_site.com/http://www.google.ba/')); // false
alert(isGoogleUrl('https://google.com.au/')); // true
alert(isGoogleUrl('http://www.google.com.some_mal_site.com/')); // false
alert(isGoogleUrl('http://yahoo.com/')); // false
```
|
All the domains end in either "google.xx", "google.co.xx", or "google.com.xx" except "google.it.ao" and "google.com", so if you just look at the domain, this regular expression should work for most cases (it's not perfect, but it accepts all the listed domains, and rejects most other valid domains that happen to include "google"):
```
/^(\w+\.)*google\.((com\.|co\.|it\.)?([a-z]{2})|com)$/i
```
As a function you could do something like this:
```
function isGoogleUrl(url) {
url = url.replace(/^https?:\/\//i, ''); // Strip "http://" from the beginning
url = url.replace(/\/.*/, ''); // Strip off the path
return /^(\w+\.)*google\.((com\.|co\.|it\.)?([a-z]{2})|com)$/i.test(url);
}
```
You could simplify it if you use `window.location.hostname`:
```
function isGoogleUrl() {
return /^(\w+\.)*google\.((com\.|co\.|it\.)?([a-z]{2})|com)$/i.test(window.location.hostname);
}
```
The only way this should allow a false positive is if there is a "google.(some other TLD)". For example, "google.tv", is not on the list (it redirects to google.com), but it would pass.
**Edit:** Like Wimmel pointed out, it also accepts invalid domains like "google.com.fr" which are not listed. It will basically accept any "google.whatever" domain name.
|
JavaScript function to match only Google URLs
|
[
"",
"javascript",
"greasemonkey",
""
] |
I'm still trying to get my head around using Java's generics. I have no problems at all with using typed collections, but much of the rest of it just seems to escape me.
Right now I'm trying to use the JUnit "PrivateAccessor", which requires a Class[] argument with a list of all the argument types for the private method being called. In Java 1.4, I'd define that as
```
Class[] args = new Class[] { Collection.class, ArrayList.class };
```
but the actual code is defined to now take the arguments
```
myMethod(Collection<MyClass1> first, ArrayList<MyClass2> second)
```
I tried to change the definition of args to be
```
Class<? extends Object>[] args = new Class<? extends Object>[]
{ Collection<MyClass1>.class, ArrayList<MyClass2>.class };
```
But Eclipse puts a red marker on the closing >s, and says it's expecting "void" at that point. Can I do this using generics, or shouldn't I bother?
|
The first problem you have is that you should be using
```
Class<?>[] args = new Class[]
```
instead of
```
Class<? extends Object>[] args = new Class<? extends Object>[]
```
[This](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104) explains why.
Your second problem is that you should be using
```
{ Collection.class, ArrayList.class };
```
instead of
```
{ Collection<MyClass1>.class, ArrayList<MyClass2>.class };
```
This is because XXX.class is evaluated at runtime, after [type erasure](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ005) has been performed, so specifying the type argument is useless, hence forbidden.
I highly recommend the [FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) from which I've linked the two explanations above for an "earthly" take on Java generics that will clarify most questions.
|
This is the correct syntax:
```
Class<?>[] paramTypes = new Class[]{ Collection.class, ArrayList.class };
```
|
Convert Class[] to generics?
|
[
"",
"java",
"generics",
""
] |
Our team is using a SecureRandom to generate a list of key pairs (the SecureRandom is passed to a KeyPairGenerator). We cannot agree on which of the following two options to use:
1. Create a new instance every time we need to generate a key pair
2. Initialize a static instance and use it for all key pairs
Which approach is generally better and *why*?
ADDED: My gut feeling is that the second option is more secure. But my only argument is a theoretical attack based on the assumption that the pseudorandomness is derived from the current timestamp: someone may see the creation time of the key pair, guess timestamps in the surrounding time interval, compute the possible pseudorandom sequences, and obtain the key material.
ADDED: My assumption about determinism based on a timestamp was wrong. That's the difference between Random and SecureRandom. So, it looks like the answer is: in terms of security it doesn't really matter.
|
Unlike the `java.util.Random` class, the `java.security.SecureRandom` class must produce non-deterministic output on each call.
What that means is, in case of `java.util.Random`, if you were to recreate an instance with the same seed each time you needed a new random number, you would essentially get the *same* result every time. However, `SecureRandom` is guaranteed to NOT do that - so, creating a single instance or creating a new one each time does *not* affect the randomness of the random bytes it generates.
So, from just normal good coding practices view point, why create too many instances when one will do?
|
For [SecureRandom](http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/security/SecureRandom.html) you would want to consider occasionally reseeding ([using system entropy in most cases](https://bugs.java.com/bugdatabase/view_bug?bug_id=6202721)) via a call like so:
```
mySecureRandom.setSeed(mySecureRandom.generateSeed(someInt));
```
so as to give a potential attacker something less than unlimited time to discover your key.
There's some great writeups about this consideration at the [Justice League](http://www.cigital.com/justiceleague/2009/08/14/proper-use-of-javas-securerandom/) blog.
|
SecureRandom: init once or every time it is needed?
|
[
"",
"java",
"security",
"random",
"cryptography",
""
] |
I'm writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.
Up till now I'd been planning on using the JDBC-ODBC bridge and just connecting to the databases using different connection strings.
**I'm told this is not very efficient.**
1. Is there a pattern or best practice for connecting to multiple database systems? Or for selecting which driver to use?
2. Should I have it configurable? but include all three drivers or build three separate clients?
I'm not doing anything complex just pumping (inserting) data into the database from an event stream.
|
I would suggest that you make it configurable and include the three drivers. You can use a pattern like this: Create a super class (lets call it DAO) that provides the functionality of connecting to the database. This could be abstract.
Create a concrete sub class for each type of database that you wish to connect to. So you may end up with MySQLDAO, MSSQLDAO, and OracleDAO. each one will load the respective driver and use its respective connection string.
Create another class (lets call it DAOFactory) with a method getDAO(DB) that will create an instance of the DAO depending on the value of DB.
So for instance(in Pseudocode):
```
if(DB.equals("MySQL")){
DAO = new MySQLDAO();
}
return DAO;
```
So any code that needs to connect to the database will call the DAOFactory and ask for a DAO instance. You may store the DB value in an external file (like a properties file) so that you do not have to modify code to change the type of database.
this way your code does not need to know which type of database it is connecting to, and if you decide to support a fourth type of database later you will have to add one more class and modify the DAOFactory, not the rest of your code.
|
If you're careful (and you test), you can do this with straight JDBC and just vary the driver class and connection information. You definitely want to stay away from the JDBC-ODBC bridge as it's generally slow and unreliable. The bridge is more likely to behave differently across dbs than JDBC is.
I think the DAO path is overkill if your requirements are as simple as listed.
If you're doing a lot of inserts, you might want to investigate prepared statements and batched updates as they are far more efficient. This might end up being less portable - hard to say without testing.
|
Pattern for connecting to different databases using JDBC
|
[
"",
"java",
"jdbc",
""
] |
As I use the web, I regularly get runtime errors (usually javascript) being reported via popups. This can make for a really unsatisfying user experience on many otherwise excellent websites and also makes me wonder what functionality I am not getting access to.
Why is this such a common issue? Is this down to a lack of testing or is it browser compatibility issues? What can be done to minimise this kind of issue?
Incidently I don't have the 'Display a notification about every script error' checked.
|
Its a number of issues.
1. Many web page creators copy and paste JavaScript code from the web. They are not programmers and may not appreciate the nuances of the language.
2. Lack of good testing frameworks (At least I don't know any). For Java we have JUNIT and .NET NUNIT etc. Its difficult to automate JavaScript testing at this time.
3. Poor IDE support. Until recently most IDE's did a poor job supporting JavaScript. Now I see more support but still not the kind that you get for the core languages.
|
I put it down to a lack of testing.
|
Web page runtime errors
|
[
"",
"javascript",
"internet-explorer-7",
"user-experience",
"runtime-error",
""
] |
How can I make a variable (object) available for the whole lifetime of the webservice?
Static variable seem to work but is there an other way to do it?
|
Static variables exist for the lifetime of the App Domain that contains them. In the case of a web service, this is usually the ASP.Net Worker Process. What that means is that when IIS decides to cycle the worker process, your static variable will be gone. This may be what you want, in which case it is probably a good choice. (Putting asside discussions of whether or not static variables are proper in a given context).
Within the scope of a web service you also have access to the [HttpApplicationState](http://msdn.microsoft.com/en-us/library/system.web.httpapplicationstate.aspx) via the Application property (this would be an asmx service...not sure if WCF is the same or not), so this could also be a good choice for stashing something needed for the lifetime of a service.
|
A singleton utilizing HttpApplicationState should work a treat
|
Web service variable shared for the lifetime of the webservice?
|
[
"",
"c#",
"web-services",
".net-2.0",
"c#-2.0",
""
] |
I'm attempting to register an anonymous function when a user clicks a cell in an HTML table. Here's some of the raw, unadulterated code:
```
document.getElementById(
"course"+displayed_year_index+occurrences_indices[displayed_year_index]).onclick =
eval("function() {PrintReceipt("+result.years[result_year_index].rul_code+");};");
```
Note the use of `eval`, since this sits in a loop and the anonymous function is different each time round.
Suffice to say, this works absolutely fine in Firefox 2. But, Firefox 3 throws a 'Syntax Error', pointing inside the brackets after the word 'function'.
Does anybody have any smart ideas on how I can fix this?
---
Just to make it crystal clear what I'm attempting to do, here's a much simplified example:
```
for (index=0; index<4; index++) {
document.getElementById("div"+index).onclick =
eval("function () {Foo(index);};");
}
```
In other words, I wish to trigger the same function with a different parameter value for each `div`.
|
IMHO closures should not be used in this case and there is no need to create a new function for each onlick (uses much more memory than necessary) and eval is the wrong answer.
You know that the element you are getting with getElementById is an object and that you can assign values to it?
```
for ( /* your definition */ ) {
var e = document.getElementById(
"course"+displayed_year_index+occurrences_indices[displayed_year_index]
);
e.rul_code = result.years[result_year_index].rul_code;
e.onclick = PrintReceipt;
}
```
But you should define the PrintReceipt first:
```
function PrintReceipt() {
//This function is called as an onclick handler, and "this" is a reference to the element that was clicked.
if (this.rul_code === undefined) { return; }
//Do what you want with this.rul_code
alert (this.rul_code);
}
```
|
Have you tried something like this?
```
document.getElementById('course' + displayed_year_index + occurences_indices[displayed_year_index]) =
function (nr)
{
return function () { PrintReceipt(nr) }
} (result.years[result_year_index].rul_code);
```
Can you please post the loop to help us find the problem instead of making us guess what you're trying to do?
|
Firefox Javascript Events Anonymous Function
|
[
"",
"javascript",
"firefox",
"event-handling",
"closures",
"anonymous-function",
""
] |
We have a simple project where we read data from a socket and we want to populate a table with the coming data, but we can't find a way to add rows to a yet created `JTable` object, we can only find how to add rows at creation time of the table.
Is it possible to add rows dynamically to a `JTable`, or there is a better alternative object to deal with this way of showing data?
**EDIT**: Thanks a lot for your answers.
All three of them look very promising, but I have to choose only one and I think the best is Guillaume's.
|
You should create a custom [`TableModel`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/table/TableModel.html). A `JTable` doesn't actually store the rows, it always delegates that to a `TableModel`. To help you implementing it, you should make use of [`AbstractTableModel`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/table/AbstractTableModel.html). Don't forget to call [`fireTableRowsInserted()`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/table/AbstractTableModel.html#fireTableRowsInserted(int,%20int)) every time you add rows. For better performances if you add a lot of rows, try to batch the updates and add many rows at a time.
|
If you use the default table model for a JTable then you can add rows with following code
```
if ( dest+1 < table.getRowCount()-1 )
( (DefaultTableModel) table.getModel() ).insertRow(dest+1, getValuesForNewRow());
else
( (DefaultTableModel) table.getModel() ).addRow(getValuesForNewRow());
```
|
Adding rows to a JTable
|
[
"",
"java",
"swing",
""
] |
This is one is for any of you Doctrine users out there. I have a PHP CLI daemon process that checks a table every n seconds to find entries that haven't been processed. It's basically a FIFO. Anyways, I always exceed the memory allocated to PHP becuase Doctrine does not free it's resources. To combat this problem it provides free for the query object. I can't seem to make it work though. Here's the code:
```
22 print "You are using " . (memory_get_usage() / 1024). "\n";
23 $query = Doctrine_Query::create()
24 ->from('SubmissionQueue s')
25 ->where('s.time_acted_on IS NULL')
26 ->orderby('s.time_queued')
27 ->limit(1)
28 ->execute();
29 print $query[0]->time_queued . "\n";
30 $query->free();
```
Any ideas what I am doing wrong?
EDIT: I am using 1.0.3
EDIT: I have tried all of the below suggestions. I was very hopeful for `unset()` as I had it in there before I found `free()`.
Here is more of the code to possibly aid in any help. Before you question the opening and closing of the connection it will be daemon process that spawns children and from I have experienced the connection has to be unique.
```
1 <?php
2
3 require_once('/usr/local/lib/php/Doctrine/lib/Doctrine.php');
4
5 spl_autoload_register(array('Doctrine', 'autoload'));
6
7 $manager = Doctrine_Manager::getInstance();
8 $manager->setAttribute('model_loading','conservative');
9 Doctrine::loadModels('lib/model/master');
10
11 while(1){
12 print "You are using " . intval(memory_get_usage() / 1024) . "\n";
13 $manager->connection('********************************************','master');
14 $query = Doctrine_Query::create()
15 ->from('SubmissionQueue s')
16 ->where('s.time_acted_on IS NULL')
17 ->orderby('s.time_queued')
18 ->limit(1)
19 ->execute();
20 print "[" . $query[0]->time_queued . "]\n";
21 $query->free();
22 unset($query);
23 $query = null;
24 $manager->closeConnection(Doctrine_Manager::getInstance()->getConnection('master'));
25 sleep(5);
26 }
27
```
Some sample output:
```
You are using 14949KB
[2008-11-17 13:59:00]
You are using 14978KB
[2008-11-17 13:59:00]
You are using 15007KB
[2008-11-17 13:59:00]
You are using 15035KB
[2008-11-17 13:59:00]
You are using 15064KB
[2008-11-17 13:59:00]
You are using 15093KB
[2008-11-17 13:59:00]
You are using 15121KB
[2008-11-17 13:59:00]
You are using 15150KB
[2008-11-17 13:59:00]
You are using 15179KB
[2008-11-17 13:59:00]
You are using 15207KB
[2008-11-17 13:59:00]
You are using 15236KB
[2008-11-17 13:59:00]
You are using 15265KB
[2008-11-17 13:59:00]
You are using 15293KB
[2008-11-17 13:59:00]
You are using 15322KB
```
|
The problem is, that `free()` does not remove the Doctrine objects from memory but just eliminates the circular references on those objects, making it possible for the garbage collector to cleanup those objects. Please see [23.6 Free Objects](http://www.doctrine-project.org/documentation/manual/1_0?chapter=improving-performance#free-objects) in the [Doctrine manual](http://www.doctrine-project.org/documentation/manual/1_0):
> As of version 5.2.5, PHP is not able
> to garbage collect object graphs that
> have circular references, e.g. Parent
> has a reference to Child which has a
> reference to Parent. Since many
> doctrine model objects have such
> relations, PHP will not free their
> memory even when the objects go out of
> scope.
>
> For most PHP applications, this
> problem is of little consequence,
> since PHP scripts tend to be
> short-lived. Longer-lived scripts,
> e.g. bulk data importers and
> exporters, can run out of memory
> unless you manually break the circular
> reference chains. Doctrine provides a
> free() function on Doctrine\_Record,
> Doctrine\_Collection, and
> Doctrine\_Query which eliminates the
> circular references on those objects,
> freeing them up for garbage
> collection.
The solution should be to `unset()` the `$query` object after using `free()`:
```
$query = Doctrine_Query::create()
->from('SubmissionQueue s')
->where('s.time_acted_on IS NULL')
->orderby('s.time_queued')
->limit(1);
$query->execute();
print $query[0]->time_queued . "\n";
$query->free();
unset($query); // perhaps $query = null; will also work
```
|
Doctrine\_Query also has a free() method, at the moment you are just calling free() on your Doctrine\_Collection, eg, try:
```
$query = Doctrine_Query::create()
->from('SubmissionQueue s')
->where('s.time_acted_on IS NULL')
->orderby('s.time_queued')
->limit(1);
$results = $query->execute();
print $results[0]->time_queued . "\n";
$results->free();
$query->free();
```
|
Why is PHP Doctine's free() not working?
|
[
"",
"php",
"memory",
"orm",
"doctrine",
""
] |
I am using JQuery to post with AJAX to another ASP page. Do I need this ASP page to return a full html page. Or can I just have it send back a value ( I just need a status ) . Here is my function.
```
$.ajax({
url: "X.asp",
cache: false,
type: "POST",
data: queryString,
success: function(html){
$('#x_'+Num).append(html);
}
});
```
|
If it's just a simple value you need, I'd simple use Json (JQuery has a dedicated method for that : [$.getJSON()](http://docs.jquery.com/Ajax/jQuery.getJSON)).
So no, you don't need your ASP page to return a full html page, just the value in simple JSON notation.
|
You can return anything you want (even single character), but remember to change content type of your page X.asp to ContentType="text/plain" if you don't want to return HTML.
|
AJAX - Do I need to return a full HTML document on the server side?
|
[
"",
"javascript",
"jquery",
"ajax",
"asp-classic",
""
] |
In C#, the questions of what types to create, what members they should have, and what namespaces should hold them, are questions of OO design. They are not the questions I'm interested in here.
Instead, I want to ask how you store these in disk artifacts. Here are some example rules:
* Put all of an assembly's types in a single source file. One friend who did this said "files are an archiac code organization tool; today I use classview and Collapse to Definitions to browse my code".
* Put all your code in one assembly. Makes deployment & versioning simpler.
* Directory structure reflects namespace structure.
* Each namespace gets its own assembly.
* Each type goes in its own assembly. (Listed as an extreme example.)
* Each type gets its own source file.
* Each member gets its own file; each type gets its own directory. (Listed as an extreme example.)
|
Whatever you do, just PLEASE do it consistently. I don't believe there is any one single answer (though there are a few wrong ones). But just make sure you stay true to your form as this will be the key for your successor(s) to find things easily.
|
Currently I do:
* One assembly for production code + unit tests
* directory structure mimics namespaces
* one type per file
* nested types get their own file, using `partial` types. That is:
```
// ------ C.cs
public partial class C : IFoo
{
// ...
}
// ------ C.Nested.cs
partial class C
{
public class Nested
{
// ...
}
}
```
|
How do you organize C# code in to files?
|
[
"",
"c#",
"code-organization",
""
] |
I'm looking for Java code that can be used to generate sound at runtime - NOT playback of existing sound files.
For example, what's the best code for generating a sawtooth waveform at 440 Hz for a duration of 2 milliseconds? **Source code appreciated!**
I remember my Commodore 128 had a simple Sound command that took as parameters voice, frequency, waveform, and duration to define a sound. That worked great in a lot of simple cases (quick and dirty games, experiments with sound, etc).
I am looking specifically for sound-effect like sounds, not music or MIDI (which the [JFugue](http://www.jfugue.org) library covers quite well).
|
You can easily generate sampled sound data in Java and play it back without using native code. If you're talking MIDI things may get tricky, but I've not dabbled in that area.
To generate sampled sound data, you have to thing of the process backwards. We're going to act like the A-to-D and sample a continuous sound function over time. Your sound card does the same thing for audio through a mic or line in.
First, choose a sample rate (NOT the freq of the tone we're generating). Let's go with 44100 hz since that's likely the sound card playback rate (thus no sample rate conversion, that's not easy unless hardware does it).
```
// in hz, number of samples in one second
sampleRate = 44100
// this is the time BETWEEN Samples
samplePeriod = 1.0 / sampleRate
// 2ms
duration = 0.002;
durationInSamples = Math.ceil(duration * sampleRate);
time = 0;
for(int i = 0; i < durationInSamples; i++)
{
// sample a sine wave at 440 hertz at each time tick
// substitute a function that generates a sawtooth as a function of time / freq
// rawOutput[i] = function_of_time(other_relevant_info, time);
rawOutput[i] = Math.sin(2 * Math.PI * 440 * time);
time += samplePeriod;
}
// now you can playback the rawOutput
// streaming this may be trickier
```
|
Here is a sample that might help. This generates sin waves:
```
package notegenerator;
import java.io.IOException;
/**
* Tone generator and player.
*
* @author Cesar Vezga vcesar@yahoo.com
*/
public class Main {
public static void main(String[] args) throws IOException {
Player player = new Player();
player.play(BeachRock.getTack1(),BeachRock.getTack2());
}
}
```
---
```
package notegenerator;
public class BeachRock {
// GUITAR
static String gs1 = "T332 A4-E4 F#5-C6 E5-A5 T166 G5 A5 F#5 A5 F5 A5 E5-A5 E3 G3 G#3 ";
static String gs2 = "A3 A3 A3 G3 E3 E3 G3 G#3 ";
static String gs3 = "A3 A3 A3 G3 E3 A3 C4 C#4 ";
static String gs4 = gs2 + gs2 + gs2 + gs3;
static String gs5 = "D4 D4 D4 C4 A3 A3 C4 D#4 ";
static String gs6 = "D4 D4 D4 C4 A3 E3 G3 G#3 ";
static String gs7 = gs4 + gs5 + gs6 + gs2 + "A3 A3 A3 G3 E3 B3 D3 D#3 ";
static String gs8 = "E4 E4 E4 D4 B3 B3 E4 B3 " + gs6 + gs2;
static String gs9 = "x E3-B3 E3-B3 E3-B3 E3-B3 E3 G3 G#3 ";
static String gs10 = gs7 + gs8 + gs9;
static String gs11 = "A3-D4 X*7 X*16 X*5 E3 G3 G#3 ";
static String guitar = gs1 + gs10 + gs11 + gs10 + gs11 + "A3 A3 A3";
// DRUMS
static String ds1 = "D2 X D3 D3 X*2 D3 X ";
static String ds2 = "D2 X D3 D3 X D3 D3 D3 ";
static String ds3 = "D2 D3 D3 D3 D3 T83 D3 D3 T166 D3 ";
static String ds4 = ds1 + ds1 + ds1 + ds2;
static String ds5 = ds1 + ds1 + ds1 + ds3;
static String ds6 = "D2*2 D3 D3 X*2 D3*2 ";
static String ds7 = "D2*2 D3 D3 X D3 D3 D3 ";
static String ds8 = ds6 + ds6 + ds6 + ds7;
static String drums = "V25 T166 X*16 " + ds4 + ds4 + ds5 + ds8 + ds4 + ds4
+ ds5 + ds8;
public static String getTack1(){
return guitar;
}
public static String getTack2(){
return drums;
}
}
```
---
```
package notegenerator;
import java.util.HashMap;
/**
*
* Physics of Music - Notes
*
* Frequencies for equal-tempered scale
* This table created using A4 = 440 Hz
* Speed of sound = 345 m/s = 1130 ft/s = 770 miles/hr
*
* ("Middle C" is C4 )
*
* http://www.phy.mtu.edu/~suits/notefreqs.html
*
* @author Cesar Vezga <vcesar@yahoo.com>
*
*/
public class Notes {
private static final Object[] notes = {
"C0",16.35,
"C#0/Db0",17.32,
"D0",18.35,
"D#0/Eb0",19.45,
"E0",20.6,
"F0",21.83,
"F#0/Gb0",23.12,
"G0",24.5,
"G#0/Ab0",25.96,
"A0",27.5,
"A#0/Bb0",29.14,
"B0",30.87,
"C1",32.7,
"C#1/Db1",34.65,
"D1",36.71,
"D#1/Eb1",38.89,
"E1",41.2,
"F1",43.65,
"F#1/Gb1",46.25,
"G1",49.00,
"G#1/Ab1",51.91,
"A1",55.00,
"A#1/Bb1",58.27,
"B1",61.74,
"C2",65.41,
"C#2/Db2",69.3,
"D2",73.42,
"D#2/Eb2",77.78,
"E2",82.41,
"F2",87.31,
"F#2/Gb2",92.5,
"G2",98.00,
"G#2/Ab2",103.83,
"A2",110.00,
"A#2/Bb2",116.54,
"B2",123.47,
"C3",130.81,
"C#3/Db3",138.59,
"D3",146.83,
"D#3/Eb3",155.56,
"E3",164.81,
"F3",174.61,
"F#3/Gb3",185.00,
"G3",196.00,
"G#3/Ab3",207.65,
"A3",220.00,
"A#3/Bb3",233.08,
"B3",246.94,
"C4",261.63, // Middle C
"C#4/Db4",277.18,
"D4",293.66,
"D#4/Eb4",311.13,
"E4",329.63,
"F4",349.23,
"F#4/Gb4",369.99,
"G4",392.00,
"G#4/Ab4",415.3,
"A4",440.00,
"A#4/Bb4",466.16,
"B4",493.88,
"C5",523.25,
"C#5/Db5",554.37,
"D5",587.33,
"D#5/Eb5",622.25,
"E5",659.26,
"F5",698.46,
"F#5/Gb5",739.99,
"G5",783.99,
"G#5/Ab5",830.61,
"A5",880.00,
"A#5/Bb5",932.33,
"B5",987.77,
"C6",1046.5,
"C#6/Db6",1108.73,
"D6",1174.66,
"D#6/Eb6",1244.51,
"E6",1318.51,
"F6",1396.91,
"F#6/Gb6",1479.98,
"G6",1567.98,
"G#6/Ab6",1661.22,
"A6",1760.00,
"A#6/Bb6",1864.66,
"B6",1975.53,
"C7",2093.00,
"C#7/Db7",2217.46,
"D7",2349.32,
"D#7/Eb7",2489.02,
"E7",2637.02,
"F7",2793.83,
"F#7/Gb7",2959.96,
"G7",3135.96,
"G#7/Ab7",3322.44,
"A7",3520.00,
"A#7/Bb7",3729.31,
"B7",3951.07,
"C8",4186.01,
"C#8/Db8",4434.92,
"D8",4698.64,
"D#8/Eb8",4978.03
};
private HashMap<String,Double> noteMap;
public Notes(){
noteMap = new HashMap<String,Double>();
for(int i=0; i<notes.length; i=i+2){
String name = (String)notes[i];
double freq = (Double)notes[i+1];
String[] keys = name.split("/");
for(String key : keys){
noteMap.put(key, freq);
System.out.println(key);
}
}
}
public byte[] getCordData(String keys, double duration){
int N = (int) (8000 * duration/1000);
byte[] a = new byte[N+1];
String[] key = keys.split(" ");
int count=0;
for(String k : key){
double freq = getFrequency(k);
byte[] tone = tone(freq,duration);
if(count==0){
a = tone;
}else{
a = addWaves(a,tone);
}
count++;
}
return a;
}
public byte[] addWaves(byte[] a, byte[] b){
int len = Math.max(a.length, b.length);
byte[] c = new byte[len];
for(int i=0; i<c.length; i++){
byte aa = ( i < a.length ? a[i] : 0);
byte bb = ( i < b.length ? b[i] : 0);
c[i] = (byte) (( aa + bb ) / 2);
}
return c;
}
public double getFrequency(String key){
Double f = noteMap.get(key);
if(f==null){
System.out.println("Key not found. "+key);
f = 0D;
}
return f;
}
public byte[] tone(String key, double duration) {
double freq = getFrequency(key);
return tone(freq,duration);
}
public byte[] tone(double hz, double duration) {
int N = (int) (8000 * duration/1000);
byte[] a = new byte[N+1];
for (int i = 0; i <= N; i++) {
a[i] = (byte) ( Math.sin(2 * Math.PI * i * hz / 8000) * 127 );
}
return a;
}
}
```
---
```
package notegenerator;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class Player {
private SourceDataLine line = null;
private Notes notes = new Notes();
private long time = 250;
private double volumen = 1;
public void play(String keys) {
byte[] data = parse(keys);
start();
line.write(data, 0, data.length);
stop();
}
public void play(String... track) {
byte[] data2 = parseAll(track);
if (data2 != null) {
start();
line.write(data2, 0, data2.length);
stop();
}
}
private byte[] parseAll(String... track) {
byte[] data2 = null;
for (String t : track) {
byte[] data1 = parse(t);
if (data2 == null) {
data2 = data1;
} else {
data2 = notes.addWaves(data1, data2);
}
}
return data2;
}
private byte[] parse(String song) {
time = 250;
volumen = 1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String[] key = song.split(" ");
byte[] data = null;
for (String k : key) {
int mult = 1;
if (k.indexOf("*") > -1) {
String keyAux = k.split("\\*")[0];
mult = Integer.parseInt(k.split("\\*")[1]);
k = keyAux;
} else if (k.startsWith("T")) {
time = Long.parseLong(k.substring(1));
continue;
} else if (k.startsWith("V")) {
volumen = Double.parseDouble(k.substring(1)) / 100;
if(volumen>1) volumen = 1;
if(volumen<0) volumen = 0;
continue;
}
if (k.indexOf("-") > -1) {
k = k.replaceAll("-", " ").trim();
data = notes.getCordData(k, time * mult);
} else {
data = notes.tone(k, time * mult);
}
volumen(data);
try {
baos.write(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return baos.toByteArray();
}
private void volumen(byte[] data) {
for(int i=0; i<data.length; i++){
data[i] = (byte) (data[i] * volumen);
}
}
private void stop() {
line.drain();
line.stop();
}
private void start() {
AudioFormat format = new AudioFormat(8000.0F, 8, 1, true, false);
SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class,
format); // format
// is
// an
// AudioFormat
// object
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Format not supported");
System.exit(1);
}
// Obtain and open the line.
try {
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
} catch (LineUnavailableException ex) {
ex.printStackTrace();
}
// Assume that the TargetDataLine, line, has already
// been obtained and opened.
int numBytesRead;
line.start();
}
public void save(String track, String fname) throws IOException {
byte[] data = parse(track);
FileOutputStream fos = new FileOutputStream(fname);
fos.write(data);
fos.flush();
fos.close();
}
}
```
|
How to generate sound effects in Java?
|
[
"",
"java",
"audio",
""
] |
I'd like to serialize some LINQ generated objects and store them in a table as a binary field (Never you mind why). I'd like to be able to write some code that looks something like this:
```
SerialTestDataContext db = new SerialTestDataContext();
relation_table row = db.relation_tables.First();
MemoryStream memStream = new MemoryStream();
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(memStream, row);
Console.WriteLine("Serilized successfully");
TestTable tt = new testTable();
tt.data = new System.Data.Linq.Binary(memStream.ToArray());
db.testTables.InsertOnSubmit(tt);
db.SubmitChanges();
Console.WriteLine("Inserted successfully");
```
Currently that fails even though I've marked the generated classes as [Serializable] because one of the LINQ inherited classes is not. Is it even possible to do this?
|
With linq-to-sql (from tags), then yes: you can mark the dmbl as serializable, which uses the [DataContract]/[DataMember] approach. You do this by setting the "Serialization Mode" to "Unidirectional" in the designer, or you can do it in the dbml itself:
```
<Database ... Serialization="Unidirectional">...
```
You can then use DataContractSerializer or NetDataContractSerializer to write this (as xml or binary respectively). If you need something portable (i.e. not MS/.NET specific), then [protobuf-net](http://code.google.com/p/protobuf-net/) will serialize data-contracts using the "protocol buffers" spec.
|
Following Marc Gravell's advice I wrote the following two blocks of code which worked beautifully:
```
relation_table row = db.relation_tables.First();
MemoryStream memStream = new MemoryStream();
NetDataContractSerializer ndcs = new NetDataContractSerializer();
ndcs.Serialize(memStream, row);
byte[] stuff = memStream.toArray();
memStream = new MemoryStream(stuff);
row = ndcs.Deserialize(memStream);
db.relation_tables.Attach(row);
Console.WriteLine(row.data_table1.somedata + ": " + row.more_data);
```
The Attach() call fills in the foreign key dependencies for me and associates the item with the data context.
|
Is it possible to Serialize a LINQ object?
|
[
"",
"c#",
"linq",
"linq-to-sql",
"serialization",
""
] |
My function is pretty much a standard search function... I've included it below.
In the function I have 1 line of code responsible for weeding out Repart NTFS points.
```
if (attributes.ToString().IndexOf("ReparsePoint") == -1)
```
The problem is now I am getting an error
`Access to the path 'c:\System Volume Information' is denied.`
I debugged the code and the only attributes at run time for this directory are :
```
System.IO.FileAttributes.Hidden
| System.IO.FileAttributes.System
| System.IO.FileAttributes.Directory
```
I'm executing this code on a windows 2008 server machine, any ideas what I can do to cure this failing?
```
public void DirSearch(string sDir)
{
foreach (string d in Directory.GetDirectories(sDir))
{
DirectoryInfo dInfo = new DirectoryInfo(d);
FileAttributes attributes = dInfo.Attributes;
if (attributes.ToString().IndexOf("ReparsePoint") == -1)
{
foreach (string f in Directory.GetFiles(d, searchString))
{
//lstFilesFound.Items.Add(f);
ListViewItem lvi;
ListViewItem.ListViewSubItem lvsi;
lvi = new ListViewItem();
lvi.Text = f;
lvi.ImageIndex = 1;
lvi.Tag = "tag";
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = "sub bugger";
lvi.SubItems.Add(lvsi);
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = d;//"C:\\Users\\Administrator\\Downloads\\MediaMonkey.GOLD.EDITION.v.3.0.2.1134.[Darkside].[Demonoid].[Grim.Reaper]";
lvi.SubItems.Add(lvsi);
listView1.Items.Add(lvi);
}
DirSearch(d);
}
}
}
```
|
Nobody has permission to access System Volume Information except the SYSTEM account. So either change the permissions on the directory. Or much, much better catch the exception and go on.
|
I'm not sure what the answer to the question is, but *please* change your attribute check to use proper bitwise operations!
```
if (attributes.ToString().IndexOf("ReparsePoint") == -1)
```
... is much more correctly written as ...
```
if ((attributes & FileAttributes.ReparsePoint) == 0)
```
|
What is the best way to check for reparse point in .net (c#)?
|
[
"",
"c#",
".net",
"ntfs",
"reparsepoint",
""
] |
I have a unit test where I have statically defined a quite large byte array (over 8000 bytes) as the byte data of a file I don't want to read every time I run my unit test.
```
private static final byte[] FILE_DATA = new byte[] {
12,-2,123,................
}
```
This compiles fine within Eclipse, but when compiling via Ant script I get the following error:
```
[javac] C:\workspace\CCUnitTest\src\UnitTest.java:72: code too large
[javac] private static final byte[] FILE_DATA = new byte[] {
[javac] ^
```
Any ideas why and how I can avoid this?
---
**Answer**: Shimi's answer did the trick. I moved the byte array out to a separate class and it compiled fine. Thanks!
|
Methods in Java are restricted to 64k in the byte code. Static initializations are done in a single method (see [link](http://www.mail-archive.com/help-bison@gnu.org/msg01990.html))
You may try to load the array data from a file.
|
You can load the byte array from a file in you `@BeforeClass` static method. This will make sure it's loaded only once for all your unit tests.
|
javac error "code too large"?
|
[
"",
"java",
"compiler-construction",
"ant",
""
] |
Is there a **JavaScript** equivalent of **Java**'s `class.getName()`?
|
> Is there a JavaScript equivalent of Java's `class.getName()`?
***No***.
**ES2015 Update**: [the name of `class Foo {}` is `Foo.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Function_names_in_classes). The name of `thing`'s class, regardless of `thing`'s type, is `thing.constructor.name`. Builtin constructors in an ES2015 environment have the correct `name` property; for instance `(2).constructor.name` is `"Number"`.
---
But here are various hacks that all fall down in one way or another:
Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)
```
Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
```
Now, all of your objects will have the function, `getName()`, that will return the name of the constructor as a string. I have tested this in `FF3` and `IE7`, I can't speak for other implementations.
If you don't want to do that, here is a discussion on the various ways of determining types in JavaScript...
---
I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome...
## Using the `constructor` property...
Every `object` has a value for its `constructor` property, but depending on how that `object` was constructed as well as what you want to do with that value, it may or may not be useful.
Generally speaking, you can use the `constructor` property to test the type of the object like so:
```
var myArray = [1,2,3];
(myArray.constructor == Array); // true
```
So, that works well enough for most needs. That said...
### Caveats
**Will not work *AT ALL* in many cases**
This pattern, though broken, is quite common:
```
function Thingy() {
}
Thingy.prototype = {
method1: function() {
},
method2: function() {
}
};
```
`Objects` constructed via `new Thingy` will have a `constructor` property that points to `Object`, not `Thingy`. So we fall right at the outset; you simply cannot trust `constructor` in a codebase that you don't control.
**Multiple Inheritance**
An example where it isn't as obvious is using multiple inheritance:
```
function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
```
Things now don't work as you might expect them to:
```
var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true
```
So, you might get unexpected results if the `object` your testing has a different `object` set as its `prototype`. There are ways around this outside the scope of this discussion.
There are other uses for the `constructor` property, some of them interesting, others not so much; for now we will not delve into those uses since it isn't relevant to this discussion.
**Will not work cross-frame and cross-window**
Using `.constructor` for type checking will break when you want to check the type of objects coming from different `window` objects, say that of an iframe or a popup window. This is because there's a different version of each core type `constructor` in each `window', i.e.
```
iframe.contentWindow.Array === Array // false
```
---
## Using the `instanceof` operator...
The `instanceof` operator is a clean way of testing `object` type as well, but has its own potential issues, just like the `constructor` property.
```
var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true
```
But `instanceof` fails to work for literal values (because literals are not `Objects`)
```
3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false
```
The literals need to be wrapped in an `Object` in order for `instanceof` to work, for example
```
new Number(3) instanceof Number // true
```
The `.constructor` check works fine for literals because the `.` method invocation implicitly wraps the literals in their respective object type
```
3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
```
Why two dots for the 3? Because Javascript interprets the first dot as a decimal point ;)
### Will not work cross-frame and cross-window
`instanceof` also will not work across different windows, for the same reason as the `constructor` property check.
---
## Using the `name` property of the `constructor` property...
### Does not work *AT ALL* in many cases
Again, see above; it's quite common for `constructor` to be utterly and completely wrong and useless.
### Does NOT work in <IE9
Using `myObjectInstance.constructor.name` will give you a string containing the name of the `constructor` function used, but is subject to the caveats about the `constructor` property that were mentioned earlier.
For IE9 and above, you can [monkey-patch in support](http://matt.scharley.me/2012/03/monkey-patch-name-ie.html):
```
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1] : "";
},
set: function(value) {}
});
}
```
**Updated version** from the article in question. This was added 3 months after the article was published, this is the recommended version to use by the article's author Matthew Scharley. This change was inspired by [comments pointing out potential pitfalls](http://matt.scharley.me/2012/03/monkey-patch-name-ie.html#comment-551654096) in the previous code.
```
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1].trim() : "";
},
set: function(value) {}
});
}
```
---
## Using Object.prototype.toString
It turns out, as [this post details](http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/), you can use `Object.prototype.toString` - the low level and generic implementation of `toString` - to get the type for all built-in types
```
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
```
One could write a short helper function such as
```
function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}
```
to remove the cruft and get at just the type name
```
type('abc') // String
```
However, it will return `Object` for all user-defined types.
---
## Caveats for all...
All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:
```
// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == "Foo"); // true
// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // false
(obj.constructor.name == "Foo"); // false
// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object); // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == ""); // true
// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == ""); // true
// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object); // true
(obj.constructor == Object); // true
(obj.constructor.name == "Object"); // true
```
While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don't assume anything, if you don't understand exactly what you are after, you may end up with code breaking where you don't expect it to because of a lack of grokking the subtleties.
### NOTE:
Discussion of the `typeof` operator may appear to be a glaring omission, but it really isn't useful in helping to identify whether an `object` is a given type, since it is very simplistic. Understanding where `typeof` is useful is important, but I don't currently feel that it is terribly relevant to this discussion. My mind is open to change though. :)
|
Jason Bunting's answer gave me enough of a clue to find what I needed:
```
<<Object instance>>.constructor.name
```
So, for example, in the following piece of code:
```
function MyObject() {}
var myInstance = new MyObject();
```
`myInstance.constructor.name` would return `"MyObject"`.
|
Get the name of an object's type
|
[
"",
"javascript",
""
] |
Lets say you need to attach some JavaScript functionality to an ASP.NET User Control of which there might be multiple instances on any given page. Because JavaScript has shared global state, what techniques can you use to keep the client state and behavior for each instance of a control separate?
|
Well, the main thing you can do is make sure your JavaScript functions are abstract enough that they are not coupled to specific instances of HTML controls - have them accept parameters that allow you to pass various instances of objects in.
The JavaScript that does whatever magic you need to be done should only exist once in your page regardless of how many instances of a user control you have on a given page, thus your functions need to be ignorant of that fact.
Without more information about what you are trying to do, there is little more I can offer in the way of help; it would depend on your circumstance.
---
EDIT: One way I have dealt with particular aspects of this problem is to create a static property on the user control (thus it is the same variable across multiple instances) that tracks the client-side IDs of the various user control elements (the user control adds the client IDs to this list in the ***control's*** OnLoad event); then, in the ***page's*** OnPreRender event (IIRC), render those out in a JavaScript variable that my code knows to look for on the client and operate on. I don't know if that makes sense, but it might help someone...
|
```
function <%=this.ClientID %>_myButton_onclick()
{
DoSomething();
}
```
and
```
<button id="myButton" onclick="<%=this.ClientID %>_myButton_onclick()">
```
Notice in this case the control is a regular HTML control.
|
How do you handle attaching JavaScript to UserControls in ASP.NET and keep multiple instance isolated?
|
[
"",
"asp.net",
"javascript",
""
] |
Is there a way to execute a query(containing built in DB function) using PreparedStatement?
Example:
insert into foo (location) values (pointfromtext('12.56666 13.67777',4130))
Here pointfromtext is a built in function.
|
By what I've seen, the first parameter on pointfromtext function is a string, and the second a number. So, try the following:
```
PreparedStatement preparedStatement = getConnection().prepareStatement("insert into map_address (location) values(pointfromtext('POINT(' || ? || ' ' || ? || ')',4130))");
preparedStatement.setString(1, "12.56565665");
preparedStatement.setString(2, "12.57565757");
preparedStatement.executeUpdate();
```
|
Sure, that should work.
If not, what is your database system, and can you run the exact same command from the SQL command line?
|
JDBC built in functions and prepared statements
|
[
"",
"java",
"jdbc",
""
] |
I have 2 tables event + event\_artist
## event
```
eventId | eventName
-------------------
1 , gig1
2, gig2
```
## event\_artist
```
eventId, artistName
-------------------
1, Led Zip
1, The Beatles
```
ie Led Zep and the Beatles are both playing @ Gig1
I need to create the SQl to bind to a gridview ( you necessarily need to know about gridviews to answers this )
The results that i want would look like this
eventId = 1, EventName = Gig1. ArtistLineup = Led Zep, The beatles
So i need to create an alias ArtistLineup that would list all the artist. Via an inner select i think.
Any thoughts on what this would look like.
|
Saw this in SQL Server Magazine- not great, and the total list will have an upper length limit, but:
```
drop table event
go
drop table event_artist
go
create table event (eventid int, eventname varchar(255))
go
create table event_artist (eventid int, artistname varchar(255))
go
insert into event values (1, 'gig1')
go
insert into event values (2, 'gig2')
go
insert into event_artist values (1, 'Led Zip')
go
insert into event_artist values (1, 'The Beatles')
go
drop function Event_Display
go
create function Event_Display (@EventID int) returns varchar(2000) as
begin
declare @artistList varchar(2000)
set @artistList=''
select @artistList=@artistList + ', ' + isnull(artistname,'')
from event_artist
where eventid=@EventID
return substring(@artistList,3,2000) --eliminate initial comma
end
go
select event.eventid, event.eventname, dbo.Event_Display(event.eventid) from event
```
```
1 gig1 Led Zip, The Beatles
2 gig2
```
|
SQL Server doesn't have anything built in to concatenate values in one statement like that. You could build the strings, but it has to be done one at a time.
However, you can get around this by building your own [custom aggregate function](https://stackoverflow.com/questions/43940/custom-aggregate-functions-in-ms-sql-server) (requires messy games with ActiveX objects in SQL Server 2000)
|
Inner select on one to many
|
[
"",
".net",
"sql",
"sql-server",
"t-sql",
""
] |
I've got a section of code on a b2evo PHP site that does the following:
```
$content = preg_replace_callback(
'/[\x80-\xff]/',
create_function( '$j', 'return "&#".ord($j[0]).";";' ),
$content);
```
What does this section of code do? My guess is that it strips out ascii characters between 128 and 256, but I can't be sure.
Also, as it stands, every time this bit of code is called from within a page, PHP allocates and then does not free upto 2K of memory. If the function is called 1000+ times on a page (this can happen), then the page uses an extra 2MB of memory.
This is causing problems with my web application. Why am I losing memory, and how do I rewrite this so I don't get a memory leak?
|
Not really stripping, it replaces high-Ascii characters by their entities.
See [preg\_replace\_callback](http://fr.php.net/manual/en/function.preg-replace-callback.php "PHP: preg_replace_callback - Manual").
create\_function is used to make an anonymous function, but you can use a plain function instead:
```
$content = 'Çà ! Nœm dé fîçhïèr tôrdù, @ pöür têstër... ? ~ Œ[€]';
$content = preg_replace_callback('/[\x80-\xff]/', 'CB_CharToEntity', $content);
echo $econtent . '<br>';
echo htmlspecialchars($content) . '<br>';
echo htmlentities($content) . '<br>';
echo htmlentities($content, ENT_NOQUOTES, 'cp1252') . '<br>';
function CB_CharToEntity($matches)
{
return '&#' . ord($matches[0]) . ';';
}
```
[EDIT] Found a cleaner, probably faster way to do the job! ^\_^ Just use htmlentities with options fitting your needs.
|
It's `create_function` that's leaking your memory - just use a normal function instead and you'll be fine.
The function itself is replacing the characters with numeric HTML entities (`&#xxx;`)
|
what does this preg_replace_callback do in PHP? and how do I stop it leaking memory?
|
[
"",
"php",
"preg-replace-callback",
"create-function",
""
] |
Is their a way to use a non-member non-friend function on an object using the same "dot" notation as member functions?
Can I pull a (any) member out of a class, and have users use it in the same way they always have?
Longer Explanation:
[Scott Meyers](http://www.ddj.com/cpp/184401197), Herb Sutter, et all, argue that non-member non-friend functions are a part of an object's interface, and can improve encapsulation. I agree with them.
However, after recently reading this article: <http://www.gotw.ca/gotw/084.htm> I find myself questioning the syntax implications.
In that article, Herb proposes having a single `insert`, `erase`, and `replace` member, and several non-member non-friend functions of the same name.
Does this mean, as I think it does, that Herb thinks some functions should be used with the dot notation, and others as a global function?
```
std::string s("foobar");
s.insert( ... ); /* One like this */
insert( s , ...); /* Others like this */
```
Edit:
Thanks everyone for your very useful answers, however, I think the point of my question has been overlooked.
I specifically did not mention the specific case of operators, and how they retain the "natural" notation. Nor that you should wrap everything in a namespace. These things are written in the article I linked to.
**The question itself was:**
In the article, Herb suggests that one insert() method be a member, while the rest are non-member non-friend functions.
This implies that to use one form of insert() you have to use dot notation, while for the others, you do not.
**Is it just me, or does that sound crazy?**
I have a hunch that perhaps you can use a single syntax. (Im thinking how Boost::function can take a \*this parameter for mem\_fun).
|
You *can* use a single syntax, but perhaps not the one you like. Instead of placing one insert() inside your class scope, you make it a friend of your class. Now you can write
```
mystring s;
insert(s, "hello");
insert(s, other_s.begin(), other_s.end());
insert(s, 10, '.');
```
For any non-virtual, public method, it's equivalent to define it as a non-member friend function. If mixed dot/no-dot syntax bothers you then by all means make those methods friend functions instead. There's no difference.
In the [future](http://www.research.att.com/~bs/multimethods.pdf) we will also be able to write polymorphic functions like this, so maybe this is the C++ way, rather than artificially trying to force free functions into the dot syntax.
|
Yes, it means that part of the interface of an object is composed of non member functions.
And you're right about the fact it involves the use of the following notation, for an object of class T:
```
void T::doSomething(int value) ; // method
void doSomething(T & t, int value) ; // non-member non-friend function
```
If you want the doSomething function/method return void, and have an int parameter called "value".
But two things are worth mentioning.
The first is that the functions part of the interface of a class should be in the same namespace. This is yet another reason (if another reason was needed) to use namespaces, if only to "put together" an object and the functions that are part of its interface.
The good part is that it promotes good encapsulation. But bad part is that it uses a function-like notation I, personally, dislike a lot.
The second is that operators are not subject to this limitation. For example, the += operator for a class T can be written two ways:
```
T & operator += (T & lhs, const T & rhs) ;
{
// do something like lhs.value += rhs.value
return lhs ;
}
T & T::operator += (const T & rhs) ;
{
// do something like this->value += rhs.value
return *this ;
}
```
But both notations are used as:
```
void doSomething(T & a, T & b)
{
a += b ;
}
```
which is, from an aesthetic viewpoint, quite better than the function-like notation.
Now, it would be a very cool syntactic sugar to be able to write a function from the same interface, and still be able to call it through the "." notation, like in C#, as mentioned by michalmocny.
## Edit: Some examples
Let's say I want, for whatever reason, to create two "Integer-like" classes.
The first will be IntegerMethod:
```
class IntegerMethod
{
public :
IntegerMethod(const int p_iValue) : m_iValue(p_iValue) {}
int getValue() const { return this->m_iValue ; }
void setValue(const int p_iValue) { this->m_iValue = p_iValue ; }
IntegerMethod & operator += (const IntegerMethod & rhs)
{
this->m_iValue += rhs.getValue() ;
return *this ;
}
IntegerMethod operator + (const IntegerMethod & rhs) const
{
return IntegerMethod (this->m_iValue + rhs.getValue()) ;
}
std::string toString() const
{
std::stringstream oStr ;
oStr << this->m_iValue ;
return oStr.str() ;
}
private :
int m_iValue ;
} ;
```
This class has 6 methods which can acess its internals.
The second is IntegerFunction:
```
class IntegerFunction
{
public :
IntegerFunction(const int p_iValue) : m_iValue(p_iValue) {}
int getValue() const { return this->m_iValue ; }
void setValue(const int p_iValue) { this->m_iValue = p_iValue ; }
private :
int m_iValue ;
} ;
IntegerFunction & operator += (IntegerFunction & lhs, const IntegerFunction & rhs)
{
lhs.setValue(lhs.getValue() + rhs.getValue()) ;
return lhs ;
}
IntegerFunction operator + (const IntegerFunction & lhs, const IntegerFunction & rhs)
{
return IntegerFunction(lhs.getValue() + rhs.getValue()) ;
}
std::string toString(const IntegerFunction & p_oInteger)
{
std::stringstream oStr ;
oStr << p_oInteger.getValue() ;
return oStr.str() ;
}
```
It has only 3 methods, and such, reduces the quantity of code that can access its internals. It has 3 non-member non-friend functions.
The two classes can be used as:
```
void doSomething()
{
{
IntegerMethod iMethod(25) ;
iMethod += 35 ;
std::cout << "iMethod : " << iMethod.toString() << std::endl ;
IntegerMethod result(0), lhs(10), rhs(20) ;
result = lhs + 20 ;
// result = 10 + rhs ; // WON'T COMPILE
result = 10 + 20 ;
result = lhs + rhs ;
}
{
IntegerFunction iFunction(125) ;
iFunction += 135 ;
std::cout << "iFunction : " << toString(iFunction) << std::endl ;
IntegerFunction result(0), lhs(10), rhs(20) ;
result = lhs + 20 ;
result = 10 + rhs ;
result = 10 + 20 ;
result = lhs + rhs ;
}
}
```
When we compare the operator use ("+" and "+="), we see that making an operator a member or a non-member has no difference in its apparent use. Still, there are two differences:
1. the member has access to all its internals. The non-member must use public member methods
2. From some binary operators, like +, \*, it is interesting to have type promotion, because in one case (i.e., the lhs promotion, as seen above), it won't work for a member method.
Now, if we compare the non-operator use ("toString"), we see the member non-operator use is more "natural" for Java-like developers than the non-member function. Despite this unfamiliarity, for C++ it is important to accept that, despite its syntax, the non-member version is better from a OOP viewpoint because it does not have access to the class internals.
As a bonus: If you want to add an operator (resp. a non-operator function) to an object which has none (for example, the GUID structure of <windows.h>), then you can, without needing to modify the structure itself. For the operator, the syntax will be natural, and for the non-operator, well...
*Disclaimer: Of course these class are dumb: the set/getValue are almost direct access to its internals. But replace the Integer by a String, as proposed by Herb Sutter in [Monoliths "Unstrung"](http://www.gotw.ca/gotw/084.htm), and you'll see a more real-like case.*
|
non-member non-friend function syntax
|
[
"",
"c++",
"class-design",
""
] |
There's this program, pdftotext, that can convert a pdf file to a text file. To use it directly on the linux console:
```
pdftotext file.pdf
```
That will generate a file.txt on the same directory as the pdf file. I was looking for a way to do it from inside a php program, and after some googling I ended with two commands that should work for me: *system()* and *exec()*. So I made a php file with this:
```
<?php
system('pdftotext file.pdf');
?>
```
But when I run this code, it doesn't work. No txt file is created.
So I tried to create a test file with another command:
```
<?php
system('touch test.txt');
?>
```
This worked fine. I've also used exec() and the results were the same. Why doesn't it work?
**EDIT:** following RoBorg advice, i added the 2>&1 argument to the command, so:
```
<?php
system('pdftotext file.pdf 2>&1');
?>
```
it printed a error message:
> pdftotext: error while loading shared
> libraries: libfontconfig.so.1: cannot
> open shared object file: No such file
> or directory
Seems like something is missing on the server.
|
It's probably a permissions issue, but try this instead:
```
<?php
system('pdftotext file.pdf 2>&1');
?>
```
The `2>&1` redirects stderr to stdout, so any error messages will be printed. It should be pretty easy to fix from then on.
|
install this. it solved the problem for me.
<http://www.ssforge.com/ssforge-standard/onlinehelp/help/faq/libstdc.html>
now, pdftotext works great.
|
Converting pdf files to txt files with php
|
[
"",
"php",
"pdf",
"text-files",
""
] |
I'm passing a reference of a form to a class. Within this class I believed I could use `formRef->Controls["controlName"]` to access properties on the control.
This works for a few labels, but on a button I receive a "Object reference not set to an instance of an object." when I try to change the Text property.
Help or explanation appreciated...
|
I did this, and it's working. Could possibly be safer as I can check if the control actually exists...
```
array<Control^>^ id = myForm->Controls->Find("myButton", true);
id[0]->Text = "new text";
```
I think the reason it breaks is that the button is on another panel. I didn't think of that when I posted. The new solution will search all children too, so it's an improvement.
|
That suggests that the control with the given name wasn't found.
Don't forget that the name of the control isn't necessarily the same as its ID in the designer. Check the actual name against the one you're using to look it up with.
|
Modifying controls with Form.Controls
|
[
"",
".net",
"c++",
"winforms",
""
] |
This is my code:
```
internal enum WindowsMessagesFlags {
WM_EXITSIZEMOVE = 0x00000232,
WM_DISPLAYCHANGE = 0x0000007e,
WM_MOVING = 0x00000216,
}
protected override void WndProc(ref Message m) {
switch(m.Msg) {
case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:
FixWindowSnapping();
break;
case (int)WindowsMessagesFlags.WM_EXITSIZEMOVE:
SaveWindowProperties();
break;
case (int)WindowsMessagesFlags.WM_MOVING:
KeepProperLocation(ref m);
break;
}
}
```
Is there anyway to prevent the casting?
|
Sort of - cast m.Msg instead:
```
protected override void WndProc(ref Message m) {
switch((WindowsMessagesFlags) m.Msg) {
case WindowsMessagesFlags.WM_DISPLAYCHANGE:
FixWindowSnapping();
break;
case WindowsMessagesFlags.WM_EXITSIZEMOVE:
SaveWindowProperties();
break;
case WindowsMessagesFlags.WM_MOVING:
KeepProperLocation(ref m);
break;
}
}
```
The reason you need the cast at all is because in C# enums aren't just numbers - they're numbers associated with the type. This prevents you from doing (without casting):
```
HttpStatusCode status = someWindowsMessageFlag;
```
This is clearly a good thing :) When you need to, however, you can always go "via" the underlying type (int in this case).
|
What is Message.Msg defined as?
I'm betting it is Int32.
I'm also betting WindowsMessagesFlags is your type, but Message is from the framework.
Which means you're using your own enum with a framework-built object, and of course they are going to have some incompatibilities regarding types.
An enum is a strong type, not just *a number*, it is a *number with a name in a context*. This name, context, number, part isn't directly compatible with just numbers, and that's why you need to cast.
|
Why do I have to cast enums to int in C#?
|
[
"",
"c#",
"enums",
"casting",
"int",
""
] |
I'm writing a function that fishes out the src from the first image tag it finds in an html file. Following the instructions in [this thread](https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php) on here, I got something that seemed to be working:
```
preg_match_all('#<img[^>]*>#i', $content, $match);
foreach ($match as $value) {
$img = $value[0];
}
$stuff = simplexml_load_string($img);
$stuff = $stuff[src];
return $stuff;
```
But after a few minutes of using the function, it started returning errors like this:
> warning: simplexml\_load\_string() [0function.simplexml-load-string0]: Entity: line 1: parser error : Premature end of data in tag img line 1 in path/to/script on line 42.
and
> warning: simplexml\_load\_string() [0function.simplexml-load-string0]: tp://feeds.feedburner.com/~f/ChicagobusinesscomBreakingNews?i=KiStN" border="0"> in path/to/script on line 42.
I'm kind of new to PHP but it seems like my regex is chopping up the HTML incorrectly. How can I make it more "airtight"?
|
These two lines of PHP code should give you a list of all the values of the src attribute in all img tags in an HTML file:
```
preg_match_all('/<img\s+[^<>]*src=["\']?([^"\'<>\s]+)["\']?/i', $content, $result, PREG_PATTERN_ORDER);
$result = $result[1];
```
To keep the regex simple, I'm not allowing file names to have spaces in them. If you want to allow this, you need to use separate alternatives for quoted attribute values (which can have spaces), and unquoted attribute values (which can't have spaces).
|
Most likely because the "XML" being picked up by the regex isn't proper XML for whatever reason. I would probably go for a more complicated regex that would pull out the src attribute, instead of using SimpleXML to get the src. This REGEX might be close to what you need.
```
<img[^>]*src\s*=\s*['|"]?([^>]*?)['|"]?[^>]*>
```
You could also use a real HTML Parsing library, but I'm not sure which options exist in PHP.
|
Why is this regex returning errors when I use it to fish img src's from HTML?
|
[
"",
"php",
"html",
"xml",
"regex",
"simplexml",
""
] |
I can understand wanting to avoid having to use a cursor due to the overhead and inconvenience, but it looks like there's some serious cursor-phobia-mania going on where people are going to great lengths to avoid having to use one.
For example, one question asked how to do something obviously trivial with a cursor and the accepted answer proposed using a common table expression (CTE) recursive query with a recursive custom function, even though this limits the number of rows that could be processed to 32 (due to recursive function call limit in sql server). This strikes me as a terrible solution for system longevity, not to mention a tremendous effort just to avoid using a simple cursor.
What is the reason for this level of insane hatred? Has some 'noted authority' issued a fatwa against cursors? Does some unspeakable evil lurk in the heart of cursors that corrupts the morals of children or something?
Wiki question, more interested in the answer than the rep.
Related Info:
[SQL Server Fast Forward Cursors](https://stackoverflow.com/questions/37029/sql-server-fast-forward-cursors)
EDIT: let me be more precise: I understand that **cursors should not be used instead of normal relational operations**; that is a no-brainer. What I don't understand is people going waaaaay out of their way to avoid cursors like they have cooties or something, even when a cursor is a simpler and/or more efficient solution. It's the irrational hatred that baffles me, not the obvious technical efficiencies.
|
The "overhead" with cursors is merely part of the API. Cursors are how parts of the RDBMS work under the hood. Often `CREATE TABLE` and `INSERT` have `SELECT` statements, and the implementation is the obvious internal cursor implementation.
Using higher-level "set-based operators" bundles the cursor results into a single result set, meaning less API back-and-forth.
Cursors predate modern languages that provide first-class collections. Old C, COBOL, Fortran, etc., had to process rows one at a time because there was no notion of "collection" that could be used widely. Java, C#, Python, etc., have first-class list structures to contain result sets.
**The Slow Issue**
In some circles, the relational joins are a mystery, and folks will write nested cursors rather than a simple join. I've seen truly epic nested loop operations written out as lots and lots of cursors. Defeating an RDBMS optimization. And running really slowly.
Simple SQL rewrites to replace nested cursor loops with joins and a single, flat cursor loop can make programs run in 100th the time. [They thought I was the god of optimization. All I did was replace nested loops with joins. Still used cursors.]
This confusion often leads to an indictment of cursors. However, it isn't the cursor, it's the misuse of the cursor that's the problem.
**The Size Issue**
For really epic result sets (i.e., dumping a table to a file), cursors are essential. The set-based operations can't materialize really large result sets as a single collection in memory.
**Alternatives**
I try to use an ORM layer as much as possible. But that has two purposes. First, the cursors are managed by the ORM component. Second, the SQL is separated from the application into a configuration file. It's not that the cursors are bad. It's that coding all those opens, closes and fetches is not value-add programming.
|
Cursors make people overly apply a procedural mindset to a set-based environment.
And they are **SLOW**!!!
From [SQLTeam](http://www.sqlteam.com/article/cursors-an-overview):
> Please note that cursors are the
> SLOWEST way to access data inside SQL
> Server. The should only be used when
> you truly need to access one row at a
> time. The only reason I can think of
> for that is to call a stored procedure
> on each row. In the [Cursor
> Performance article](http://www.sqlteam.com/article/cursor-performance) I discovered
> that cursors are **over thirty times
> slower than set based alternatives**.
|
Why do people hate SQL cursors so much?
|
[
"",
"sql",
"database-cursor",
""
] |
## Setup
I have a website that draws RSS feeds and displays them on the page. Currently, I use percentages on the divs that contain each feed, so that multiples can appear next to each other.
However, I only have two next to each other, and if the window resizes, there can be some ugly empty space on the screen.
## Desire
What I'd like to be able to do, but have not figured out a way yet, is to put all the feeds linearly into the page, and have:
* a 'pre-built' multicolumn view where the feeds would "balance" themselves into the columns
which leads me to:
* the number of columns change depending on how wide the screen is currently\
This is akin to how word processing applications handle columnar layouts.
## Question
I presume that I will need to implement some form of AJAXy happiness, but currently know very little about Javascript.
Is there a way to do this with ***just*** CSS/HTML/PHP?
If not, how should I go about solving this?
### final solution:
(based on [@warpr](https://stackoverflow.com/a/272183/4418)'s and [@joh6nn](https://stackoverflow.com/a/272229/4418)'s answers)
```
#rss
{min-width: 10em;
max-width: 25em;
min-height: 15em;
max-height: 25em;
font-size: .97em;
float: left;
}
```
|
You probably cannot get what you want with just CSS/HTML, but you can get somewhat close.
A trick I used for a photo album is this:
1. Make sure each feed has a fixed width, I would recommend something like '20em';
2. Make sure each feed has the same height.
3. Float everything left.
Because each div has the same dimensions, when they're floated left they will form a grid with exactly the number of columns that will fit in your browser.
Unless you actually fix the height of the divs and use CSS to clip the content, you will need javascript for step 2, what I did was:
1. Iterate over each feed div, finding the tallest div.
2. Iterate over each div again, changing the height to match the div found in the first step.
This is fairly easy to implement, but is obviously not optimal. I look forward to reading any better solutions posted here :)
|
you might be able to do this with lists; i've never tried it, so i'm not sure.
if you make list items display:inline, the list becomes horizontal instead of vertical. from there, if you stuff the list into a containing element and fiddle with the padding and margins, you may be able to get the list to line-warp, like text: again, i've never tried that, so i don't know.
if this technique works, i'd be very interested to hear about it.
|
Dynamic resizing / repositioning of divs for multi-column viewing
|
[
"",
"php",
"html",
"css",
"styling",
"dynamic-css",
""
] |
I need to spawn a process in Java (under Linux exclusively) that will continue to run after the JVM has exited. How can I do this?
Basically the Java app should spawn an updater which stops the Java app, updates files and then starts it again.
I'm interested in a hack & slash method to just get it working as well as a better design proposal if you have one :)
|
If you're spawning the process using [`java.lang.Process`](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) it should "just work" - I don't believe the spawned process will die when the JVM exits. You might find that the Ant libraries make it easier for you to control the spawning though.
|
It does actually "just work", unless you're trying to be clever.
My wrapped java.lang.Process was trying to capture the script's output, so when the JVM died, the script didn't have anywhere to send output so it just dies. If I don't try to capture the output, or the script doesn't generate any or redirects everything to a file or /dev/null, everything works as it should.
|
Spawn a process in Java that survives a JVM shutdown
|
[
"",
"java",
"process",
""
] |
When @RadioServiceGroup is set to NULL, I want to return all the records from the sbi\_l\_radioservicecodes table which has about 120 records. However, when I execute the following procedure and set the @RadioServiceGroup to NULL, it returns no records. Here is the stored proc:
```
CREATE PROCEDURE [dbo].[GetRadioServiceCodes]
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
IF(@RadioServiceGroup = NULL)
BEGIN
SELECT rsc.RadioService
FROM sbi_l_radioservicecodes rsc
END
ELSE
BEGIN
SELECT rsc.RadioService
FROM sbi_l_radioservicecodes rsc
WHERE rsc.RadioServiceGroup = @RadioServiceGroup
END
END
```
|
Try "IS NULL" instead of "= NULL"
|
> Curious, is it just a syntax thing on why = does not work on nvarchar for NULL
Some people are saying that NULL = NULL evaluates to false. This is wrong. NULL = NULL evaluates to NULL.
The result (NULL) is not true, so the ELSE condition is run.
See also : [ThreeValuedLogic on Wikipedia](http://en.wikipedia.org/wiki/Sql_null#Three-valued_logic_.283VL.29)
Another affect you should be aware of - Concatenation: NULL + @SomeVar evaluates to NULL. This can wipe out a computed string unexpectedly.
|
Why doesn't setting a nvarchar variable to null return nothing in this stored proc?
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
Is it better to initialize class member variables on declaration
```
private List<Thing> _things = new List<Thing>();
private int _arb = 99;
```
or in the default constructor?
```
private List<Thing> _things;
private int _arb;
public TheClass()
{
_things = new List<Thing>();
_arb = 99;
}
```
Is it simply a matter of style or are there performance trade-offs, one way or the other?
|
In terms of performance, there is no real difference; field initializers are implemented as constructor logic. The only difference is that field initializers happen before any "base"/"this" constructor.
The constructor approach can be used with auto-implemented properties (field initializers cannot) - i.e.
```
[DefaultValue("")]
public string Foo {get;set;}
public Bar() { // ctor
Foo = "";
}
```
Other than that, I tend to prefer the field initializer syntax; I find it keeps things localized - i.e.
```
private readonly List<SomeClass> items = new List<SomeClass>();
public List<SomeClass> Items {get {return items;}}
```
I don't have to go hunting up and down to find where it is assigned...
The obvious exception is where you need to perform complex logic or deal with constructor parameters - in which case constructor-based initialization is the way to go. Likewise, if you have multiple constructors, it would be preferable for the fields to always get set the same way - so you might have ctors like:
```
public Bar() : this("") {}
public Bar(string foo) {Foo = foo;}
```
edit: as a side comment, note that in the above, if there are other fields (not shown) with field initializers, then they are only directly initialized in the constructors that call `base(...)` - i.e. the `public Bar(string foo)` ctor. The other constructor does *not* run field initializers, since it knows they are done by the `this(...)` ctor.
|
Actually, field initializers as you demonstrate is a convenient shorthand. The compiler actually copies the initialization code into the beginning of each instance constructor that you define for your type.
This has two implications: first, any field initialization code is duplicated in each constructor and, second, any code you include in your constructors to initialize fields to specific values will in fact re-assign the fields.
So performance-wise, and with regards to compiled code size, you're better off moving field initializers into constructors.
On the other hand, the performance impact and code 'bloat' will usually be negligable, and the field initializer syntax has the important benefit of lessening the risk that you might forget to initialize some field in one of your constructors.
|
C# member variable initialization; best practice?
|
[
"",
"c#",
"constructor",
"declaration",
""
] |
Is there a single algorithm that removes elements from a container as happens in the following code?
```
vec_it = std::remove_if( vec.begin(), vec.end(), pred );
vec.erase( vec_it, vec.end() );
```
|
The idiomatic way to do it is like jalf has said. You can build your own function to do that more easily:
```
template<typename T, typename Pred> void erase_if(T &vec, Pred pred)
{
vec.erase(std::remove_if(vec.begin(), vec.end(), pred), vec.end());
}
```
So you can use
```
std::vector<int> myVec;
// (...) fill the vector. (...)
erase_if(myVec, myPred);
```
|
You mean like this?
```
vec.erase( std::remove_if( vec.begin(), vec.end(), pred ), vec.end() );
```
That's the idiomatic way to do it.
|
Single statement method to remove elements from container
|
[
"",
"c++",
"stl",
"erase-remove-idiom",
""
] |
How can I programmatically change my browser's default home page with C#?
|
Set it in this registry setting:
```
HKCU\Software\Microsoft\Internet Explorer\Main\Start Page
```
|
See this, which is not in C#, but you should be able to work out the registry stuff in C# pretty easily.
<http://www.microsoft.com/technet/scriptcenter/resources/qanda/nov04/hey1108.mspx>
Please don't arrange for this code to run on my machine!
|
How to set the default browser home page (IE) with C#?
|
[
"",
"c#",
"browser",
""
] |
I would like to know how to get the name of the property that a method parameter value came from. The code snippet below shows what I want to do:
```
Person peep = new Person();
Dictionary<object, string> mapping = new Dictionary<object, string>();
mapping[peep.FirstName] = "Name";
Dictionary<string, string> propertyToStringMapping = Convert(mapping);
if (mapping[peep.FirstName] == propertyToStringMapping["FirstName"])
Console.WriteLine("This is my desired result");
private Dictionary<string, string> Convert(Dictionary<object, string> mapping)
{
Dictionary<string, string> stringMapping = new Dictionary<string, string>();
foreach (KeyValuePair<object, string> kvp in mapping)
{
//propertyName should eqal "FirstName"
string propertyName = kvp.Key??????
stringMapping[propertyName] = kvp.Value;
}
return stringMapping;
}
```
|
I think ultimately you will need to store either the PropertyInfo object associated with the property, or the string representation of the property name in you mapping object. The syntax you have:
```
mapping[peep.FirstName] = "Name";
```
Would create an entry in the dictionary with a key value equal to the value of the peep.FirstName property, and the Value equal to "Name".
If you store the property name as a string like:
```
mapping["FirstName"] = "Name";
```
You could then use reflection to get the "FirstName" property of your object. You would have to pass the "peep" object into the Convert function, however. This seems to be somewhat opposite of what you are wanting to do.
You may also be able to get crazy with Expressions and do something like:
```
var mapping = new Dictionary<Expression<Action<T>>,string>();
mapping[ p => p.FirstName ] = "Name";
```
Then in your Convert function you could examine the expression. It would look something like:
```
private Dictionary<string,string> Convert(Dictionary<Expression<Action<T>>,string> mapping)
{
var result = new Dictionary<string,string>();
foreach(var item in mapping)
{
LambdaExpression ex = item.Key as LambdaExpression;
string propertyName = ((MemberExpression)ex.Body).Member.Name;
string propertyValue = item.Value;
result.Add(propertyName,proeprtyValue);
}
return result;
}
```
This is more or less off the top of my head, so I may have the expression types off a bit. If there are issues with this implementation let me know and I will see if I can work out a functional example.
|
You are not able to do so in this way, since the way it works is that C# evaluates the value of FirstName property by calling its get accessor and passes the value of that to the indexer of the dictionary. Therefore, the way you found out FirstName value is completely lost. Just like the way you evaluate 2 + 2.
If you write, "x = 2 + 2", x will have the value 4 but there will be no way to tell if it was 3 + 1 or 2 + 2 or 5 + (-1) or ... that evaluated to 4.
|
Getting the property name that a value came from
|
[
"",
"c#",
".net",
"reflection",
""
] |
How can I display something over all other application. I want to to display something over all form of my program and all other programs open on my desktop (not mine).
**\*Top Most doesn't work I have tested and my browser can go OVER my application :S**
Here is an image of when I use TopMost to TRUE. You can see my browser is over it...
<http://www.freeimagehosting.net/uploads/5a98165605.png>
|
You can use the form instance and set the property **TopMost** to True.
---
If you want to be over all Windows, there are another way with **Win32 Api** calls.
Here is what you could do:
In your form class add :
```
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
```
In the form load you can add :
```
SetForegroundWindow(this.Handle);
```
This should do the trick.
## Update
**TopMost** should do the job BUT: Top most OR/AND the Win32 Api call will only work not inside Visual Studio (well for Vista and with VS2008 I tested it... I can't tell for other). Try running the program with the .Exe from the /bin directory, it will works.
|
The Form.TopMost property will set your form the top form above all other running windows applications (not just your forms.)
```
myForm.TopMost = true; // This will do the job
```
|
Form top most?
|
[
"",
"c#",
".net",
""
] |
I have a block of JSP code that needs to be used in several places (basically a widget that several pages use). What's a good way to modularize this? I'd rather not put it in an object since string manipulation of HTML gets ugly. Using `<%@ include file="foo.jsp"%>` is problematic because we wind up having implicit global vars.
|
You can create a simple *tag* and use it anywhere you want your widget. A tag is a reusable object that you can use in any of your JSP's.
Please see <http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags.html>.
|
1. Separate the JSP out into its own file and include it (JSP Includes, Tiles Includes, etc)
2. Can you create a Tag Lib incorporating the functionality?
|
Best way to modularize a block of JSP code
|
[
"",
"java",
"jsp",
""
] |
We have very strange problem, one of our applications is continually querying server by using .net remoting, and every 100 seconds the application stops querying for a short duration and then resumes the operation. The problem is on a client and not on the server because applications actually queries several servers in the same time and stops receiving data from all of them in the same time.
|
I've never seen that behavior before and unfortunately it's a vague enough scenario I think you're going to have a hard time finding someone on this board who's encountered the problem. It's likely specific to your application.
I think there are a few investigations you can do to help you narrow down the problem.
1. Determine whether it's the client or server that is actually stalling. If you have problems determining this, try installing a packet filter and monitor the traffic to see who sent the last data. You likely won't be able to read the binary data but at least you will get a sense of who is lagging behind.
2. Once you figure out whether it's the client or server causing the lag, attempt to debug into the application and get a breakpoint where the hang occurs. This should give you enough details to help track down the problem. Or at least ask a more defined question on SO.
|
100 Seconds is a give away number as it's the default timeout for a webrequest in .Net.
I've seen in the past that the PSI (Project Server Interface within Microsoft Project) didn't override the timeout and so the default of 100 seconds was applied and would terminate anything talking to it for longer than that time.
Do you have access to all of the code and are you sure you have set timeouts where applicable so that any defaults are not being applied unbeknownst to you?
|
.net remoting stops every 100 seconds
|
[
"",
"c#",
".net",
"remoting",
""
] |
I have a \*.MDB database file, and I am wondering if it is possible or recommended to work against it using LINQ in C#. I am also wondering what some simple examples would look like.
I don't know a lot about LINQ, but my requirements for this task are pretty simple (I believe). The user will be passing me a file path to Microsoft Access MDB database and I would like to use LINQ to add rows to one of the tables within the database.
|
What you want is a LINQ to ODBC provider, or a LINQ to JET/OLEDB provider.
Out of the box, MS doesn't make one. There may be a 3rd party who does.
|
Actually I recently (today) discovered that you can access an Access database with LinqToSql. It must be in the 2002 or newer format, you will not be able to drag and drop the tables to your datacontext so either manually create the objects in your dbml or you can use SQL Server Migration for Access to move it to a sql server and then drag and drop all you want. When you want to actually create the context pass it an OleDbConnection. Use your standard Jet.OLEDB.4.0 connection string on the OleDbConnection and you are good to go. Not sure of the limitation this may incurr though. I just did a quick sample and did an OrderBy without issue.
|
Query Microsoft Access MDB Database using LINQ and C#
|
[
"",
"c#",
"linq",
"ms-access",
""
] |
When you use the PHP [copy](https://www.php.net/manual/en/function.copy.php) function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file?
|
The obvious solution would be to call [file\_exists](https://www.php.net/manual/en/function.file-exists.php) to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call [file\_exists](https://www.php.net/manual/en/function.file-exists.php) and when you call [copy](https://www.php.net/manual/en/function.copy.php). The only safe way to check if the file exists is to use [fopen](https://www.php.net/manual/en/function.fopen.php).
When you call [fopen](https://www.php.net/manual/en/function.fopen.php), set the mode to 'x'. This tells [fopen](https://www.php.net/manual/en/function.fopen.php) to create the file, but only if it doesn't exist. If it exists, [fopen](https://www.php.net/manual/en/function.fopen.php) will fail, and you'll know that you couldn't create the file. If it succeeds, you will have a created a file at the destination that you can safely copy over. Sample code is below:
```
// The PHP copy function blindly copies over existing files. We don't wish
// this to happen, so we have to perform the copy a bit differently. The
// only safe way to ensure we don't overwrite an existing file is to call
// fopen in create-only mode (mode 'x'). If it succeeds, the file did not
// exist before, and we've successfully created it, meaning we own the
// file. After that, we can safely copy over our own file.
$filename = 'sourcefile.txt'
$copyname = 'sourcefile_copy.txt'
if ($file = @fopen($copyname, 'x')) {
// We've successfully created a file, so it's ours. We'll close
// our handle.
if (!@fclose($file)) {
// There was some problem with our file handle.
return false;
}
// Now we copy over the file we created.
if (!@copy($filename, $copyname)) {
// The copy failed, even though we own the file, so we'll clean
// up by itrying to remove the file and report failure.
unlink($copyname);
return false;
}
return true;
}
```
|
I think you answered your own question - check to make sure the destination file exists before performing the copy. If the file exists, skip the copy.
Update: I see you really did answer your own question. You mention race conditions, but if you do find that the file already exists, how do you know that:
* the file that is already there is really the one you want to copy
* the other process copying the file has completed its job (the file data is all there)
* the other process copying the file isn't going to fail (and leave an incomplete file, or delete the new file)
I think you should consider these questions when designing a solution to your problem.
|
How do you copy a file in PHP without overwriting an existing file?
|
[
"",
"php",
"file",
"file-io",
""
] |
**Background**
We have a web application in which several developers have written several .js files that manipulate the DOM and the problem of duplicate function names has crept into our application.
**Question**
Can anyone recommend a tool that will warn us when we accidentally write a web page with two javascript functions with the same name?
**Example**
*HTML page*
```
<script language="JavaScript" src="test.js" type="text/javascript"></script>
<script>function foo() {alert('bar');}</script>
```
*test.js*
```
function foo() {alert('foo');}
```
Since foo() is declared twice in the page, apparently only the one that takes precedence is loaded.
The tools I've used seem to ignore this. Firebug only shows the loaded function. Netbeans will show both functions in navigator (without a warning), but only looks at one file at a time (ie, I can't point it at the HTML file and see it and the .js at the same time.) and web developer extensions allows me to look at everything at once, but no errors or warnings. Firefox's error console also throws no warning or error. Neither does IE.
Thanks!
|
Well, using a parser may not always be ideal as it requires an extra step of copying and pasting your code, and everyone else's, into the parser and even then I'm not sure it would catch what you want. The time tested solution to collaborative Javascript development is to namespace your code.
```
var myNamespace = function (){
var myPrivateProperty;
var myPrivateFunction = function(){};
return{
myPublicProperty: '',
myPublicFunction: function(){}
}
}();
```
This is based on Douglas Crockford's [module pattern](http://yuiblog.com/blog/2007/06/12/module-pattern/).
Then you can call your public functions this way:
```
myNamespace.myPublicFunction();
```
And your public properties:
```
myNamespace.myPublicProperty;
```
Each developer can develop in their own namespace so as to not step on others' code.
|
I have often used [JSLINT](http://jslint.com/)
In short it is a "compiler" for JavaScript using JavaScript. I have learned a lot by watching Douglas Crockford’s training videos.
It not only checks for duplicate functions, but global variables, and a whole bunch of other things. Like Douglas said in one of his videos it allows you to only use the good bits of JavaScript
|
Tool that detects duplicate javascript function names in a web page?
|
[
"",
"javascript",
""
] |
Could someone explain why this works in C#.NET 2.0:
```
Nullable<DateTime> foo;
if (true)
foo = null;
else
foo = new DateTime(0);
```
...but this doesn't:
```
Nullable<DateTime> foo;
foo = true ? null : new DateTime(0);
```
The latter form gives me an compile error "Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'."
Not that I can't use the former, but the second style is more consistent with the rest of my code.
|
The compiler is telling you that it doesn't know how convert `null` into a `DateTime`.
The solution is simple:
```
DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);
```
Note that `Nullable<DateTime>` can be written `DateTime?` which will save you a bunch of typing.
|
FYI (Offtopic, but nifty and related to nullable types) we have a handy operator just for nullable types called the null coalescing operator
```
??
```
Used like this:
```
// Left hand is the nullable type, righthand is default if the type is null.
Nullable<DateTime> foo;
DateTime value = foo ?? new DateTime(0);
```
|
Nullable type issue with ?: Conditional Operator
|
[
"",
"c#",
"generics",
"nullable",
"conditional-operator",
""
] |
In Perl
```
print "a" x 3; # aaa
```
In C#
```
Console.WriteLine( ??? )
```
|
It depends what you need... there is `new string('a',3)` for example.
For working with strings; you could just loop... not very interesting, but it'll work.
With 3.5, you could use `Enumerable.Repeat("a",3)`, but this gives you a sequence of strings, not a compound string.
If you are going to use this a lot, you could use a bespoke C# 3.0 extension method:
```
static void Main()
{
string foo = "foo";
string bar = foo.Repeat(3);
}
// stuff this bit away in some class library somewhere...
static string Repeat(this string value, int count)
{
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (string.IsNullOrEmpty(value)) return value; // GIGO
if (count == 0) return "";
StringBuilder sb = new StringBuilder(value.Length * count);
for (int i = 0; i < count; i++)
{
sb.Append(value);
}
return sb.ToString();
}
```
|
If you only need to repeat a single character (as in your example) then this will work:
```
Console.WriteLine(new string('a', 3))
```
|
What is the C# equivalent of Perl's repetition operator?
|
[
"",
"c#",
"perl",
"string",
""
] |
I have following string
```
String str = "replace :) :) with some other string";
```
And I want to replace first occurance of `:)` with some other string
And I used `str.replaceFirst(":)","hi");`
it gives following exception
> "Unmatched closing ')'"
I tried using `replace` function but it replaced all occurance of `:)`.
|
[Apache Jakarta Commons](http://commons.apache.org/) are often the solution for this class of problems. In this case, I would have a look at [commons-lang](http://commons.apache.org/lang/), espacially [StringUtils.replaceOnce()](http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html#replaceOnce(java.lang.String,%20java.lang.String,%20java.lang.String)).
|
The `replaceFirst` method takes a regular expression as its first parameter. Since `)` is a special character in regular expressions, you must quote it. Try:
```
str.replaceFirst(":\\)", "hi");
```
The double backslashes are needed because the double-quoted string also uses backslash as a quote character.
|
String replace function
|
[
"",
"java",
"string",
""
] |
I have an object that implements [ArrayAccess](http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html), [Iterator](http://www.php.net/~helly/php/ext/spl/interfaceIterator.html) and [Countable](http://www.php.net/~helly/php/ext/spl/interfaceCountable.html). That produces a nigh-perfect array masking. I can access it with offsets (`$object[foo]`), I can throw it into a [`foreach`](http://php.net/foreach)-loop, and many other things.
But what I can't do is give it to the native array iterator functions (`next()`, `reset()`, `current()`, `key()`), even though I have implemented the required methods from Iterator. PHP seems to stubbornly try to iterate through its member variables, and entirely disregards the iterator-methods.
Is there an interface that would hook the object to the remaining array-traversing-functions, or am I stuck with what I have?
**Update:** IteratorAggregate doesn't seem to be the answer either. While it is used in `foreach`-loops, the basic array iterator functions don't call the methods.
|
Recent changes in PHP prevent ArrayIterators form being manipulated using the standard array functions (reset, next, etc).
This should be restored soon:
<http://news.php.net/php.internals/42015>
|
One way to get this to work is to define your own iterator in a separate class, and then tell your main class to use that new iterator instead of the default one.
```
class MyIterator implements Iterator {
public function key() {
//
}
public function rewind() {
//
}
// etc.
}
class MyMainClass implements IteratorAggregate {
private $_data = array();
// getIterator is required for the IteratorAggregate interface.
public function getIterator() {
return new MyIterator($this->_data);
}
// etc.
}
```
Then you should have as much control as you need. (And you can reuse your own MyIterator across a number of classes).
No testing done on the above, but the principle is correct, I believe.
Hope this helps!
|
PHP objects as faux-arrays
|
[
"",
"php",
"arrays",
"spl",
""
] |
I have an ActiveX plugin that we need (if possible) to run in Firefox. Is there a plugin (or other way) for Firefox that will allow this?
|
I seem to have found a solution:
<http://code.google.com/p/ff-activex-host/>
"This Firefox plugin makes it possible to use ActiveX controls in Firefox. It is based on the Gecko NPAPI and provides full access to the hosted control (events, functions, properties)."
|
You used to be able to in Firefox 1.5 but not any longer I believe, the [plugin](http://www.iol.ie/~locka/mozilla/mozilla.htm) doesnt seem to be supported anymore.
More info [here](http://groups.google.com/group/mozilla.dev.tech.plugins/browse_thread/thread/c1ffb11ac6bcf0e0/4209766365b7146f)
|
Is there a way to run ActiveX components in Firefox through the use of a plugin?
|
[
"",
"c++",
"firefox",
"browser",
"activex",
"xul",
""
] |
I would like to return a string with all of the contents of a CSS rule, like the format you'd see in an inline style. I'd like to be able to do this without knowing what is contained in a particular rule, so I can't just pull them out by style name (like `.style.width` etc.)
The CSS:
```
.test {
width:80px;
height:50px;
background-color:#808080;
}
```
The code so far:
```
function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<classes.length;x++) {
if(classes[x].selectorText==className) {
//this is where I can collect the style information, but how?
}
}
}
getStyle('.test')
```
|
Adapted from [here](http://www.javascriptkit.com/domref/cssrule.shtml), building on scunliffe's answer:
```
function getStyle(className) {
var cssText = "";
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
cssText += classes[x].cssText || classes[x].style.cssText;
}
}
return cssText;
}
alert(getStyle('.test'));
```
|
Since the accepted answer from "nsdel" is only avilable with one stylesheet in a document this is the adapted full working solution:
```
/**
* Gets styles by a classname
*
* @notice The className must be 1:1 the same as in the CSS
* @param string className_
*/
function getStyle(className_) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
if (!classes)
continue;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
if (classes[x].selectorText == className_) {
var ret;
if(classes[x].cssText){
ret = classes[x].cssText;
} else {
ret = classes[x].style.cssText;
}
if(ret.indexOf(classes[x].selectorText) == -1){
ret = classes[x].selectorText + "{" + ret + "}";
}
return ret;
}
}
}
}
```
Notice: The selector must be the same as in the CSS.
|
How do you read CSS rule values with JavaScript?
|
[
"",
"javascript",
"html",
"css",
""
] |
I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application.
I'm trying to go in a file and read the lines and print them on the console.
I've been able to do it with a while-loop, but I want to try it with a foreach loop.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace testing
{
public class Program
{
public static void Main(string[] args)
{
string file = @"C:\Temp\New Folder\New Text Document.txt";
using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
foreach(string line in file)
{
Console.WriteLine(line);
}
}
}
}
}
}
```
The error I keep getting for this is: Cannot convert type 'char' to 'string'
The while loop, which does work, looks like this:
```
while((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
```
I'm probably overlooking something really basic, but I can't see it.
|
To read all lines in New Text Document.txt:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace testing
{
public class Program
{
public static void Main(string[] args)
{
string file = @"C:\Temp\New Folder\New Text Document.txt";
using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
while(!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
}
}
}
}
```
|
If you want to read a file line-by-line via foreach (in a reusable fashion), consider the following iterator block:
```
public static IEnumerable<string> ReadLines(string path)
{
using (StreamReader reader = File.OpenText(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
```
Note that this this is lazily evaluated - there is none of the buffering that you would associate with `File.ReadAllLines()`. The `foreach` syntax will ensure that the iterator is `Dispose()`d correctly even for exceptions, closing the file:
```
foreach(string line in ReadLines(file))
{
Console.WriteLine(line);
}
```
---
(this bit is added just for interest...)
Another advantage of this type of abstraction is that it plays beautifully with LINQ - i.e. it is easy to do transformations / filters etc with this approach:
```
DateTime minDate = new DateTime(2000,1,1);
var query = from line in ReadLines(file)
let tokens = line.Split('\t')
let person = new
{
Forname = tokens[0],
Surname = tokens[1],
DoB = DateTime.Parse(tokens[2])
}
where person.DoB >= minDate
select person;
foreach (var person in query)
{
Console.WriteLine("{0}, {1}: born {2}",
person.Surname, person.Forname, person.DoB);
}
```
And again, all evaluated lazily (no buffering).
|
FileStream StreamReader problem in C#
|
[
"",
"c#",
""
] |
I want to enumerate all available drive letters (which aren't already taken) in Windows using VC++.
How can I do this?
|
[::GetLogicalDrives()](https://msdn.microsoft.com/en-us/library/aa364972(v=vs.85).aspx) returns a list of available (read: used) drives as bits in a mask. This should include mapped network drives. Thus, you can simply walk the bits to find bits that are zero, meaning no drive is present. If in doubt, you can always call [::GetDriveType()](http://msdn.microsoft.com/en-us/library/windows/desktop/aa364939%28v=vs.85%29.aspx) with the drive letter + `":\"` (`":\\"` in C code, or `_T(":\\")` in Unicode-aware terminology, of course), and that should return `DRIVE_UNKNOWN` or `DRIVE_NO_ROOT_DIR` if the drive is available.
|
[`GetLogicalDriveStrings`](http://msdn.microsoft.com/en-us/library/aa364975(VS.85).aspx) can get you just the list of currently used drive letters.
[`GetVolumeInformation`](http://msdn.microsoft.com/en-us/library/aa364993(VS.85).aspx) can be used to get more information about a specific drive.
|
Enumerating all available drive letters in Windows
|
[
"",
"c++",
"winapi",
"drives",
""
] |
What do people recommend for creating popup's in ASP.Net MVC? I have used the AJAX toolkit and component art's methods in the web forms world and am looking something with similar capability.
What JQUERY plugins do people like? SimpleModal, JBOX (I think this was, what it was called)
Is it worth exploring pulling out the JavaScript from the AJAX toolkit?
|
jqModal looks pretty cool <http://dev.iceburg.net/jquery/jqModal/> - have only done some brief experiments, not used in production yet, but have put in the toybox for my current project.
|
I like [lightBox](http://leandrovieira.com/projects/jquery/lightbox/)
|
asp.net mvc & popup dialogs
|
[
"",
"javascript",
"asp.net-mvc",
"modal-dialog",
""
] |
I am running JVM 1.5.0 (Mac OS X Default), and I am monitoring my Java program in the Activity Monitor. I have the following:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
public class MemoryTest {
public static void memoryUsage() {
System.out.println(
Runtime.getRuntime().totalMemory() -
Runtime.getRuntime().freeMemory()
);
}
public static void main( String[] args ) throws IOException {
/* create a list */
ArrayList<Date> list = new ArrayList<Date>();
/* fill it with lots of data */
for ( int i = 0; i < 5000000; i++ ) {
list.add( new Date() );
} // systems shows ~164 MB of physical being used
/* clear it */
memoryUsage(); // about 154 MB
list.clear();
list = null;
System.gc();
memoryUsage(); // about 151 KB, garbage collector worked
// system still shows 164 MB of physical being used.
System.out.println("Press enter to end...");
BufferedReader br = new BufferedReader(
new InputStreamReader( System.in )
);
br.readLine();
}
```
}
So why doesn't the physical memory get freed even though the garbage collector seems to work just fine?
|
Many JVMs never return memory to the operating system. Whether it does so or not is implementation-specific. For those that don't, the memory limits specified at startup, usually through the -Xmx flag, are the primary means to reserve memory for other applications.
I am having a hard time finding documentation on this subject, but the [garbage collector documentation for Sun's Java 5](http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html) does address this, suggesting that under the right conditions, the heap will shrink if the correct collector is used—by default, if more that 70% of the heap is free, it will shrink so that only 40% is free. The command line options to control these are `-XX:MinHeapFreeRatio` and `-XX:MaxHeapFreeRatio`.
|
There are several command line options for the JVM which help to tune the size of the heap used by Java.
Everybody knows (or should know) about -Xms and -Xmx, which set the minimum and the maximum size of the heap.
But there is also -XX:MinHeapFreeRatio and -XX:MaxHeapFreeRatio which are the respective limits between which the JVM manages free space. It does this by shrinking the used heap, and it can lower the memory consumption of the program.
You can find more information here:
* [Sun Java System Application Server Enterprise Edition 8.1 2005Q1 Performance Tuning Guide, Chapter 4](http://docs.sun.com/source/819-0084/pt_tuningjava.html)
* [Tuning Garbage Collection Outline](http://www.petefreitag.com/articles/gctuning/), by Pete Freitag
|
Java still uses system memory after deallocation of objects and garbage collection
|
[
"",
"java",
"memory-management",
"memory-leaks",
"garbage-collection",
""
] |
I've got a (SQL Server 2005) database where I'd like to create views on-the-fly. In my code, I'm building a CREATE VIEW statement, but the only way I can get it to work is by building the entire query string and running it bare. I'd like to use parameters, but this:
```
SqlCommand cmd = new SqlCommand("CREATE VIEW @name AS SELECT @body");
cmd.Parameters.AddWithValue("@name", "foo");
cmd.Parameters.AddWithValue("@body", "* from bar");
```
tells me there's an error "near the keyword VIEW" (presumably the "@name") -- needless to say `"CREATE VIEW foo AS SELECT * FROM bar"` works like a champ.
Is this just not possible? If not, is there a better way to clean up the input before running the CREATE statement? In some cases, the query body could have user input and I'd just feel safer if there was some way that I could say "treat this as the body of a single select statement". Maybe what I'm asking for is just too weird?
---
FOLLOWUP 04 Nov:
OK, yes, what I want is sort of like SQL injection when you get down to it, but I would like to at least minimize (if not totally remove) the option of running this command and dropping a table or something. Granted, the user this is running as doesn't have permissions to drop any tables in the first place, but I think you get the idea. I'd love to have a way of saying, in effect, `"This statement will not alter any existing data in any way{ ... }"`.
The way it's coded right now is to do string concatenation like in **friol**'s answer, but that does no sanitization at all. I'd feel better if I could at least scrub it for suspect characters, like ; or -- or what have you. I was hoping there might be a library function to do the scrub for me, or something along those lines.
|
Maybe I've not understood it correctly, but what prevents you to do:
```
viewname="foo";
viewwhere="* from bar";
SqlCommand cmd = new SqlCommand("CREATE VIEW "+viewname+" AS SELECT "+viewwhere);
```
|
Parameters are not simply string substitutions. That is why your code won't work.
Its like you cant do
sql = "select \* from orders where orders\_id in (?)"
and pass "1,2,3,5" as parameter.
Parameters are type checked and can only contain scalar values IIRC.
|
Parameterized CREATE VIEW possible?
|
[
"",
"sql",
"sql-server-2005",
"parameters",
"view",
""
] |
What exception should I throw if I encounter an illegal state - for instance, an initialization method that should only be called once being called a second time? I don't really see any built-in exception that makes sense. This seems like something that should be in the framework - am I not poking in the right spot?
|
[InvalidOperationException](http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx) maybe?
> The exception that is thrown when a method call is invalid for the object's current state.
|
In general you should program your object in such a way *that it cannot reach an invalid state*. If you find out that your object is in an invalid state then you should throw a `SystemException` or an exception *directly derived* from `SystemException`. This is the answer to the question *in the title*.
However, the exceptional circumstance that you are *referring to* in the question text is a *user of your object* pushing it into an illegal state. In that case `InvalidOperationException` is the right exception to throw, as indicated in [this earlier answer](https://stackoverflow.com/a/259805/589259). This will avoid your object *getting* into an illegal state.
Needless to say you need to *document* how your object should be used. If your object has a long life expectancy or if it is used/shared between different objects then it is nice for a user to be able to request the current state, and to implement `ToString` to retrieve the current state as text, for instance in a debugging environment / log.
|
Is there a built in .NET exception that indicates an illegal object state?
|
[
"",
"c#",
".net",
"exception",
""
] |
We've been using [jbossmq](http://www.jboss.org/community/docs/DOC-10525) and [csil](http://csil.sourceforge.net). The implementation has been successful in production for 6 years, but I'm wondering if something better is available.
One issue is jbossmq's thread per client model, and scheduled end of life. Another is csil's lack of support for JBossMessaging, which is the latest JMS implementation from JBoss.
|
IKVM for compiling .NET from Java looks interesting.
For .NET messaging check out [RabbitMQ](http://www.rabbitmq.com/).
|
You should look at an ActiveMQ backend with NMS clients. I've had no problems with it.
I can't vouch for it though because the production system I am using it in is not high volume.
|
What is the best messaging server for communicating across java and .net?
|
[
"",
"c#",
"jboss",
""
] |
I don't understand how GCC works under Linux. In a source file, when I do a:
```
#include <math.h>
```
Does the compiler extract the appropriate binary code and insert it into the compiled executable OR does the compiler insert a reference to an external binary file (a-la Windows DLL?)
I guess a generic version of this question is: Is there an equivalent concept to Windows DLLs under \*nix?
|
Well. When you include `math.h` the compiler will read the file that contains declarations of the functions and macros that can be used. If you call a function declared in that file (*header*), then the compiler inserts a call instruction into that place in your object file that will be made from the file you compile (let's call it `test.c` and the object file created `test.o`). It also adds an entry into the relocation table of that object-file:
```
Relocation section '.rel.text' at offset 0x308 contains 1 entries:
Offset Info Type Sym.Value Sym. Name
0000001c 00000902 R_386_PC32 00000000 bar
```
This would be a relocation entry for a function bar. An entry in the symbol table will be made noting the function is yet undefined:
```
9: 00000000 0 NOTYPE GLOBAL DEFAULT UND bar
```
When you link the `test.o` object file into a program, you need to link against the math library called `libm.so` . The `so` extension is similar to the `.dll` extension for windows. It means it is a **shared object file**. The compiler, when linking, will fix-up all the places that appear in the relocation table of `test.o`, replacing its entries with the proper address of the bar function. Depending on whether you use the shared version of the library or the static one (it's called `libm.a` then), the compiler will do that fix-up after compiling, or later, at runtime when you actually start your program. When finished, it will inject an entry in the table of shared libraries needed for that program. (can be shown with `readelf -d ./test`):
```
Dynamic section at offset 0x498 contains 22 entries:
Tag Type Name/Value
0x00000001 (NEEDED) Shared library: [libm.so.6]
0x00000001 (NEEDED) Shared library: [libc.so.6]
... ... ...
```
Now, if you start your program, the dynamic linker will lookup that library, and will link that library to your executable image. In Linux, the program doing this is called `ld.so`. Static libraries don't have a place in the dynamic section, as they are just linked to the other object files and then they are forgotten about; they are part of the executable from then on.
In reality it is actually much more complex and i also don't understand this in detail. That's the rough plan, though.
|
There are several aspects involved here.
First, **header files**. The compiler simply includes the content of the file at the location where it was included, nothing more. As far as I know, GCC doesn't even treat standard header files differently (but I might be wrong there).
However, header files might actually not contain the implementation, only its declaration. If the implementation is located somewhere else, you've got to tell the compiler/linker that. By default, you do this by simply passing the appropriate **library files** to the compiler, or by passing a library name. For example, the following two are equivalent (provided that `libcurl.a` resides in a directory where it can be found by the linker):
```
gcc codefile.c -lcurl
gcc codefile.c /path/to/libcurl.a
```
This tells the [link editor](http://en.wikipedia.org/wiki/Linker) (“linker”) to link your code file against the implementation of the static library `libcurl.a` (the compiler `gcc` actually ignores these arguments because it doesn't know what to do with them, and simply passes them on to the linker). However, this is called **static linking**. There's also [**dynamic linking**](http://en.wikipedia.org/wiki/Dynamic_linker), which takes place at startup of your program, and which happens with `.dll`s under Windows (whereas static libraries correspond to `.lib` files on Windows). Dynamic library files under Linux usually have the file extension `.so`.
The best way to learn more about these files is to familiarize yourself with the GCC linker, `ld`, as well as the excellent toolset [`binutils`](http://www.gnu.org/software/binutils/), with which you can edit/view library files effortlessly (any binary code files, really).
|
Includes with the Linux GCC Linker
|
[
"",
"c++",
"linux",
"unix",
"gcc",
""
] |
I find it curious that the most obvious way to create `Date` objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.
How do you check that a date, given as a combination of day, month, and year, is a valid date?
For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.
|
The current way is to use the calendar class. It has the [setLenient](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setLenient%28boolean%29) method that will validate the date and throw and exception if it is out of range as in your example.
Forgot to add:
If you get a calendar instance and set the time using your date, this is how you get the validation.
```
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(yourDate);
try {
cal.getTime();
}
catch (Exception e) {
System.out.println("Invalid date");
}
```
|
Key is `df.setLenient(false);`. This is more than enough for simple cases. If you are looking for a more robust (I doubt that) and/or alternate libraries like [joda-time](https://www.joda.org/joda-time/), then look at the [answer by user "tardate"](https://stackoverflow.com/a/892204/1076848)
```
final static String DATE_FORMAT = "dd-MM-yyyy";
public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
```
|
How to sanity check a date in Java
|
[
"",
"java",
"validation",
"calendar",
"date",
""
] |
I'm currently using `std::ofstream` as follows:
```
std::ofstream outFile;
outFile.open(output_file);
```
Then I attempt to pass a `std::stringstream` object to `outFile` as follows:
```
GetHolesResults(..., std::ofstream &outFile){
float x = 1234;
std::stringstream ss;
ss << x << std::endl;
outFile << ss;
}
```
Now my `outFile` contains nothing but garbage: "0012E708" repeated all over.
In `GetHolesResults` I can write
```
outFile << "Foo" << std:endl;
```
and it will output correctly in `outFile`.
Any suggestion on what I'm doing wrong?
|
You can do this, which doesn't need to create the string. It makes the output stream read out the contents of the stream on the right side (usable with any streams).
```
outFile << ss.rdbuf();
```
|
If you are using `std::ostringstream` and wondering why nothing get written with `ss.rdbuf()` then use `.str()` function.
```
outFile << oStream.str();
```
|
Writing stringstream contents into ofstream
|
[
"",
"c++",
"stl",
"parameters",
"stringstream",
"ofstream",
""
] |
I was curious if anyone had any hard numbers around the performance difference between annotating Entities using private fields instead of public getter methods. I've heard people say that fields are slower because they're called "through reflection" but then again so are the getter methods, no? Hibernate needs to set the accessibility of the field to true before it tries to read it which I can see having some *slight* overhead. However wouldn't that be done at the Class-level in the scope of a Session or perhaps only once when the Configuration is read and SessionFactory is built?
Just curious if this is a myth or if there's really truth to it; I personally find annotating the fields to be a bit more readable.
|
Loaded 5000 records into a simple 3 column table. Mapped two classes to that table, one using annotated private fields and another using annotated public getters. Ran 30 runs of Spring's HibernateTemplate.loadAll() followed by a HibernateTemplate.clear() to purge the Session cache. Results in ms below...
methods total: 6510, average: 217
fields total: 6586, average: 219
I should probably take another stab at it after adding more properties to each class but right now the difference doesn't appear to be statistically significant.
|
ok, I can't give numbers haha, but I would guess that accessing the fields through reflection wouldn't be a 'one time' thing. Each object has its own private members.
I honestly don't know much about reflection but the getter/setters should be straight forward. In fact you can try setting one of the methods to private and I think it won't work because it can't find the method it needs.
There are other issues like proxies that will affect getter methods though depending on how you load your entities.
This is all I see in the documentation:
> The access attribute lets you control
> how Hibernate will access the property
> at runtime. By default, Hibernate will
> call the property get/set pair. If you
> specify access="field", Hibernate will
> bypass the get/set pair and access the
> field directly, using reflection. You
> may specify your own strategy for
> property access by naming a class that
> implements the interface
> org.hibernate.property.PropertyAccessor.
My guess is that reflection in general is going to be a higher cost though, but sorry.. no numbers :(
|
Performance difference between annotating fields or getter methods in Hibernate / JPA
|
[
"",
"java",
"hibernate",
"jpa",
""
] |
Do you have any tricks for generating SQL statements, mainly INSERTs, in Excel for various data import scenarios?
I'm really getting tired of writing formulas with like
`="INSERT INTO Table (ID, Name) VALUES (" & C2 & ", '" & D2 & "')"`
|
The semi-colon needs to be inside the last double quote with a closing paren. When adding single quotes around a string, remember to add them outside your selected cell.
(spaces added for visibility - remove before inserting)
`=CONCATENATE("insert into table (id, name) values (",C2,",' ",D2," ');")`
Here is another view:
`=CONCATENATE("insert into table (id, date, price) values (",C3,",'",D3,"',",B3,");")`
|
I used to use String concatenation method to create SQL inserts in Excel. It can work well but can also be a little time consuming and 'fiddly'.
I created an Excel Add-In that makes generating Inserts from Excel easier :
(see the video at the bottom of the page)
<http://www.howinexcel.com/2009/06/generating-sql-insert-statements-in-excel.html>
<http://www.querycell.com/SQLGenerator.html>
<http://www.oneclickcommissions.com/excel-statement.html>
|
Tricks for generating SQL statements in Excel
|
[
"",
"sql",
"vba",
"excel",
"metaprogramming",
""
] |
How do I get a human-readable file size in bytes abbreviation using .NET?
**Example**:
Take input 7,326,629 and display 6.98 MB
|
This may not the most efficient or optimized way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.
```
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
order++;
len = len/1024;
}
// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string result = String.Format("{0:0.##} {1}", len, sizes[order]);
```
|
using **Log** to solve the problem....
```
static String BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num).ToString() + suf[place];
}
```
Also in C#, but should be a snap to convert. Also I rounded to 1 decimal place for readability.
Basically determine the number of decimal places in Base 1024 and then divide by `1024^decimalplaces`.
And some samples of use and output:
```
Console.WriteLine(BytesToString(9223372036854775807)); //Results in 8EB
Console.WriteLine(BytesToString(0)); //Results in 0B
Console.WriteLine(BytesToString(1024)); //Results in 1KB
Console.WriteLine(BytesToString(2000000)); //Results in 1.9MB
Console.WriteLine(BytesToString(-9023372036854775807)); //Results in -7.8EB
```
Edit:
Was pointed out that I missed a `Math.Floor`, so I incorporated it. (`Convert.ToInt32` uses rounding, not truncating and that's why `Floor` is necessary.) Thanks for the catch.
Edit2:
There were a couple of comments about negative sizes and 0 byte sizes, so I updated to handle those cases.
|
How do I get a human-readable file size in bytes abbreviation using .NET?
|
[
"",
"c#",
".net",
"vb.net",
"filesize",
"human-readable",
""
] |
My mission is to create a little app where you can upload a picture, and the app will turn it into ASCII art. I'm sure these exist already but I want to prove that I can do it myself.
This would involve taking an image, making it greyscale and then matching each pixel with a character depending on how dark the picture is and how full the character is.
So my question is, Using the GD Library (or i guess some other means if necessary) how do I make an image black and white?
|
A common formula to convert RGB to greyscale is:
```
Gray scale intensity = 0.30R + 0.59G + 0.11B
```
|
As pointed out by [nickf](https://stackoverflow.com/users/9021/nickf) in his [comment](https://stackoverflow.com/questions/276780/making-an-image-greyscale-with-gd-library#276811), the simple formula `(pixel.r + pixel.g + pixel.b) / 3` is not correct. Use the GD-included function `imagefilter()` (no need to iterate over all pixels in an image using PHP loops) instead:
```
$im = imagecreatefrompng('dave.png');
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagepng($im, 'dave.png');
```
|
Making an Image Greyscale with GD Library
|
[
"",
"php",
"image",
"gd",
""
] |
I believe this is a common question / problem but have not been able to find a good clean concise answer.
**The Problem**
How to map entities that appear to have an inheritance relationship:
```
Company
Supplier
Manufacturer
Customer
```
However, a Supplier can be a Manufacturer.
or
```
Person
Doctor
Patient
Employee
```
Where a Patient can be a Doctor or can be an Employee.
**Suggestion: Use Roles**
In discussions on the NHibernate forums, the response is often that this is multiple inheritance.
<http://forum.hibernate.org/viewtopic.php?t=959076>
They solution suggested is to use composition or to use "Roles". However, I cannot find any examples or explanation on how exactly to do that.
> "Favor composition over inheritance."
> Remember that little goodie from
> class? In this instance I have to
> agree that you are trying multiple
> inheritance-- not possible in C# or
> Java (yet). I, personally, would
> encourage you to think about
> re-modeling so you have a Person
> object and a person has a one-to-many
> collection of Roles.
|
You probably want to consider using the Roles. So a Role will have a set of Persons. Or a Person will have a set of Roles or both. This would probably imply that there is an Association class that maps persons to roles.
Define a Person class with all properties that are common to people. Then define a Role super class and DoctorRole, PatientRole and EmployeeRole sub classes (Assuming that each role has different properties).
The Person class can have a Collection of roles defined and the Role class can have a Collection of people defined. Or it might be easier to create an Association class, lets call it PeopleRole.
[This](http://www.hibernate.org/hib_docs/nhibernate/html/example-mappings.html) page explains how to do the mapping so that PeopleRole is a composite element. Look at the Order/Product/LineItem example. Your Person is like Order, PeopleRole is like LineItem and Role is like Product.
|
It seems to me that this is more a question around how to model a domain well, rather than an NHibernate mapping issue.
Once you've sorted out your domain modelling, I think you'll find the NHibernate mapping falls out relatively easily.
One place to look to get your head around the idea of modeling Roles is to look for "[Color Modeling](http://en.wikipedia.org/wiki/UML_colors)" - [Jeff de Luca](http://www.nebulon.com/) has [some resources](http://www.nebulon.com/articles/fdd/adsposters.html), though the idea originated with [Peter Coad](http://en.wikipedia.org/wiki/Peter_Coad)
The basic idea is to separate the identity of a participant from the role they play in an activity.
For example, you might have a Person object that captures the identify of a particular person.
Then, a completely separate object "Student" that captures the additional information to record the enrolment of a person as a student. Each instance of Student would have a reference to the person enrolled. A single person may be related to many "Student" records, one for each distinct enrolment.
In parallel, you could have a distinct "Tutor" object that records employment details when someone is hired to teach students in one-on-one situations. The Tutor object captures the additional details around how someone is employed as a tutor.
This structure gives you great flexibility - one person (Joe Bloggs) may just be a student, another person (Jane Doe) may just be a tutor, and a third (Chuck Norris) may be both.
Also, introducing another role (Lecturer, Marker, Administrator) becomes easier because the additions don't require changes to existing objects.
|
How to map classes in NHibernate using Roles or Composition
|
[
"",
"c#",
"nhibernate",
""
] |
When I switch tabs with the following code
```
tabControl1.SelectTab("MyNextTab");
```
It calls the tabPage\_Enter for the tab it is switching from and the tab it is switching to. I want it to be called for the tab it is switching to, but not the tab it is switching from. How would I turn this off. I do know when it happens so if there was a call I could make that would turn off calling the enter method for that tab I could implement that.
|
Yes, I repro if I use a button to change the selected tab. TabControl forces the focus onto itself before it changes SelectedIndex. This appears to have been done to avoid problems with the Validating event. The focus change produces the first Enter event, for the active tab, the tab change then produces the second Enter event.
Knowing this, you could set a helper boolean member, indicating that the first Enter event should be ignored. Be careful to check that the current tab isn't already the one you want to select. In a perfect world, this behavior shouldn't matter. The focus really *did* move to the active tab first.
|
Can you check the index of the active tab and workaround using that?
|
Turn off calling tabPage_Enter method in C#
|
[
"",
"c#",
"winforms",
"tabcontrol",
""
] |
Let's say I have a table that represents a super class, **students**. And then I have N tables that represent subclasses of that object (**athletes**, **musicians**, etc). How can I express a constraint such that a student must be modeled in one (not more, not less) subclass?
Clarifications regarding comments:
* This is being maintained manually, not through an ORM package.
* The project this relates to sits atop SQL Server (but it would be nice to see a generic solution)
* This may not have been the best example. There are a couple scenarios we can consider regarding subclassing, and I just happened to invent this student/athlete example.
A) In true object-oriented fashion, it's possible that the superclass can exist by itself and need not be modeled in any subclasses.
B) In real life, any object or student can have multiple roles.
C) The particular scenario I was trying to illustrate was requiring that every object be implemented in exactly one subclass. Think of the superclass as an abstract implementation, or just commonalities factored out of otherwise disparate object classes/instances.
Thanks to all for your input, especially Bill.
|
Here are a couple of possibilities. One is a `CHECK` in each table that the `student_id` does not appear in any of the other sister subtype tables. This is probably expensive and every time you need a new subtype, you need to modify the constraint in all the existing tables.
```
CREATE TABLE athletes (
student_id INT NOT NULL PRIMARY KEY,
FOREIGN KEY (student_id) REFERENCES students(student_id),
CHECK (student_id NOT IN (SELECT student_id FROM musicians
UNION SELECT student_id FROM slackers
UNION ...))
);
```
**edit:** @JackPDouglas correctly points out that the above form of CHECK constraint is not supported by Microsoft SQL Server. Nor, in fact, is it valid per the SQL-99 standard to reference another table (see <http://kb.askmonty.org/v/constraint_type-check-constraint>).
SQL-99 defines a metadata object for multi-table constraints. This is called an *ASSERTION*, however I don't know any RDBMS that implements assertions.
Probably a better way is to make the primary key in the `students` table a compound primary key, the second column denotes a subtype. Then restrict that column in each child table to a single value corresponding to the subtype represented by the table. **edit:** no need to make the PK a compound key in child tables.
```
CREATE TABLE athletes (
student_id INT NOT NULL PRIMARY KEY,
student_type CHAR(4) NOT NULL CHECK (student_type = 'ATHL'),
FOREIGN KEY (student_id, student_type) REFERENCES students(student_id, student_type)
);
```
Of course `student_type` could just as easily be an integer, I'm just showing it as a char for illustration purposes.
If you don't have support for `CHECK` constraints (e.g. MySQL), then you can do something similar in a trigger.
I read your followup about making sure a row exists in *some* subclass table for every row in the superclass table. I don't think there's a practical way to do this with SQL metadata and constraints. The only option I can suggest to meet this requirement is to use [Single-Table Inheritance](http://martinfowler.com/eaaCatalog/singleTableInheritance.html). Otherwise you need to rely on application code to enforce it.
**edit:** JackPDouglas also suggests using a design based on [Class Table Inheritance](http://www.martinfowler.com/eaaCatalog/classTableInheritance.html). See [his example](https://stackoverflow.com/questions/5522320/what-is-the-best-way-to-enforce-a-subset-relationship-with-integrity-constraint/5522344#5522344) or my examples of the similar technique [here](https://stackoverflow.com/questions/987654/in-a-stackoverflow-clone-what-relationship-should-a-comments-table-have-to-quest/987709#987709) or [here](https://stackoverflow.com/questions/1408556/is-it-possible-to-constrain-a-table-to-have-a-value-in-only-one-of-a-set-of-colum/1408592#1408592) or [here](https://stackoverflow.com/questions/3349838/should-i-add-a-type-column-to-design-inheritance-in-postgresql/3349962#3349962).
|
Each Student record will have a SubClass column (assume for the sake of argument it's a CHAR(1)). {A = Athlete, M=musician...}
Now create your Athlete and Musician tables. They should also have a SubClass column, but there should be a check constraint hard-coding the value for the type of table they represent. For example, you should put a default of 'A' and a CHECK constraint of 'A' for the SubClass column on the Athlete table.
Link your Musician and Athlete tables to the Student table using a COMPOSITE foreign key of StudentID AND Subclass. And you're done! Go enjoy a nice cup of coffee.
```
CREATE TABLE Student (
StudentID INT NOT NULL IDENTITY PRIMARY KEY,
SubClass CHAR(1) NOT NULL,
Name VARCHAR(200) NOT NULL,
CONSTRAINT UQ_Student UNIQUE (StudentID, SubClass)
);
CREATE TABLE Athlete (
StudentID INT NOT NULL PRIMARY KEY,
SubClass CHAR(1) NOT NULL,
Sport VARCHAR(200) NOT NULL,
CONSTRAINT CHK_Jock CHECK (SubClass = 'A'),
CONSTRAINT FK_Student_Athlete FOREIGN KEY (StudentID, Subclass) REFERENCES Student(StudentID, Subclass)
);
CREATE TABLE Musician (
StudentID INT NOT NULL PRIMARY KEY,
SubClass CHAR(1) NOT NULL,
Instrument VARCHAR(200) NOT NULL,
CONSTRAINT CHK_Band_Nerd CHECK (SubClass = 'M'),
CONSTRAINT FK_Student_Musician FOREIGN KEY (StudentID, Subclass) REFERENCES Student(StudentID, Subclass)
);
```
|
Maintaining subclass integrity in a relational database
|
[
"",
"sql",
"sql-server",
"database-design",
"oop",
""
] |
Parts of my application are in C++ under windows. I need the process id for the current process. Any thoughts?
|
The [`GetCurrentProcessId`](http://msdn.microsoft.com/en-us/library/ms683180(VS.85).aspx) function will do this.
|
Having grown accustomed to seeing yards and yards of code to accomplish seemingly straightforward tasks, I was pleasantly surprised at the directness of `GetCurrentProcessId`. Earlier today, I watched it run in a debugger, when I was following a new bit of code in a `DllMain` routine that combines the process ID with an embedded GUID to create a locally unique name for a mutex.
Following is the entire routine, all three machine instructions.
```
mov eax,fs:[00000018]
mov eax,dword ptr [eax+20h]
ret
```
BTW, two other blessedly simple Windows API functions are `GetLastError` and `SetLastError`; indeed, both are quite similar to this one.
|
ms c++ get pid of current process
|
[
"",
"c++",
"windows",
"process",
"pid",
""
] |
If I have the following code:
```
MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass = null;
```
Will pClass be garbage collected? Or will it hang around still firing its events whenever they occur? Will I need to do the following in order to allow garbage collection?
```
MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass.MyEvent -= MyFunction;
pClass = null;
```
|
For the specific question "Will pClass be garbage collected": the event subscription has no effect on the collection of pClass (as the publisher).
For GC in general (in particular, the target): it depends whether MyFunction is static or instance-based.
A delegate (such as an event subscription) to an instance method includes a reference to the instance. So yes, an event subscription will prevent GC. However, as soon as the object publishing the event (pClass above) is eligible for collection, this ceases to be a problem.
Note that this is one-way; i.e. if we have:
```
publisher.SomeEvent += target.SomeHandler;
```
then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.
So no: if pClass is going to be collected anyway, there is no need to unsubscribe the listeners. However, if pClass was long-lived (longer than the instance with MyFunction), then pClass could keep that instance alive, so it *would* be necessary to unsubscribe if you want the target to be collected.
Static events, however, for this reason, are very dangerous when used with instance-based handlers.
|
Yes, `pClass` will be garbage collected. The event subscription does not imply that any reference exists to `pClass`.
So no, you will not have to detach the handler in order for `pClass` to be garbage collected.
|
Do event handlers stop garbage collection from occurring?
|
[
"",
"c#",
".net",
"event-handling",
"garbage-collection",
""
] |
When C# 4.0 comes out and we have the dynamic keyword as described in this [excellent presentation by Anders Hejlsberg](http://channel9.msdn.com/pdc2008/TL16/), (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)
Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?
```
var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
```
|
No, they're very different.
`var` means "infer the type of the variable at compile-time" - but it's still entirely statically bound.
`dynamic` means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls *really* mean at execution time.
I expect to use `dynamic` very rarely - only when I truly want dynamic behaviour:
* `var` lets you catch typos etc at compile-time
* statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)
* statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc
|
Dynamic and var represent two completely different ideas.
**var**
Var essentially asks the compiler to figure out the type of the variable based on the expression on the right hand side of the assignment statement. The variable is then treated exactly as if it were explicitly declared as the type of the expression. For example the following two statements are equivalent
```
var a = "foo";
string a = "foo";
```
The key to take away here is that "var" is 100% type safe and is a compile time operation
**dynamic**
Dynamic is in many ways the exact opposite of var. Using dynamic is essentially eliminating all type safety for thet particular variable. It many ways it has no type. When you call a method or field on the variable, the determination on how to invoke that field occurs at runtime. For example
```
dynamic d = SomeOperation();
d.Foo(); // Will this fail or not? Won't know until you run the program
```
The key to take away here is that "dynamic" is not type safe and is a runtime operation
|
Does the new 'dynamic' C# 4.0 keyword deprecate the 'var' keyword?
|
[
"",
"c#",
"c#-4.0",
"dynamic-languages",
""
] |
Is it possible to create a list that can be access by either an index or a key?
*I am looking for a Collection type that already exists but has this facility, I want to avoid redefining the indexers*
|
System.Collections.Specialized.NameValueCollection can do this, but it can only store strings as values.
```
System.Collections.Specialized.NameValueCollection k =
new System.Collections.Specialized.NameValueCollection();
k.Add("B", "Brown");
k.Add("G", "Green");
Console.WriteLine(k[0]); // Writes Brown
Console.WriteLine(k["G"]); // Writes Green
```
|
There's a similar question at [What is the best data structure in .NET for look-up by string key or numeric index?](https://stackoverflow.com/questions/137753/what-is-the-best-data-structure-in-net-for-look-up-by-string-key-or-numeric-ind).
Have a look at [KeyedCollection](http://msdn.microsoft.com/en-us/library/ms132438.aspx):
```
class IndexableDictionary<TKey, TItem> : KeyedCollection<TKey, TItem>
{ Dictionary<TItem, TKey> keys = new Dictionary<TItem, TKey>();
protected override TKey GetKeyForItem(TItem item) { return keys[item];}
public void Add(TKey key, TItem item)
{ keys[item] = key;
this.Add(item);
}
}
```
|
Built-in List that can be accessed by index and key
|
[
"",
"c#",
"dictionary",
"list",
""
] |
```
SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU
FROM PRACOWNICY
GROUP BY NR_DZIALU
HAVING NR_DZIALU = 30
```
or
```
SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU
FROM PRACOWNICY
WHERE NR_DZIALU = 30
GROUP BY NR_DZIALU
```
|
The theory (by theory I mean [SQL Standard](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt)) says that WHERE restricts the result set before returning rows and HAVING restricts the result set after bringing all the rows. So WHERE is faster. On SQL Standard compliant DBMSs in this regard, only use HAVING where you cannot put the condition on a WHERE (like computed columns in some RDBMSs.)
You can just see the execution plan for both and check for yourself, nothing will beat that (measurement for your specific query in your specific environment with your data.)
|
It might depend on the engine. MySQL for example, applies HAVING almost last in the chain, meaning there is almost no room for optimization. From the [manual](http://dev.mysql.com/doc/refman/5.0/en/select.html):
> The HAVING clause is applied nearly last, just before items are sent to the client, with no optimization. (LIMIT is applied after HAVING.)
I believe this behavior is the same in most SQL database engines, but I can't guarantee it.
|
Which SQL statement is faster? (HAVING vs. WHERE...)
|
[
"",
"sql",
"performance",
"grouping",
"if-statement",
""
] |
Here is the code currently used.
```
public String getStringFromDoc(org.w3c.dom.Document doc) {
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
writer.flush();
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
```
|
Relies on [DOM Level3 Load/Save](http://www.w3.org/TR/DOM-Level-3-LS/load-save.html):
```
public String getStringFromDoc(org.w3c.dom.Document doc) {
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
return lsSerializer.writeToString(doc);
}
```
|
The transformer API is the only XML-standard way to transform from a DOM object to a serialized form (String in this case). As standard I mean SUN [Java XML API for XML Processing](http://en.wikipedia.org/wiki/Java_API_for_XML_Processing).
Other alternatives such as Xerces [XMLSerializer](http://xerces.apache.org/xerces-j/apiDocs/org/apache/xml/serialize/XMLSerializer.html) or JDOM [XMLOutputter](http://www.jdom.org/docs/apidocs/org/jdom/output/XMLOutputter.html) are more direct methods (less code) but they are framework-specific.
In my opinion the way you have used is the most elegant and most portable of all. By using a standard XML Java API you can plug the XML-Parser or XML-Transformer of your choice without changing the code(the same as JDBC drivers). Is there anything more elegant than that?
|
Is there a more elegant way to convert an XML Document to a String in Java than this code?
|
[
"",
"java",
"xml",
""
] |
In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?
|
There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:
```
>>> class Foo( object ):
... def foo( self ):
... print 'FOO!'
...
>>> class Bar( Foo ):
... def foo( self ):
... raise AttributeError( "'Bar' object has no attribute 'foo'" )
...
>>> b = Bar()
>>> b.foo()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 3, in foo
AttributeError: 'Bar' object has no attribute 'foo'
```
|
kurosch's method of solving the problem isn't quite correct, because you can still use `b.foo` without getting an `AttributeError`. If you don't invoke the function, no error occurs. Here are two ways that I can think to do this:
```
import doctest
class Foo(object):
"""
>>> Foo().foo()
foo
"""
def foo(self): print 'foo'
def fu(self): print 'fu'
class Bar(object):
"""
>>> b = Bar()
>>> b.foo()
Traceback (most recent call last):
...
AttributeError
>>> hasattr(b, 'foo')
False
>>> hasattr(b, 'fu')
True
"""
def __init__(self): self._wrapped = Foo()
def __getattr__(self, attr_name):
if attr_name == 'foo': raise AttributeError
return getattr(self._wrapped, attr_name)
class Baz(Foo):
"""
>>> b = Baz()
>>> b.foo() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError...
>>> hasattr(b, 'foo')
False
>>> hasattr(b, 'fu')
True
"""
foo = property()
if __name__ == '__main__':
doctest.testmod()
```
Bar uses the "wrap" pattern to restrict access to the wrapped object. [Martelli has a good talk](http://www.aleax.it/gdd_pydp.pdf) dealing with this. Baz uses [the property built-in](http://docs.python.org/library/functions.html?highlight=property#property) to implement the descriptor protocol for the attribute to override.
|
Python inheritance - how to disable a function
|
[
"",
"python",
"inheritance",
"interface",
"private",
""
] |
Seems a great C++ unit testing framework. I'm just wanting something a bit more sophisticated than the console output for running the test, also something that makes it really easy to run specific tests (since gtest supports all kinds of test filtering)
If there is nothing, I'll probably roll my own
|
I opened a google code project that adds UI to google test. Runs on both Windows and Unix.
It is not a plugin to any IDE by design - I did not want to tie myself. Instead you open it in the background and press the "Go" button whenever you want to run.
As of this writing V1.2.1 is out and you are invited to give it a try.
<https://github.com/ospector/gtest-gbar>
|
According to the project owner, [there isn't](http://groups.google.com/group/googletestframework/browse_thread/thread/af01d964d65c2144). If you do work on one, do post to the project's [group](http://groups.google.com/group/googletestframework). I'm sure there are some folks there who'd like to help.
|
Is there a graphical test runner for "Google Test" ( gtest ) for windows?
|
[
"",
"c++",
"googletest",
""
] |
I have a Flash movie embedded in some DIV. The trouble is that when I change any property of the enclosing DIV dynamically, Firefox (not other browsers) restarts/reinitializes Flash movie effectively resetting the whole progress (eg: file selection for upload, etc.).
Is there some sort of a workaround for this?
|
Try hiding it with `visibility:hidden` or if all else fails, `position:absolute;left:-9999px`.
I presume Firefox doesn't want to waste memory and CPU on Flash animation that's invisible, so it kills it.
|
see <https://bugzilla.mozilla.org/show_bug.cgi?id=90268>
|
Firefox restarts Flash movie if enclosing DIV properties change
|
[
"",
"javascript",
"flash",
"firefox",
""
] |
I have written C# code for ascx. I am trying to send an email on click of image button which works in Mozilla Firefox but not in Internet Explorer.
This function is called on button click:
```
<%@ Control Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Globalization" %>
<script language="c#" runat="server">
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string from = "manoj.singh@espireinfo.com";
string to = "manoj.singh@espireinfo.com";
string subject = "Keep me Updated";
string sendguide = "";
if (optsendguide.Checked)
{
sendguide = "Yes Please send me";
}
else
{
sendguide = "No Please don't send me";
}
// build up the body text
string body = "<html><body>";
body += String.Format("<div>Title: {0} </div>", title.Text);
body += String.Format("<div>First Name: {0} </div>",firstname.Value);
body += String.Format("<div>Sur Name: {0} </div>", surname.Value);
body += String.Format("<div>Email address: {0} </div>", email.Value);
body += String.Format("<div>Break Type: {0} </div>", breakTypeDescription.Text);
body += String.Format("<div>Big weekends guide: {0} </div>", sendguide);
body += "</body></html>";
string error = Utilities.SendEmail(to, from, subject, body);
if (error == "") // success
{
Response.Redirect("index.aspx");
}
else // error
{
Response.Write(error);
}
}
}
</script>
```
Markup:
```
<div class="form_elm_button">
<asp:ImageButton ID="SubmitButton"
runat="server"
Text="Submit"
ImageUrl="/images/17-6164button_submit.png"
OnClick="btnSubmit_Click"
CausesValidation="true"/>
</div>
```
|
hai all,
This code is working in IE not mozilla,anyone give idea
document.onkeypress = KeyCheck;
function KeyCheck(e) {
```
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID == 0) {
var image = document.getElementById("<%= imagetirukural.ClientID%>");
var label = document.getElementById("<%= lbltirukural.ClientID%>");
if (image != null) {
document.getElementById("<%= imagetirukural.ClientID%>").style.display = "block";
InitializeTimer();
}
else {
document.getElementById("<%= lbltirukural.ClientID%>").style.display = "block";
InitializeTimer();
}
}
else if (KeyID != 0) {
if (image != null) {
document.getElementById("<%= imagetirukural.ClientID%>").style.display = "block";
}
else {
document.getElementById("<%= lbltirukural.ClientID%>").style.display = "block";
}
}
}
```
|
In code behind just change
protected void btnSubmit\_Click(object sender, EventArgs e)
with
protected void btnSubmit\_Click(object sender, ImageClickEventArgs e)
|
.net click on image button not working in Internet Explorer but in Firefox
|
[
"",
"c#",
"asp.net",
""
] |
Currently I have a ListView (using the Details View). I would like to implement the behaviour whereby when a user selects a single item (log entry) the log entry expands (from one line to multiple lines) to provide more detailed information about the error that occured.
My question is this: Is this possible? If so, is there a good resource that I can use to help me?
EDIT:
If I *HAVE* to use WPF, then I guess Ill use the ElementHost with the control. However, I have absolutely no idea as to how about designing/coding/using WPF components. Any suggestions?
|
Edit: sorry this is wpf
The trick I used to achieve the same thing was creating a trigger to show a secondary grid which is defaulted to collapsed.
Try this out:
```
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Height="20" >
<TextBlock Text="Not Selected"></TextBlock>
</Grid>
<Grid x:Name="selectedOnlyGrid" Grid.Row="1" Visibility="Collapsed">
<TextBlock Text="Selected"></TextBlock>
</Grid>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}, AncestorLevel=1}, Path=IsSelected}" Value="True">
<Setter Property="Visibility" Value="Visible" TargetName="selectedOnlyGrid" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
|
Have a read through the post on CodeProject Here: [Extended List Box](http://www.codeproject.com/KB/miscctrl/ExtendedListBoxControl.aspx)
Should have all the info you need for it :)
|
c# How can I expand an item within a ListView to occupy multiple lines?
|
[
"",
"c#",
"wpf",
"winforms",
"listview",
""
] |
I create new ASP.NET web application that use SMTP to send message. The problem is the smtp was not authenticated from who send the message.
How can I make SMTP authenticated in my program? does C# have a class that have attribute for enter username and password?
|
```
using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("from@yourdomain.com");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("to@anydomain.com");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
```
You may use the above code.
|
Ensure you set `SmtpClient.Credentials` **after** calling `SmtpClient.UseDefaultCredentials = false`.
The order is important as setting `SmtpClient.UseDefaultCredentials = false` will reset `SmtpClient.Credentials` to null.
|
How can I make SMTP authenticated in C#
|
[
"",
"c#",
"authentication",
"smtp",
""
] |
I have a key that appears to be an empty string, however using `unset($array[""]);` does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.
The line for the element on a print\_r is `[] => 1`, which indicates to me that the key is the empty string.
Using var\_export, the element is listed as `'' => 1`.
Using var\_dump, the element is listed as `[""]=>int(1)`.
So far, I have tried all of the suggested methods of removal, but none have removed the element. I have tried `unset($array[""]);`, `unset($array['']);`, and `unset($array[null]);` with no luck.
|
Try `unset($array[null]);`
If that doesn't work, print the array via `var_export` or `var_dump` instead of `print_r`, since this allows you to see the type of the key. Use `var_export` to see the data in PHP syntax.
`var_export($array);`
Note that var\_export does not work with recursive structures.
|
Tried:
```
$someList = Array('A' => 'Foo', 'B' => 'Bar', '' => 'Bah');
print_r($someList);
echo '<br/>';
unset($someList['A']);
print_r($someList);
echo '<br/>';
unset($someList['']);
print_r($someList);
echo '<br/>';
```
Got:
```
Array ( [A] => Foo [B] => Bar [] => Bah )
Array ( [B] => Bar [] => Bah )
Array ( [B] => Bar )
```
You should analyse where the key come from, too...
|
How do you remove a value that has an empty key from an associative array in PHP?
|
[
"",
"php",
"arrays",
"associative-array",
""
] |
How to figure out if a table is in use in SQL (on any type database)? if somebody is already using it, or have it "open" then its in use.
|
Actually this will give you a better result:
```
select spid
from master..sysprocesses
where dbid = db_id('Works') and spid <> @@spid
```
|
Generally speaking, the correct way to find out whether someone else is using the table and will prevent you from doing whatever you want is to try doing what you want and to check whether it fails. If the failure message indicates 'non-exclusive access' or 'table in use' or equivalent, then you guessed wrong.
If your DBMS supports table locking, you can apply a lock to the table and then do a sequence of operations - but you'll impede other people who might otherwise be trying to use it.
Note that checking in a lock table (such as syslockinfo) is both DBMS-specific and unreliable - it leads to TOCTOU (time of check, time of use) problems.
|
Is the Table in Use?
|
[
"",
"sql",
""
] |
I remember from way back at university using a switch with 'binary search' or 'binary switch'. Something like that, My google foo is broken today. Anyway it goes down like this: You define an array of possible options (Strings usually), some magic happens, and those options in the array become the cases in the switch happens. I do remember that they had to be in alphabetical order for this to work. Can you help me remember the magic? Even a name of what I should be looking at would be fantastic.
|
I think what you are looking for is an [Enum](http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html).
From the link above...
```
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
....
}
```
|
Did you mean gperf? Or possibly you were referring to the theory (hashing) in general?
<http://www.gnu.org/software/gperf/>
|
Array as the options for a switch statment
|
[
"",
"java",
"enums",
"switch-statement",
""
] |
Is there a way to have a function return a editable reference to some internal data. Here's an example I hope helps show what I mean.
```
class foo
{
public int value;
}
class bar
{
bar()
{
m_foo = new foo();
m_foo.value = 42;
}
private m_foo;
foo getFoo(){return m_foo;}
}
class main
{
int main()
{
bar b = new bar();
b.getFoo().value = 37;
}
}
```
The return of getFoo() according to "==" is the same as the internal m\_foo until I try to edit it. In c/c++ I'd return a reference or pointer.
|
Actually, your code sample, after some cleaning up, does demonstrate that when you assign 37 to value, you are changing bar's interman m\_foo too. So the answer is, your function is returning a reference type. Now, maybe your real code is different, and it's returning not an reference type but an int, a value type, or string, a kind of special beastie...
```
using System;
namespace ConsoleApplication1
{
public class foo
{
public int value;
};
public class bar
{
public bar()
{
m_foo = new foo();
m_foo.value = 42;
}
private foo m_foo;
public foo getFoo() { return m_foo; }
};
public class Program
{
public static int Main()
{
bar b = new bar();
b.getFoo().value = 37;
return 0;
}
};
}
```
More about reference vs value types:
<http://www.albahari.com/valuevsreftypes.aspx>
|
You're already returning the reference of `foo` in `getFoo` (this happens by default). So any changes that you make to the return value of `getFoo` will be reflected in the internal `foo` data structure in `bar`.
|
Function which returns reference to be edited in c#
|
[
"",
"c#",
""
] |
I guess it should be a common technique,
However, I tried the following two options:
1) Using my existing POP3 PHP client to access my local mail account. I am getting a "could not connect". Same code works if I run it with my localhost connecting to GoDaddy's pop3 server
2) Parsing the local mbox file - I can't figure out if I can access it, seems like I can't.
Any good ideas of which approach should be best here?
|
Seems like I have this figured out. Shared hosting (GoDaddy specifically) does not allow direct TCP connections anywhere, including their own POP3 server. Looks like I can't be able to access the mbox file directly either. So I figure it is just not going to work.
Thanks all repliers!
Maybe there are OTHER inexpensive shared hosting plans that provide this option...
|
I'd go with the POP3 option. It should work once you get the right port/host etc.
The other option will result in you duplicating a large part of the functionality already in the mail server, and its quite likely you'll have minor bugs in it resulting in emails not displaying properly, or worse, corruption in the mbox.
If you do go with 2, try to find a library for doing the mbox bit!
|
Accessing local mailbox using PHP on a shared hosting Linux account (GoDaddy)
|
[
"",
"php",
"email",
"shared-hosting",
""
] |
I have double (or float) variables that might be "empty", as in holding no valid value. How can I represent this condition with the built in types float and double?
One option would be a wrapper that has a float and a boolean, but that can´t work, as my libraries have containers that store doubles and not objects that behave as doubles. Another would be using NaN (std::numeric\_limits). But I see no way to check for a variable being NaN.
How can I solve the problem of needing a "special" float value to mean something other than the number?
|
In Visual C++, there is a non-standard [`_isnan(double)`](http://msdn.microsoft.com/en-us/library/tzthab44.aspx) function that you can import through `float.h`.
In C, there is a [`isnan(double)`](http://www.opengroup.org/onlinepubs/009695399/basedefs/math.h.html) function that you can import through `math.h`.
In C++, there is a isnan(double) function that you can import through `cmath`.
As others have pointed out, using NaN's can be a lot of hassle. They are a special case that has to be dealt with like NULL pointers. The difference is that a NaN will not usually cause core dumps and application failures, but they are extremely hard to track down. If you decide to use NaN's, use them as little as possible. Overuse of NaN's is an offensive coding practice.
|
We have done that by using NaN:
```
double d = std::numeric_limits<double>::signaling_NaN();
bool isNaN = (d != d);
```
NaN values compared for equality against itself will yield false. That's the way you test for NaN, but which seems to be only valid if `std::numeric_limits<double>::is_iec559` is true (if so, it conforms to ieee754 too).
In C99 there is a macro called `isnan` for this in `math.h`, which checks a floating point number for a NaN value too.
|
Float or Double Special Value
|
[
"",
"c++",
"floating-point",
"double",
""
] |
This is for my DB class. I am new to OO, been a procedural lad for some time, so I'm still a bit murky.
My first idea was using a bunch of setter functions/methods.. but after writing a whole bunch, I thought about using PHP's define function, like so.
```
define('MYSQL_USERNAME', 'jimbo');
```
Is this an accepted practice? What is the best practice? Should I really clutter my class with a bunch of setter functions (I am currently the only developer using these classes). What are your solutions?
Thank you!
|
I use `const` only for creating mnemonic names for immutable constants in the class. The `define()` function does not create constants as part of the class, it creates constants in the global space.
```
class MyClass
{
const CONFIG_FILE = 'myapp.ini';
```
Class configuration data I usually declare as a `protected` hash-array in the class. Keys are useful for mnemonics. Values are defaults.
```
protected $config = array(
'logfile' => 'err.out',
'debug' => false
);
```
Then I load an "ini" format file with `parse_ini_file()` and use `array_merge()` to map the keys into your class config array:
```
public function __construct() {
$ini_data = parse_ini_file(self::CONFIG_FILE, __CLASS__);
$this->config = array_merge($this->config, $ini_data);
}
}
```
|
there are probably a few options to deal with this:
1. just use setters, it's perfectly acceptable, but can get a bit "wordy" with a lot of config options.
2. use a config object to pass in:
```
$config = (object) array(
'prop1' => 'somevalue',
'prop2' => 'somevalue2',
'prop3' => 'somevalue3',
);
$db = new DB($config);
```
3. if you want to use constants, you could restrict them to the class to avoid global namespace pollution:
```
class DB {
const USER = 'mysqluser';
}
echo DB::USER; // for example
```
|
What is the best way to get config variables into a class in php 5?
|
[
"",
"php",
"oop",
""
] |
Is there any way to follow a URL in JavaScript without setting the `document.location.href`?
I have a page that displays a list of objects and each object may have a file download associated with it, which is accessed via a hyperlink. Clicking the link initiates an AJAX request that ultimately leads to a transient file being generated that can be referenced by a unique and temporary URL.
At the moment when the AJAX call completes, it simply sets the `document.location.href` to the temporary URL and the file download is initiated. Of course this has the side effect of changing the URL in the browser's address bar, so if the page is refreshed the file is downloaded again rather than the object listing page itself getting refreshed. I guess I could set the URL back to what it was before, but that feels a bit hacky.
Incidentally, I'm using the Prototype JavaScript framework.
|
you could open a new window with the new url? or try setting an iframe's url to the new url, both should present a file download (the latter being the better option)
|
You could use a hidden iframe - set the src of that to the file to download.
|
Follow a URL using JavaScript
|
[
"",
"javascript",
"ajax",
""
] |
I've just started building a prototype application in Django. I started out by working through the [Django app tutorial on the Django site](http://docs.djangoproject.com/en/dev/intro/tutorial01/) which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions:
I want to put a loop into views.py, looping over a set of variables that have been passed in from a form. So I have a load of items in the HTML form, each of which has a SELECT drop-down list for people to select a score from 0-10, like this:
```
<select name="score1">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
```
So I have, let's say, 100 of these variables, score1, score2, score3, ..., score99, score100. When the form is submitted, I want to loop through each of these variables and see if it's been set (i.e. is not 0) and if so, I want to store that value in a suitable place in the database. My problem is that I can't figure out how to loop through those variables.
I'm guessing that I want something like this:
```
for o in request.POST.all
endfor
```
but then I'm really not sure what to do with that.
I'm not looking for someone to write the code for me, really: I just would like some guidance on how to write a loop like this in python / Django, and also maybe some pointers as to a good reference guide I can either see online or buy that will give me access to this kind of thing.
Also, the select object above I created pretty much by hand, and I'd really like to be able to ue a loop to generate it in the template in the first place. My template currently has this:
```
<table>
{% for movie in movie_list %}
<tr>
<td> {{ movie }} </td>
<td>
<select name="score{{ movie.id }}">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
</td></tr>
{% endfor %}
</table>
```
I feel like there must be a way to create a simple loop that counts from 1 to 10 that would generate most of those options for me, but I can't figure out how to do that...
|
You need to look at the Django [forms](http://docs.djangoproject.com/en/dev/topics/forms/#topics-forms-index).
You should never build your own form like that.
You should declare a Form class which includes a [ChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield) and provide the domain of choices to that field. Everything will happen pretty much automatically from there.
The choices, BTW, should be defined in your Model as the range of values for that Model field.
Your page merely includes `{{form}}`. Django builds the form with the choices and decodes the choices to a final result.
|
> I feel like there must be a way to
> create a simple loop that counts from
> 1 to 10 that would generate most of
> those options for me, but I can't
> figure out how to do that...
If you don't want to use Django forms (why btw?), check out this [custom range tag](http://www.djangosnippets.org/snippets/779/) or just pass a range(1, 11) object into your template and use it in the `{% for %}` loop.
|
Looping in Django forms
|
[
"",
"python",
"django",
""
] |
If I put a DateTime value into an Excel cell using `Range.set_value` through .Net COM Interop, and then retrieve the value of that same cell using `Range.get_value`, the Millisecond part of the value is not returned, though everything else is correct.
Is this a bug?
What is the workaround? I'm guessing that using the Value2 property instead might help. Has anybody else tried this?
|
As [Jon suggested](https://stackoverflow.com/questions/298458/milliseconds-missing-when-getting-a-datatime-value-from-excel-using-net-interop#298467), converting the DateTime to a double using DateTime.ToOADate (then back again using DateTime.FromOADate) works if you set the value using the Range.Value2 property.
The only trouble with this property is that, if you don't already know, it doesn't tell you that the cell is supposed to be treated as a DateTime. I guess to solve this, you'd need to use a two-pass approach: get cell values using Range.get\_Value to determine their type, then, for any DateTime cells, get their values again using Range.Value2, then convert using DateTime.FromOADate.
|
If you set a date/time with a millisecond value in Excel manually, does it maintain it? I don't know about the Excel internal object model, but it's conceivable that it just doesn't support milliseconds.
EDIT: Okay, now we know that the set fails (the get may also fail, of course)... you could try setting it as a double after converting it via [DateTime.ToOADate()](http://msdn.microsoft.com/en-us/library/system.datetime.tooadate.aspx). I'm not saying I'm holding out *much* hope, but it's worth a try...
|
Milliseconds missing when getting a DateTime value from Excel using .Net Interop
|
[
"",
"c#",
".net",
"excel",
"com-interop",
""
] |
in javascript, when I receive a focus event, how can I work out which element has lost focus? I'm trying to avoid having to put an onblur event handler on all elements within my web page.
|
@pbrodka: the target/srcElement property would refer to the element with focus for onfocus events
offhand I can't see a way to get this short of onblur, or if the set of objects you care about all have focus methods you could store a reference to that object instead. It's also possible event bubbling could get you out of jail
this all feels like a bit of a code smell though - perhaps you need to describe the problem in more detail
|
Difficult this. You cannot use event delegation to find out which control last produced a blur as focus/blur do not bubble up. There have been some attempts to 'fix' this but they are buggy and not resiliant cross browser.
Could I ask you why do you need this information as maybe there is an alternative solution.
|
which HTML element lost focus?
|
[
"",
"javascript",
"focus",
""
] |
I want to close a System.Windows.Forms.Form if the user clicks anywhere outside it. I've tried using IMessageFilter, but even then none of the messages are passed to PreFilterMessage. How do I receive clicks outside a form's window?
|
With thanks to [p-daddy](https://stackoverflow.com/users/36388/p-daddy) in [this question](https://stackoverflow.com/questions/298626/what-do-these-wndproc-codes-mean), I've found this solution which allows me to use ShowDialog:
```
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.Capture = true;
}
protected override void OnCaptureChanged(EventArgs e)
{
if (!this.Capture)
{
if (!this.RectangleToScreen(this.DisplayRectangle).Contains(Cursor.Position))
{
this.Close();
}
else
{
this.Capture = true;
}
}
base.OnCaptureChanged(e);
}
```
|
In your form's Deactivate event, put "this.Close()". Your form will close as soon as you click anywhere else in Windows.
Update: I think what you have right now is a Volume button, and inside the Click event you create an instance of your VolumeSlider form and make it appear by calling ShowDialog() which blocks until the user closes the popped-up form. In the next line you read the volume the user selected and use it in your program.
This is OK, but as you've noticed it forces the user to explicitly close the popup in order to get back to the main program. Show() is the method you really want to use here on your popup form, but Show() doesn't block which means the Click event back on your main form finishes without knowing what the new volume is supposed to be.
A simple solution is to create a public method on your main form like this:
```
public void SetVolume(int volume)
{
// do something with the volume - whatever you did before with it
}
```
Then, in your Volume button's Click event (also on the main form), you make the VolumeSlider appear like so:
```
VolumeSlider slider = new VolumeSlider();
slider.Show(this); // the "this" is needed for the next step
```
In the VolumeSlider form, as the user works the (I guess) scrollbar, you put this code in the scrollbar's ValueChanged event (I think that's what it is):
```
MainForm owner = (MainForm)this.Owner;
owner.SetVolume(scrollbar.Value);
```
And then in the VolumeSlider form's Deactivate event you would put this.Close() as mentioned above. Your form will then behave as expected.
|
How do I close a form when a user clicks outside the form's window?
|
[
"",
"c#",
"forms",
"click",
""
] |
As the title really, I'm in one part of my code and I would like to invoke any methods that have been added to the Button.Click handler.
How can I do this?
|
Do you mean you need to access it from elsewhere in your code? It may be an idea to refactor that section to it's own method then call that method whenever you need to access it (including in the Click event)
|
AVOID. Really. Seems like you handle some important logic right in the event handler.
Move the logic out of the handler.
|
How can I invoke (web) Button.Click in c#?
|
[
"",
"c#",
".net",
"asp.net",
"events",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.