Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I need to store fixed-length (up to 8 digits) numbers produced from a variable length strings. The hash need not be unique. It just needs to change when input string changes. Is there a hash function in .Net that does this?
Thanks
Kishore. | I assume you are doing this because you need to store the value elsewhere and compare against it. Thus Zach's answer (while entirely correct) may cause you issues since the contract for String.GetHashCode() is explicit about its scope for changing.
Thus here is a fixed and easily repeatable in other languages version.
I assume you will know at compile time the number of decimal digits available.
This is based on the Jenkins One At a Time Hash (as implemented and [exhaustively tested](https://web.archive.org/web/20120722074148/http://bretm.home.comcast.net/%7Ebretm/hash/) by Bret Mulvey), as such it has excellent avalanching behaviour (a change of one bit in the input propagates to all bits of the output) which means the somewhat lazy modulo reduction in bits at the end is not a serious flaw for most uses (though you could do better with more complex behaviour)
```
const int MUST_BE_LESS_THAN = 100000000; // 8 decimal digits
public int GetStableHash(string s)
{
uint hash = 0;
// if you care this can be done much faster with unsafe
// using fixed char* reinterpreted as a byte*
foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s))
{
hash += b;
hash += (hash << 10);
hash ^= (hash >> 6);
}
// final avalanche
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
// helpfully we only want positive integer < MUST_BE_LESS_THAN
// so simple truncate cast is ok if not perfect
return (int)(hash % MUST_BE_LESS_THAN);
}
``` | Simple approach (note that this is [platform-dependent](http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx)):
```
int shorthash = "test".GetHashCode() % 100000000; // 8 zeros
if (shorthash < 0) shorthash *= -1;
``` | Fixed Length numeric hash code from variable length string in c# | [
"",
"c#",
".net-3.5",
"hash",
""
] |
How does URL rewriting affect the `$_GET` parameter for PHP?
Say I have a URL like `http://example.com/index.php?p=contact` and I use `$_GET['p']` to tell `index.php` to serve the contact page. If I use a rewrite rule that converts the URL to `http://example.com/contact`, will `$_GET['p']` still work as expected?
If it does, could you elaborate on why it works? If not, what strategies could be used to solve the problem so that the page will work both with and without the rewrite? | Yes, that will work as expected. | I'd amend Grant's answer to "Yes, that will work *mostly* as expected."
Specifically, `mod_rewrite`'s behavior with regards to existing query strings can be surprising. As an example, let's take the following rule, which converts the URL you supplied:
```
RewriteRule /contact /index.php?p=contact
```
This will correctly rewrite `/contact` to `/index.php?p=contact` and the page name will be accessible through `$_GET['p']`. However, if you use this technique with a script that uses parameters other than the page name, it gets slightly trickier. This rule also translates `/contact?person=Joe` to `/index.php?p=contact`. The `person=Joe` parameter disappears entirely! There are two ways to deal with this.
The simplest way is to use the `[QSA]` ("query string append") flag on your rule, which will place the original query string *after* the parameters supplied in the rule, translating `/contact?person=Joe` to `/index.php?p=contact&person=Joe`:
```
RewriteRule /contact /index.php?p=contact [QSA]
```
However, this makes it possible for your `p=` parameter to get overwritten. Visiting `/contact?p=about` will get rewritten to `/index.php?p=contact&p=about`, so `$_GET['p']` will return "about" in your script, not "contact". To resolve this, use the `QUERY_STRING` variable instead:
```
RewriteRule /contact /index.php?%{QUERY_STRING}&p=contact
```
This guarantees that `$_GET['p']` will **always** return "contact" when using this rule, regardless of whether your visitors are messing with your URLs. :-) | $_GET and URL Rewriting for PHP | [
"",
"php",
"url-rewriting",
"url-routing",
"friendly-url",
""
] |
If a column is null, does that affect the space used by the column?
Is the space used fixed by the column definition?
Does this vary from database to database.
(I am mainly interestred in SQL Server 2000.)
Clarification:
The question relates not to what happens when the column is 'nullable' (This costs another bit as Kritsen & gbn pointed out). The question is, is there any saving when the column is actually null (in some particular row).
...
Cadaeic provided the answer for SQL Server which seems to be no savings in SQL Server until version 2008, whereas according to Quassnoi you can get savings in Oracle if the null columns are at the end. Thanks for the answers, they were all helpful. | Storing a NULL in a column does not specifically cost or save space. For fixed-length data, the entire space is still reserved.
On the other hand, variable-length data requires only the length of the data plus overhead to store the actual length. For example, a VARCHAR(n) will use 2 bytes of data to indicate that actual length, so the storage space required is always n+2.
Additionally, it should be mentioned that if SET ANSI\_PADDING ON, a char(n) with a NULL value will behave as a VARCHAR(n).
No matter what, you will not recognize space "savings" from storing NULLs when using SQL Server 2000 or SQL Server 2005. SQL Server 2008 introduces the concept of a sparse column, which can yield savings for columns that are primarily NULL. | SQL Server has a Bit to indicate NULL. There is no such bit used if the column is defined as NOT NULL
VARCHAR uses variable length to store data (and thus has overhead of indicating how long the actual data is), whereas CHAR is fixed width.
So on that basis a CHAR(1) NOT NULL is "shorter" than a VARCHAR(1) NOT NULL as VARCHAR needs a length indicator, and CHAR will always use just one byte.
EDIT: Note that having a BIT field that allows NULL requires two bits to store it! I often see BIT fields where this has not been considered, don't need to store NULL but have not been set to NOT NULL so are wasting a bit unintentionally | Space used by nulls in database | [
"",
"sql",
"sql-server",
"database",
"null",
""
] |
I'd like to make use of `ProgressMonitor`'s functionality but I don't want to give the user the option of canceling the action. I know if I don't call `isCanceled()` then the button press has no effect, but I'd prefer not to have the user believe the program is unresponsive.
How shall I go about doing this? | You can't. Make your own dialog using a JProgressBar, as described in [The Java Tutorial](http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html). | I don't know why all ProgressMonitor fields are private. Probably not Mr. Godsling's proudest creation :)
```
* @author James Gosling
* @author Lynn Monsanto (accessibility)
* @version 1.37 04/12/06
```
Just clone it, along with some package private stuff from Swing, then you can do whatever you want, like add a flag for cancelability, and use it in ProgressOptionPane's constructor.
---
(UPDATE) If you can't derive JDK code under SCSL, then here is a devious way to get hold of the JDialog, then you can do anything you want, including removing the Cancel button:
```
progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this,
"Running a Long Task",
"", 0, 100);
progressMonitor.setMillisToDecideToPopup(0);
progressMonitor.setMillisToPopup(0);
progressMonitor.setProgress(0);
JDialog dialog = (JDialog)progressMonitor.getAccessibleContext().getAccessibleParent();
JOptionPane pane = (JOptionPane)dialog.getContentPane().getComponent(0);
pane.setOptions(new Object[]{});
```
It's ugly, and it's totally dependent on ProgressMonitor's implementation. So you should check for ClassCastException and null.
Why do you need to set both time periods to 0? Otherwise the dialog is not created in setProgress. | How do I disable the Cancel Button when using javax.swing.ProgressMonitor? | [
"",
"java",
"swing",
""
] |
What are the recommended steps for creating scalable web/enterprise applications in Java and .NET? I'm more interested in what it takes to go from a low volume app to a high volume one (assuming no major faults in the original architecture). For example, what are the options in each platform for clustering, load-balancing, session management, caching, and so on. | Unfortunately there are a lot of aspects of your question that are going to be context dependant. Scalability can mean different things depending on your requirements and the application. The questions that need answering as you come up with your architecture (regardless of the technology you are using) include:
* For example do you want to support users working with very large amounts of data or do you simply need to support a large number users each working with relative modest amounts of data?
* Does your application do more reading than writing, since reads are cheap and writes are expensive a read heavy application can be simpler to scale than a write heavy one.
* Does the data in your application have be always consistent or will eventual consistency suffice? Think posting a message to a social networking site versus withdrawing money from a bank account).
* How available does you application need to be? Strict high availability requirements will probably require you to have smooth fail-over to other servers when one server crashes.
There are many other questions like this that need to be answered about your specific application before a proper discussion on your application architecture can take place.
However so I don't just leave you questions and not a single answer here is what I think is the single most important thing to take into account when designing a web application for scalability: **Reduce (down to zero if possible) the amount of shared session state in your application (global application counters, cached primary key blocks and the like). Replicating shared state across a cluster has a very high cost, when you are trying to scale up** | Perhaps there is so many options, I am not sure anyone to considered all options in full. Usually, the choice of language comes first and then you decide how to achieve the results you want.
My guess is you have good options in just about any major general purpose language.
This would have been an issue 10 years ago, but not today IMHO.
A good comparison of available open source technologies in Java is <http://java-sources.org/> As you drill down into each category, you can see this is fairly extensive and it does even consider commercial products or C#
For any scalable system, you need to consider hardware solutions as well, such as network components.
My suggestion for turning a low volume app into a high volume one, is start with something fairly high volume in the first place and expect to re-engineer it as you go.
What sort of volumes are you talking about? Everyone has different expectations of high and low volume. e.g. When google have lower than average volumes they switch of whole data centres to save power. ;) | Comparing scalable web-app architecture on Java and .NET | [
"",
"java",
".net",
"architecture",
"scalability",
""
] |
I have some questions on using `std::map`:
1. Is using an `enum` as the key in `std::map` a good practice? Consider the following code:
```
enum Shape{
Circle,
Rectangle
};
int main(int argc, char* argv[])
{
std::map<Shape,std::string> strMap;
// strMap.insert(Shape::Circle,"Circle"); // This will not compile
strMap[Shape::Circle] = "Circle"; // But this will work
return 0;
}
```
2. In the above example, why is the call to `insert()` generating a compiler error while the overloaded `[]` operator works correctly? Which of these methods is recommended for inserting items into a `std::map`?
3. I understand that when the `find()` method is used on the `std::map` class, it is not doing a sequential search in the container but doing some logarithmic search which will be much faster than sequential search. Is this understanding correct? | 1. Having an enum as key\_type is not bad by itself. (**edit**) But if you only use sequential enum-values, a `std::vector` with O(1) access is even better.
2. `insert` must be used like this: `mapVar.insert(make_pair(key, value));`
See also [cppreference.com](http://www.cppreference.com/wiki/stl/map/insert).
3. Yes, `std::map` has O(log(n)) lookup, as guaranteed by the standard, and this is faster than O(n) if n is sufficiently high. | Insert fails because the value\_type is std::pair | Are these appropriate practices when working with std::map? | [
"",
"c++",
"enums",
"dictionary",
"standard-library",
""
] |
In the two following snippets, is the first one safe or must you do the second one?
By safe I mean is each thread guaranteed to call the method on the Foo from the same loop iteration in which the thread was created?
Or must you copy the reference to a new variable "local" to each iteration of the loop?
```
var threads = new List<Thread>();
foreach (Foo f in ListOfFoo)
{
Thread thread = new Thread(() => f.DoSomething());
threads.Add(thread);
thread.Start();
}
```
-
```
var threads = new List<Thread>();
foreach (Foo f in ListOfFoo)
{
Foo f2 = f;
Thread thread = new Thread(() => f2.DoSomething());
threads.Add(thread);
thread.Start();
}
```
**Update:** As pointed out in Jon Skeet's answer, this doesn't have anything specifically to do with threading. | Edit: this all changes in C# 5, with a change to where the variable is defined (in the eyes of the compiler). From **C# 5 onwards, they are the same**.
---
**Before C#5**
The second is safe; the first isn't.
With `foreach`, the variable is declared **outside** the loop - i.e.
```
Foo f;
while(iterator.MoveNext())
{
f = iterator.Current;
// do something with f
}
```
This means that there is only 1 `f` in terms of the closure scope, and the threads might very likely get confused - calling the method multiple times on some instances and not at all on others. You can fix this with a second variable declaration *inside* the loop:
```
foreach(Foo f in ...) {
Foo tmp = f;
// do something with tmp
}
```
This then has a separate `tmp` in each closure scope, so there is no risk of this issue.
Here's a simple proof of the problem:
```
static void Main()
{
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in data)
{
new Thread(() => Console.WriteLine(i)).Start();
}
Console.ReadLine();
}
```
Outputs (at random):
```
1
3
4
4
5
7
7
8
9
9
```
Add a temp variable and it works:
```
foreach (int i in data)
{
int j = i;
new Thread(() => Console.WriteLine(j)).Start();
}
```
(each number once, but of course the order isn't guaranteed) | Pop Catalin and Marc Gravell's answers are correct. All I want to add is a link to [my article about closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx) (which talks about both Java and C#). Just thought it might add a bit of value.
EDIT: I think it's worth giving an example which doesn't have the unpredictability of threading. Here's a short but complete program showing both approaches. The "bad action" list prints out 10 ten times; the "good action" list counts from 0 to 9.
```
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
List<Action> badActions = new List<Action>();
List<Action> goodActions = new List<Action>();
for (int i=0; i < 10; i++)
{
int copy = i;
badActions.Add(() => Console.WriteLine(i));
goodActions.Add(() => Console.WriteLine(copy));
}
Console.WriteLine("Bad actions:");
foreach (Action action in badActions)
{
action();
}
Console.WriteLine("Good actions:");
foreach (Action action in goodActions)
{
action();
}
}
}
``` | The foreach identifier and closures | [
"",
"c#",
"enumeration",
"closures",
""
] |
I have a program that send a document to a pdf printer driver and that driver prints to a particular directory. After the print I want to attach the pdf to an e-mail (MailMessage) and send it off.
Right now, I send the document to the printer (wich spawns a new process) and then call a FileSystemWatcher.WaitForChanged(WaitForChangedResult.Created) but when the object is created, it's still not done "printing" and the pdf printer still has a lock on it, throwing an error when I try to attach that file to an e-mail.
* I've considered a plain Thread.Sleep(2000) or whatever, but that's far less than ideal.
* I considered putting the attachment code in a try/catch block and looping on failure, but again, that's just bad news.
I can't really think of an elegant solution. | WaitForChanges is *waiting for the created event* as you have it coded. As the document is being created, you get notified: this does not mean that the file is fully written and the lock removed.
Sadly, I don't know of a good solution other than polling the file periodically. If there was a "all locks removed" event, you could use that, but there isn't.
I just checked our PDF dump to directory code, and we only use WaitForChanges to detect the start of a new file. We then use an try {} catch {} where the catch (failing to get rights over the file) resubmits the attempt into the queue we maintain: each attempt "backs off" for longer, so the first try is 1 second after we detected the file, the second is 2 seconds later, then 4, 8, etc. This reduces the number retries on large files while still being fairly responsive to shorter files. | Well, as long as the watcher is watching the file and letting you know whenever it's changed, you can just ignore the change notifications that occur while the files is still locked (still being written) and wait for the ultimate change notification which would signal the last write event, after which the file should be accessible (at which point you could finally disable the watch).
Other than that I'm not sure what you can do, because the watcher has no "file closed" event AFAIK. | FileSystemWatcher.WaitForChanged returns, but there is still a lock on the file | [
"",
"c#",
"filesystemwatcher",
"file-locking",
""
] |
Can I dynamically create a function and invoke it (passing values into it) in one line of code?
Clarification:
I was looking for some way that could allow me to create an anonymous function and then calling it directly. Sort of:
```
delegate(string aa){ MessageBox.show(aa); }("Hello World!");
```
or something like that (I know the above code does not compile, but I wanted something close). | ```
new Action<int>(x => Console.WriteLine(x))(3);
```
it's not so readable but answering your question, you definitely can.
EDIT: just noticed you tagged it as c# 2.0, the answer above is for 3.5, for 2.0 it would be
```
new Action<int>(delegate(int x) { Console.WriteLine(x); })(3);
``` | The `.Invoke` is actually not needed; you can just write:
```
new Action<int>(x => Console.WriteLine(x))(3);
```
or for C# 2.0:
```
new Action<int>(delegate(int x) { Console.WriteLine(x); })(3);
``` | Create a function and call it in one line of C# code | [
"",
"c#",
"delegates",
"c#-2.0",
""
] |
I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.
The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either. | This answer is similar in spirit to Douglas Leeder's, with the following changes:
* It doesn't use actual Base64, so there's no padding characters
* Instead of converting the number first to a byte-string (base 256), it converts it directly to base 64, which has the advantage of letting you represent negative numbers using a sign character.
```
import string
ALPHABET = string.ascii_uppercase + string.ascii_lowercase + \
string.digits + '-_'
ALPHABET_REVERSE = dict((c, i) for (i, c) in enumerate(ALPHABET))
BASE = len(ALPHABET)
SIGN_CHARACTER = '$'
def num_encode(n):
if n < 0:
return SIGN_CHARACTER + num_encode(-n)
s = []
while True:
n, r = divmod(n, BASE)
s.append(ALPHABET[r])
if n == 0: break
return ''.join(reversed(s))
def num_decode(s):
if s[0] == SIGN_CHARACTER:
return -num_decode(s[1:])
n = 0
for c in s:
n = n * BASE + ALPHABET_REVERSE[c]
return n
```
---
```
>>> num_encode(0)
'A'
>>> num_encode(64)
'BA'
>>> num_encode(-(64**5-1))
'$_____'
```
---
A few side notes:
* You could (*marginally*) increase the human-readibility of the base-64 numbers by putting string.digits first in the alphabet (and making the sign character '-'); I chose the order that I did based on Python's urlsafe\_b64encode.
* If you're encoding a lot of negative numbers, you could increase the efficiency by using a sign bit or one's/two's complement instead of a sign character.
* You should be able to easily adapt this code to different bases by changing the alphabet, either to restrict it to only alphanumeric characters or to add additional "URL-safe" characters.
* I would recommend *against* using a representation other than base 10 in URIs in most cases—it adds complexity and makes debugging harder without significant savings compared to the overhead of HTTP—unless you're going for something TinyURL-esque. | All the answers given regarding Base64 are very reasonable solutions. But they're technically incorrect. To convert an integer to the *shortest URL safe string* possible, what you want is base 66 (there are [66 URL safe characters](https://www.rfc-editor.org/rfc/rfc3986#section-2.3)).
That code looks something like this:
```
from io import StringIO
import urllib
BASE66_ALPHABET = u"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~"
BASE = len(BASE66_ALPHABET)
def hexahexacontadecimal_encode_int(n):
if n == 0:
return BASE66_ALPHABET[0].encode('ascii')
r = StringIO()
while n:
n, t = divmod(n, BASE)
r.write(BASE66_ALPHABET[t])
return r.getvalue().encode('ascii')[::-1]
```
Here's a complete implementation of a scheme like this, ready to go as a pip installable package:
<https://github.com/aljungberg/hhc> | How to convert an integer to the shortest url-safe string in Python? | [
"",
"python",
"url",
"base64",
""
] |
Can anyone point me a good resource or explain me about the concept behind Class Loaders? I found the following resource on class loaders <http://www.onjava.com/lpt/a/5586> but still no help. The following questions may look silly but trying to answer them always confuses me.
* Why do developers write Custom class loaders, why not invoke a Bootstrap class loader to invoke your custom classes? What is the need to define custom class loaders?
* Why there are so many varieties of class loaders? eg: Bootsrap, Comman, Catalina class loader etc.,
Thanks in advance. | I found the following, valid reasons to create custom classloaders:
1. You want to load a class from an unconventional source (For example, the bytecode for one class is stored in a database, across the network or [carried as 0 and 1s by pidgeons](http://www.ietf.org/rfc/rfc1149.txt?number=1149) - MessengerPidgeonClassLoader). There is some ClassLoader implementations already in the API for such cases, such as [URLClassLoader](http://java.sun.com/j2se/1.4.2/docs/api/java/net/URLClassLoader.html).
2. You need to define a different hierarchy to load classes. Default implementations of the ClassLoader delegate the search first to the parent, then they try to load the class themselves. Maybe you want a different hierarchy. This is the reason why OSGI and Eclipse have its own ClassLoaders as the Manifest .MF files define all types of weird hierarchy paths (buddy-classloading, for example). All Eclipse classloaders implement the BundleClassLoader interface and have some extra code to find resources within Eclipse Plugins.
3. You need to do some modification to the bytecode. Maybe the bytecode is encrypted, and you will unencrypt it on the fly ([Not that it helps, really, but has been tried](http://www.javaworld.com/javaworld/javaqa/2003-05/01-qa-0509-jcrypt.html)). Maybe you want to "patch" the classes loaded on the fly (A la JDO bytecode enhancement).
Using a different classloader than the System Classloader is required if you need to unload classes from memory, or to load classes than could change their definition at runtime. A typical case is an application that generates a class on the fly from an XML file, for example, and then tries to reload this class. Once a class is in the System Classloader, there is no way to unload it and have a new definition. | A common use of classloaders is to isolate a JAR. If you have an application which uses plugins ([Eclipse](http://www.eclipse.org/), [Maven 2](http://maven.apache.org/)), then you can have this situation: Plugin X needs jar A with version 1.0 while plugin Y need the same jar but version 2.0. X does not run with version 2.0, though.
If you have classloaders, you can create partitions of classes (think of isolated islands connected by thin bridges; the bridges are the classloaders). This way, the classloaders can control what each plugin can see.
When plugin X instantiates a class Foo, which has static fields, this is no problem and there won't be a mixup with the "same" class in plugin Y because each classloader will in fact create its own instance of the class Foo. You then have two classes in memory, where `cl1.getName().equals(cl2.getName())` is `true` but `cl1.equals(cl2)` is not. This means that instances of cl1 are not assignment compatible to instances of cl2. This can lead to strange `ClassCastExceptions` which say that `org.project.Foo` can't be assigned to `org.project.Foo`.
Just like with remote islands, the two classes are not aware that the other one exists. Think of human clones which are born and then raised on different islands. From the point of view of the VM, there is no problem because instances of the type Class are handled like any other object: There can be several of them. That you think that some of them are "the same" doesn't matter to the VM.
Another use for this pattern is that you can get rid of classes loaded this way: Just make sure that no one has a pointer to any object created from classes loaded from a classloader and then forget about the classloader, too. On the next run of the [GC](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)), all classes loaded by this classloader are removed from memory. This allows you to "reload" your application without having to restart the whole VM. | Java Class Loaders | [
"",
"java",
"classloader",
"dynamic-class-loaders",
""
] |
trying to do some Android development, which means Eclipse, however, most of my experience is Microsoft tools (*e.g. Visual Studio*). My java experience is mostly either Blackberry dev in the *JDE* and some miscellaneous stuff back in the *Java 1.0* days.
My question is this. In VS200x, there is a `.sln` (solution), `.csproj`(project), etc...
What are the equivalent file extensions for Eclipse? Do they even exist? I am having trouble with the basics, like how does one load a project into a **workspace**.
* Is there a tutorial for Microsoft refugees somewhere? | You need to use file import and then choose Existing projects into workspace.
A .project file and a .classpath file will be created.
I find the Eclipse way of working to be incredibly frustrating having come from Delphi/JBuilder where a single project file held all your settings.
Make sure that you back up your workspace as well - there is nothing worse than recreating it when you are under pressure! | Have a look [here](http://www.ibm.com/developerworks/opensource/library/os-eclipse-visualstudio/?ca=dgr-lnxw06Eclipse-VS) for "An introduction to Eclipse for Visual Studio users"...
Basically, for Java program (I never done any Android development) the basic Eclipse configuration files for a project are a .classpath (defining the dependencies of your project), and a .project file, that contains all specificities to your project configuration. In addition to that, a .settings directory is created, which contains some configuration files for plugins activated on your project.
Edit:
Eclipse is the most used IDE for the Java development. However, the **best** IDE is [JetBrains IntelliJ IDEA](http://www.jetbrains.com/idea/). I see that there is a plugin for it to develop Android applications ([here](http://code.google.com/p/idea-android/)). If you can affort this wonderful application ($249), you will not regret it! You may eventually try the free 30 days trial... | Eclipse eye for a Visual Studio guy | [
"",
"java",
"android",
"visual-studio",
"eclipse",
""
] |
We have an application in which admin members can add content for their subordinates to view. Their requirement is that it should be able to display Word, Excel, PowerPoint and PDF documents in a non-editable manner.
The one option that I found for doing this is to have the content loaded into a web browser component. The downside to that is that it prompts the user to open/save/cancel. We are concerned that the subordinates, being mostly computer illiterate, will have trouble opening the documents in this manner.
Using the above method also means that Microsoft Office and Adobe Acrobat (or another IE enabled PDF viewer) need to be installed on all the machines that will be running the application, which implies expensive licensing fees.
Is there a better way to get this content to display on my forms in C#? | Possibly interesting as well:
Save the documents to XPS using Microsoft Office 2007 (or print them to an XPS printer).
You can display the read-only XPS document either using the XPS viewer component or render page by page into a PNG or JPEG image. This rendering can be achieved quite easily using .NET 3.5 / WPF.
```
XpsDocument xpsDoc = new XpsDocument(xpsFileName, System.IO.FileAccess.Read);
FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();
const double scaleFactor = 0.8;
for (int pageNum = 0; pageNum < docSeq.DocumentPaginator.PageCount; pageNum++)
{
DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageNum);
// FIX: calling GetPage without calling UpdateLayout causes a memory leak
((FixedPage)docPage.Visual).UpdateLayout();
RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)Math.Round(scaleFactor * docPage.Size.Width),
(int)Math.Round(scaleFactor * docPage.Size.Height), (int)Math.Round(scaleFactor * 96), (int)Math.Round(scaleFactor * 96), PixelFormats.Default);
renderTarget.Render(docPage.Visual);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 75;
// Choose type here ie: JpegBitmapEncoder, etc
//BitmapEncoder encoder = new PngBitmapEncoder(); // Choose type here ie: JpegBitmapEncoder, etc
encoder.Frames.Add(BitmapFrame.Create(renderTarget));
string pageImageFileName = string.Format("{0}-{1}.jpg", Path.Combine(Path.GetDirectoryName(xpsFileName), Path.GetFileNameWithoutExtension(xpsFileName)), pageNum);
using (FileStream pageOutStream = new FileStream(pageImageFileName, FileMode.Create, FileAccess.Write))
{
encoder.Save(pageOutStream);
}
}
```
This code needs references to the PresentationCore, PresentationFramework and ReachFramework assemblies.
EDIT: The code above contained a memory leak (see [Opening XPS document in .Net causes a memory leak](https://stackoverflow.com/questions/218681/opening-xps-document-in-net-causes-a-memory-leak)). The workaround has been been inserted in the example. | [SpreadsheetGear for .NET](http://www.spreadsheetgear.com/) has an [Excel Compatible Windows Forms control](http://www.spreadsheetgear.com/support/samples/windowsforms.aspx) which will display your Excel workbooks (it will do lot more than that if you want it to). You can [see what people say](http://www.spreadsheetgear.com/products/spreadsheetgear.net.aspx) and [download](https://www.spreadsheetgear.com/downloads/register.aspx) the free trial if you want to give it a try.
SpreasheetGear can also create [images from charts and ranges of cells](http://www.spreadsheetgear.com/support/samples/imaging.aspx) if you need to generate images to display in a web page. | How do I display office and/or pdf content on a windows form? | [
"",
"c#",
".net",
"excel",
"pdf",
"ms-word",
""
] |
Lets say I'm building a base class which will be extended upon by the children class. So a base class is called `Base` and children can be `Child1`, `Child2`, etc.
In the base class's constructor, how can i get the value of Child1/Child2?
This is all using PHP | A base class should really never depend on information about child classes---
To answer your question:
```
class base {
public function __construct() {
print "Class:" . get_class($this) . "\n";
}
}
class child extends base{
public function __construct() {
parent::__construct();
}
}
$c = new child();
```
Just for future reference -- this can be acheived in a static context using get\_called\_class(), but this is only available in PHP >= 5.3 | simply call [get\_class](http://php.net/get_class)($this) - note however that a base class method has no real business in changing its behaviour depending on which derived class is using it. That's the whole point of deriving a class :) | Getting the name of a child class in PHP | [
"",
"php",
"oop",
""
] |
I want to get the os version that the browser opens, actually my project is an asp.net project and i want to know which operating system runs on the client but there is a question about it. Because the client will use xp but at the same time will use Windows CE 5.0, so the internet explorer in Windows CE is not as good as the one in xp, because of it i'll redirect the user to the page that i designed for Windows CE. So is there any solution to do it?
Thank you.. | The gist of it is use `Request.Browser.Platform`, and the version is in `Request.UserAgent`. | Use [`Request.UserAgent`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.useragent.aspx) - that will *probably* give all the information you need.
There's a ["List of User-Agents"](http://www.user-agents.org/index.shtml?moz) web site which gives lots of sample strings, but if your client has a limited range of setups, it would be worth just trying each of them and logging the user agent as a preliminary step.
Be aware that many browsers will allow you to "spoof" the user agent string, so you mustn't use this for security purposes - but it sounds as if your use case is pretty reasonable. | How to get operating system version asp.net | [
"",
"c#",
"asp.net",
"windows-mobile",
""
] |
I have a Delphi DLL that I did not write, but need to call from a C# ASP.NET 3.5 app. Here is the function definition I got from the developers:
```
function CreateCode(SerialID : String;
StartDateOfYear, YearOfStartDate, YearOfEndDate, DatePeriod : Word;
CodeType,RecordNumber,StartHour,EndHour : Byte) : PChar;
external 'CreateCodeDLL.dll';
```
And here is my C# code:
```
[DllImport( "CreateCodeDLL.dll",
CallingConvention = CallingConvention.StdCall,
CharSet=CharSet.Ansi)]
public static extern IntPtr CreateCode( string SerialID,
UInt16 StartDateOfYear,
UInt16 YearOfStartDate,
UInt16 YearOfEndDate,
UInt16 DatePeriod,
Byte CodeType,
Byte RecordNumber,
Byte StartHour,
Byte EndHour);
```
And finally, my call to this method:
```
//The Inputs
String serialID = "92F00000B4FBE";
UInt16 StartDateOfYear = 20;
UInt16 YearOfStartDate = 2009;
UInt16 YearOfEndDate = 2009;
UInt16 DatePeriod = 7;
Byte CodeType = 1;
Byte RecordNumber = 0;
Byte StartHour = 15;
Byte EndHour = 14;
// The DLL call
IntPtr codePtr = CodeGenerator.CreateCode(serialID, StartDateOfYear,
YearOfStartDate, YearOfEndDate, DatePeriod, CodeType,
RecordNumber, StartHour, EndHour);
// Take the pointer and extract the code in a string
String code = Marshal.PtrToStringAnsi(codePtr);
```
Every time I re-compile this exact code and run it, it returns a different value. The expected value is a 10-digit code comprised of numbers. The returned value is actually 12 digits.
The last important piece of information is that I have a test .EXE that has a GUI that allows me to test the DLL. Every test using the .EXE returns the same 10-digit number (the expected result).
So, I have to believe that I have declared my call to the DLL incorrectly. Thoughts? | Delphi uses the so called ***fastcall*** calling convention by default. This means that the compiler tries to pass parameters to a function in the CPU registers and only uses the stack if there are more parameters than free registers. For example Delphi uses (EAX, EDX, ECX) for the first three parameters to a function.
In your C# code you're actually using the ***stdcall*** calling convention, which instructs the compiler to pass parameters via the stack (in reverse order, i.e. last param is pushed first) and to let the callee cleanup the stack.
In contrast, the ***cdecl*** calling used by C/C++ compilers forces the caller to cleanup the stack.
Just make sure you're using the same calling convention on both sides. Stdcall is mostly used because it can be used nearly everywhere and is supported by every compiler (Win32 APIs also use this convention).
Note that ***fastcall*** isn't supported by .NET anyway. | jn is right. The function prototype, as given, cannot be easily called directly from C# as long as it is in Delphi's `register` calling convention. You either need to write a `stdcall` wrapper function for it - perhaps in another DLL if you don't have source - or you need to get the people who maintain the function to change its calling convention to `stdcall`.
**Update:** I also see that the first argument is a Delphi string. This isn't something that C# can supply either. It should be a PChar instead. Also, it's important to be clear about whether the function is Ansi or Unicode; if the DLL is written with Delphi 2009 (or later), then it is Unicode, otherwise it is Ansi. | Calling a Delphi DLL from C# produces unexpected results | [
"",
"c#",
"delphi",
"dll",
""
] |
I just finished a little 5000-line PHP application and are now going into testing and debugging. A short while before the end I stumbled upon PHPLint. I really liked the idea - with some special comments I can specify variable types and the tool then checks my code for all kinds of mistakes. Neat. I thought that at the end of the development I would comment my code and run PHPLint on it.
Unfortunately I ran into a little problem - PHPLint isn't compilable under Windows. Well, it is, but only with Cygwin, and I don't want to install THAT thing again. Nor do I want to get a virtual machine with Linux or something. Of course, I will, if there will be no other choices, but first I'd like to explore other options.
So - are there any alternatives for PHPLint that run under Windows? I mean in the sense of code-checking. I don't care about the documentation-generation part. | PHPLint now runs under Windows. The download page is currently here: <http://www.icosaedro.it/phplint/download-windows.html>
It's a command-line utility, but there's also a little GUI tool which requires a separate download of the Tcl/Tk interpreter from <http://www.tcl.tk> | They don't work exactly like PHPLint, but there are a couple of static analysis tools listed in [this post](https://stackoverflow.com/questions/378959/is-there-a-static-code-analyzer-like-lint-for-php-files) | What alternatives are there for PHPLint that run under Windows? | [
"",
"php",
"windows",
"validation",
""
] |
Is there a way to find out the memory usage of each dll within a c# application using com dll's? Or what would you say is the best way to find out why memory grows exponentially when using a com object (IE. Whether the COM object has a memory leak, or whether some special freeing up of objects passed to managed code has to occur(and/or how to do that)). | Are you releasing the COM object after usage(`Marshal.ReleaseComObject`)?
What type of parameters are you passing in/out of the calls?
If you don't have the COM object source code and want to determine why its 'leaking', Run the COM object outa proc, attach WinDBG to the process and set breakpoints on memory allocation APIs(HeapAlloc,etc...). Look at the call stack and allocation patterns. Sure you can use profilers on the managed side but if you want to know what is going on you are going to have to get your hands dirty... | A Microsoft support engineer has a fabulous blog that walks through lots of cases like [this](http://blogs.msdn.com/tess/archive/2006/01/23/net-memory-leak-case-study-the-event-handlers-that-made-the-memory-baloon.aspx). She goes over all the tools she uses. I found it extremely helpful to read through all of her posts when I was debugging this kind of stuff a few years ago.
Edit: Apparently, she has added a series of labs that explain how to setup your environment and diagnose different problems. You may want to start [here](http://blogs.msdn.com/tess/pages/net-debugging-demos-information-and-setup-instructions.aspx). | COM C# Memory leak Tracing | [
"",
"c#",
"com",
"memory-leaks",
""
] |
Normally, when you want to call a stored procedure directly through Linq to Sql, you can use the ExecuteQuery method:
```
result = dc.ExecuteQuery<MyTable>("Exec myStoredProcedure");
```
And if you need to call it with parameters, you can add them through string substitution:
```
string query = "Exec myStoredProcedure ";
for (int i = 0; i < parameters.Count - 1; i++) {
query += " {" + i + "},";
}
query = query.TrimEnd(',');
result = dc.ExecuteQuery<MyTable>(query, parameters);
```
But what if one of the parameters is an output variable? Is it possible to get the value back after the procedure has been run? | Alper Ozcetin's is right you can map StoredProcedures in \*.dbml and you can use StoredProcedures as Method.
Below is demo doing this with the AdventureWorks DB and works for both vs2008 and vs2010
Wtih AdventureWorks I created the following Proc
```
CREATE PROC sp_test (@City Nvarchar(60) , @AddressID int out )
AS
SELECT TOP 10 * FROM Person.Address where City = @City
select top 1 @AddressID = AddressID FROM Person.Address where City = @City
```
I then added sp\_test to a dbml and wrote the following program
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext dc = new DataClasses1DataContext("SomeSQLConnection);
int? AddressID = null;
ISingleResult<sp_testResult> result = dc.sp_test("Seattle", ref AddressID);
foreach (sp_testResult addr in result)
{
Console.WriteLine("{0} : {1}", addr.AddressID, addr.AddressLine1);
}
Console.WriteLine(AddressID);
}
}
}
```
This results in the following ouput
```
23 : 6657 Sand Pointe Lane
91 : 7166 Brock Lane
92 : 7126 Ending Ct.
93 : 4598 Manila Avenue
94 : 5666 Hazelnut Lane
95 : 1220 Bradford Way
96 : 5375 Clearland Circle
97 : 2639 Anchor Court
98 : 502 Alexander Pl.
99 : 5802 Ampersand Drive
13079
```
You'll notice that the input into the sp\_test method is a `ref` | I'm not sure, but you can try to declare variable in query, pass it as an output parameter and then select it:
```
//assuming you out parameter is integer
string query = "DECLARE @OUT INT ";
query += " Exec myStoredProcedure ";
for (int i = 0; i < parameters.Count - 1; i++) {
query += " {" + i + "},";
}
//assuming the output parameter is the last in the list
query += " @OUT OUT ";
//select value from out param after sp execution
query += " SELECT @OUT"
``` | Is it possible to use output parameters with ExecuteQuery<T>? | [
"",
"sql",
"linq-to-sql",
"stored-procedures",
""
] |
I know that you can use a javascript: pseudo protocol for URLs in an `<a>` tag. However, I've noticed that Firefox and IE will both allow '`javascript:`' to precede javascript code within a `<script>` tag. Is this valid syntax? Does it change the scoping rules?
Examples:
I've seen this many times:
```
<a onclick="javascript:alert('hello world!');">Hello World!</a>
```
But is this legal/valid syntax and does it do anything special:
```
<script type="text/javascript">
javascript:alert('hello world!');
</script>
``` | Outside of the `href` attribute (where it is a protocol specifier), *name*: just creates [a label](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/Label) (such as one might use with a `continue` or `break`).
### See: [Do you ever need to specify javascript: in an onclick?](https://stackoverflow.com/questions/372159/do-you-ever-need-to-specify-javascript-in-an-onclick) | You need the `javascript:` "protocol" when you want to put JavaScript in the `href` attribute of a link.
```
<!-- does not work -->
<a href="alert('some text');">link</a>
<!-- does work -->
<a href="javascript:alert('some text');">link</a>
<!-- also works -->
<a href="#" onclick="alert('some text');">link</a>
```
As far as I know (and please, if I'm wrong, someone correct me) there is no difference in scope, but there is a very important difference about `this`.
```
<!-- does not work -->
<a href="alert(this.href);">link</a>
<!-- alerts "undefined" -->
<a href="javascript:alert(this.href);">link</a>
<!-- works as expected, alerts "<url>#" -->
<a href="#" onclick="alert(this.href);">link</a>
``` | When is the 'javascript:' prefix valid syntax? | [
"",
"javascript",
"syntax",
""
] |
I'm working on developing a SIP application in Java and wondering what is the most used SIP library currently.
MJSIP? | As far as I know, its [JAIN-SIP](http://wiki.java.net/bin/view/Communications/JainSIP). Its good to know about MjSip, by the way. You might be interested in looking at [JBoss Mobicent](http://www.mobicents.org-a.googlepages.com/index.html), the user guide is not complete at the moment. and you wouldn't find much help on Mobicent.
Or as [metadaddy](https://stackoverflow.com/users/33905/metadaddy) stated [here](https://stackoverflow.com/a/498307/42769), "You might want to take a look at [SailFin](https://sailfin.dev.java.net/) - its a SIP servlet container built by Ericsson using [GlassFish](http://glassfish.java.net/)." | You might want to take a look at [SailFin](https://sailfin.dev.java.net/) - its a SIP servlet container built by Ericsson using [GlassFish](http://glassfish.java.net/). | What is the currently popular Java SIP library? | [
"",
"java",
"sip",
""
] |
I am currently working in J2ME. I would like to link the source code of J2ME with my Eclipse installation so that I can go through the contents of it and also it will help me in debugging.
I am quite used to this when the source code of J2SE was (is) available in jar format and you just need to link it to Eclipse.
Could you please provide me the link to the download of the jar. Is it free? | I think the core issue is that Java SE and the JDK is now open source, where J2ME is not. So, even getting Sun's implementations of J2ME might be a bit tough at this time.
There must be a reason, but not sure why they wouldn't open source the J2ME implementation as well. | There are multiple implementations of the CLDC VM. So you might have a hard time finding the sources. Also most of the VM do not support debugging the system classes. If you want to see the CLDC sources, SUNs implementation is open-sourced on dev.java.net [PhoneME Project](https://phoneme.dev.java.net/). | Where can I find the source code for J2ME? | [
"",
"java",
"java-me",
""
] |
I currently have multiple tables in my database which consist of the same 'basic fields' like:
```
name character varying(100),
description text,
url character varying(255)
```
But I have multiple specializations of that basic table, which is for example that `tv_series` has the fields `season`, `episode`, `airing`, while the `movies` table has `release_date`, `budget` etc.
Now at first this is not a problem, but I want to create a second table, called `linkgroups` with a Foreign Key to these specialized tables. That means I would somehow have to normalize it within itself.
One way of solving this I have heard of is to normalize it with a `key-value`-pair-table, but I do not like that idea since it is kind of a 'database-within-a-database' scheme, I do not have a way to require certain keys/fields nor require a special type, and it would be a huge pain to fetch and order the data later.
So I am looking for a way now to 'share' a Primary Key between multiple tables or even better: a way to normalize it by having a general table and multiple specialized tables. | Right, the problem is you want only one object of one sub-type to reference any given row of the parent class. Starting from the [example](https://stackoverflow.com/questions/561576/polymorphism-in-sql-database-tables/561627#561627) given by @Jay S, try this:
```
create table media_types (
media_type int primary key,
media_name varchar(20)
);
insert into media_types (media_type, media_name) values
(2, 'TV series'),
(3, 'movie');
create table media (
media_id int not null,
media_type not null,
name varchar(100),
description text,
url varchar(255),
primary key (media_id),
unique key (media_id, media_type),
foreign key (media_type)
references media_types (media_type)
);
create table tv_series (
media_id int primary key,
media_type int check (media_type = 2),
season int,
episode int,
airing date,
foreign key (media_id, media_type)
references media (media_id, media_type)
);
create table movies (
media_id int primary key,
media_type int check (media_type = 3),
release_date date,
budget numeric(9,2),
foreign key (media_id, media_type)
references media (media_id, media_type)
);
```
This is an example of the disjoint subtypes [mentioned](https://stackoverflow.com/questions/561576/polymorphism-in-sql-database-tables/561960#561960) by @mike g.
---
Re comments by @Countably Infinite and @Peter:
INSERT to two tables would require two insert statements. But that's also true in SQL any time you have child tables. It's an ordinary thing to do.
UPDATE may require two statements, but some brands of RDBMS support multi-table UPDATE with JOIN syntax, so you can do it in one statement.
When querying data, you can do it simply by querying the `media` table if you only need information about the common columns:
```
SELECT name, url FROM media WHERE media_id = ?
```
If you know you are querying a movie, you can get movie-specific information with a single join:
```
SELECT m.name, v.release_date
FROM media AS m
INNER JOIN movies AS v USING (media_id)
WHERE m.media_id = ?
```
If you want information for a given media entry, and you don't know what type it is, you'd have to join to all your subtype tables, knowing that only one such subtype table will match:
```
SELECT m.name, t.episode, v.release_date
FROM media AS m
LEFT OUTER JOIN tv_series AS t USING (media_id)
LEFT OUTER JOIN movies AS v USING (media_id)
WHERE m.media_id = ?
```
If the given media is a movie,then all columns in `t.*` will be NULL. | Consider using a main basic data table with tables extending off of it with specialized information.
Ex.
```
basic_data
id int,
name character varying(100),
description text,
url character varying(255)
tv_series
id int,
BDID int, --foreign key to basic_data
season,
episode
airing
movies
id int,
BDID int, --foreign key to basic_data
release_data
budget
``` | Polymorphism in SQL database tables? | [
"",
"sql",
"postgresql",
"database-normalization",
""
] |
Working on our restricted system means I cant drop class librariess into the app\_bin/bin/App\_Code basically any normal folder, so I'm currently linking to my class library as follows...
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="~/cs/codebehind.cs" Inherits="codebehind" %>
<%@ Assembly Src="~/cs/mycodelibrary.cs" %>
```
The problem I'm trying to solve is how would I reference the class library as a file in the codebehind so I don't need to have another thing on the page, and VS stops telling me the things in the assembly don't exist.
i.e
```
using "~/cs/regionalPages.cs"
```
---
Quick addition, adding the mycodelibrary.cs as above does work. I'm just trying to find a better way.
And i should reaffirm that **I have no access to normal .net folders**, if I did I wouldn't be asking this seemingly dumb question. | So. You miss real servers.
Why don't you use the App\_Code folder and let ASP.NET handle the compilation and reference paths for you? That's what it's for.
**Edit**: Hm. You're saying you don't have access to App\_Code, but you have a folder called cs where you can drop code files instead? That's a very strange arrangement. What would whoever restricted your access in the first place think about that?
Another thing i don't get is how your mycodelibrary.cs will be compiled at all. ASP.NET handles compilation inside the App\_Code folder, but not elsewhere (or am I wrong?).
**Another edit**: OK, I've got it now, and have tried it out. The `@Assembly` directive in the .aspx page ensures the code file is compiled, and a reference to it made available to the page. Then the reference is also available in the codebehind (even with intellisense), since it's the same (partial) class.
Now, is you question how you can accomplish the same thing without the `@Assembly` directive in the .aspx file (but rather something in the codebehind)? I can tell you no form of `using` will do the trick, at least. Honestly, I can't see any way to accomplish that, sorry.
Cerebrus mentions configuring the runtime with codebase or probing in Web.config, but that only works with compiled assemblies. | First of all, a .cs file is not an assembly. It must be compiled into a DLL first before it can be considered an assembly.
In order to reference the code in the assembly imported at the page-level, I believe you will have to put your server-side code inline with the markup (as opposed to having a separate aspx.cs file).
Best regards... | Including class libraries within a page behind, C# ASP.Net | [
"",
"c#",
"asp.net",
"class",
""
] |
How can I fire a trigger BEFORE a delete in T-SQL 2005?
The FOR actually fires AFTER an event and they seems no BEFORE argument in the TRIGGER function.
The INSTEAD OF is not what I want.
I need to fire before I delete a record.
Any ideas? | You can use the INSTEAD OF option, just explicitly delete the rows at the end. For example:
```
CREATE TRIGGER dbo.My_Table_Delete_Instead_Of_Trigger
ON dbo.My_Table
INSTEAD OF DELETE
AS
BEGIN
-- Do some stuff here
DELETE T
FROM DELETED D
INNER JOIN dbo.My_Table T ON T.PK_1 = D.PK_1 AND T.PK_2 = D.PK_2
END
```
This assumed a primary key made up of columns PK\_1 and PK\_2. | You can't. But you can perform a rollback in an AFTER DELETE trigger. | How can I fire a trigger BEFORE a delete in T-SQL 2005? | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.
I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: [Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx)](https://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx)
So I rolled my own.
It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.
Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.
The implementation is simple, and here is a quick overview off the features:
```
workbook = Workbook(filename) # open a file
for sheet in workbook: pass # iterate over the worksheets
workbook["sheetname"] # access a sheet by name, also possible to do by index from 0
sheet["A1"] # Access cell
sheet["A"] # Access column
sheet["1"] # Access row
cell.value # Cell value - only tested with ints and strings.
```
Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.
My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.
So I put it on github for any to see and branch off:
<http://github.com/staale/python-xlsx/tree/master>
I don't want to do all the work for the python project hosting, so that's out.
Accepting the git answer, as that was the only thing that worked for me. And git rocks.
Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later. | [GitHub](http://github.com/) would also be a great place to post this. Especially as that would allow others to quickly fork their own copies and make any improvements or modifications they need. These changes would then also be available to anyone else who wants them. | You should post it [here](http://code.activestate.com/recipes/langs/python/). There are plenty of recipes here and yours would fit in perfectly.
Stack Overflow is meant to be a wiki, where people search for questions and find answers. That being said, if you want to post it here, what you would do is open a question relevant to your answer, then respond to your own question with your answer. | Where should I post my python code? | [
"",
"python",
"excel-2007",
""
] |
Let's say I have a class designed to be instantiated. I have several private "helper" methods inside the class that do not require access to any of the class members, and operate solely on their arguments, returning a result.
```
public class Example {
private Something member;
public double compute() {
double total = 0;
total += computeOne(member);
total += computeMore(member);
return total;
}
private double computeOne(Something arg) { ... }
private double computeMore(Something arg) {... }
}
```
Is there any particular reason to specify `computeOne` and `computeMore` as static methods - or any particular reason not to?
It is certainly easiest to leave them as non-static, even though they could certainly be static without causing any problems. | I prefer such helper methods to be `private static`; which will make it clear to the reader that they will not modify the state of the object. My IDE will also show calls to static methods in italics, so I will know the method is static without looking the signature. | It might result in slightly smaller bytecode, since the static methods won't get access to `this`. I don't think it makes any difference in speed (and if it did, it would probably be too small to make a difference overall).
I would make them static, since I generally do so if at all possible. But that's just me.
---
**EDIT:** This answer keeps getting downvoted, possibly because of the unsubstantiated assertion about bytecode size. So I will actually run a test.
```
class TestBytecodeSize {
private void doSomething(int arg) { }
private static void doSomethingStatic(int arg) { }
public static void main(String[] args) {
// do it twice both ways
doSomethingStatic(0);
doSomethingStatic(0);
TestBytecodeSize t = new TestBytecodeSize();
t.doSomething(0);
t.doSomething(0);
}
}
```
Bytecode (retrieved with `javap -c -private TestBytecodeSize`):
```
Compiled from "TestBytecodeSize.java"
class TestBytecodeSize extends java.lang.Object{
TestBytecodeSize();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
private void doSomething(int);
Code:
0: return
private static void doSomethingStatic(int);
Code:
0: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: invokestatic #2; //Method doSomethingStatic:(I)V
4: iconst_0
5: invokestatic #2; //Method doSomethingStatic:(I)V
8: new #3; //class TestBytecodeSize
11: dup
12: invokespecial #4; //Method "<init>":()V
15: astore_1
16: aload_1
17: iconst_0
18: invokespecial #5; //Method doSomething:(I)V
21: aload_1
22: iconst_0
23: invokespecial #5; //Method doSomething:(I)V
26: return
}
```
Invoking the static method takes two bytecodes (byteops?): `iconst_0` (for the argument) and `invokestatic`.
Invoking the non-static method takes three: `aload_1` (for the `TestBytecodeSize` object, I suppose), `iconst_0` (for the argument), and `invokespecial`. (Note that if these hadn't been private methods, it would have been `invokevirtual` instead of `invokespecial`; see [JLS §7.7 Invoking Methods](http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14787).)
Now, as I said, I don't expect there to be any great difference in performance between these two, other than the fact that `invokestatic` requires one fewer bytecode. `invokestatic` and `invokespecial` should both be slightly faster than `invokevirtual`, since they both use static binding instead of dynamic, but I have no idea if either is faster than the other. I can't find any good references either. The closest I can find is [this 1997 JavaWorld article](http://www.javaworld.com/javaworld/jw-06-1997/jw-06-hood.html), which basically restates what I just said:
> The fastest instructions will most likely be `invokespecial` and `invokestatic`, because methods invoked by these instructions are statically bound. When the JVM resolves the symbolic reference for these instructions and replaces it with a direct reference, that direct reference probably will include a pointer to the actual bytecodes.
But many things have changed since 1997.
So in conclusion... I guess I'm still sticking with what I said before. Speed shouldn't be the reason to choose one over the other, since it would be a micro-optimization at best. | Should private helper methods be static if they can be static | [
"",
"java",
"static",
"methods",
"static-methods",
""
] |
I have a GWT application that displays some charts rendered by JFreeChart. Every few minutes, the page refreshes, which causes the app to generate new charts. (In other words, the entire chart generation process is bootstrapped by a client request.) The problem with this is that multiple clients hitting the same server would result in multiple requests to generate charts, but since the charts are the same for all users, there's really no reason to do this. I would like to prerender the charts in a background thread, which would be kicked off when the application starts, and then just serve the already-rendered charts to the client on request.
I don't see any "sanctioned" way in GWT to execute your own code at server startup. The only way I can think of to accomplish this is to create a servlet that gets loaded at startup by the application container, and kick off the chart generation thread in the init() method.
Is there a more preferred way to do this?
Note: Assuming that it's true, "no" is a perfectly acceptable answer. | To answer your question: No. GWT is a front end technology, and the only bit of GWT that crosses this line is the RPC mechanism. The only 'GWT' type way that you could do it would be to check if the chart files exist the first time a user requests them, and generate them if they don't. This would mean using the file system as your check of if it's been created yet or not.
The better way would be to do what you said, eg: configure your your web project to kick off a class on startup. You do this in your web.xml as described here:
<http://wiki.metawerx.net/wiki/Web.xml.LoadOnStartup>
Here's an example of how Stripes does it:
```
<servlet>
<servlet-name>StripesDispatcher</servlet-name>
<servlet-class>net.sourceforge.stripes.controller.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StripesDispatcher</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
``` | I disagree that you should put code in the servlet initialization to create these threads. When the web app is stopped you won't get control over when to destroy these threads. Also when you start the web app up again will it create these threads again or not?
What would be better is to use the J2EE ServletContextListener event named contextInitialized to create the threads and the contextDestroyed event to destroy your threads. This also allows you to control thread destruction and wait for code in the threads to finish executing before destroying them.
Looks like this explains how that works:
<http://www.java-tips.org/java-ee-tips/java-servlet/how-to-work-with-servletcontextlistener.html> | Launching background threads on GWT startup | [
"",
"java",
"multithreading",
"gwt",
""
] |
How could I convert a year-week (for example, 0852 or 200852) into a date (for example, 2008-12-31 or specifically a week-ending day, that is, Saturday 2008-12-27 or a week-beginning day, that is, 2008-12-21)?
Any day of the week-ending will do, Friday, Saturday, Sunday or Monday. | I've created a [UDF](https://en.wikipedia.org/wiki/User-defined_function#Databases) for this purpose.
It'll convert a YYYYWW string or number to a date.
```
CREATE FUNCTION dbo.GetDateFromYearWeek (
@YearWeek VARCHAR(7) = '000101', -- default
@WeekDay INT = 1, -- default
@FirstWeekDayName VARCHAR(9) = 'mon' -- default
) RETURNS DATE
BEGIN
IF @YearWeek = '000101'
SET @YearWeek = CONCAT(DATEPART(year, GETDATE()), '-', DATEPART(week, GETDATE()));
IF @YearWeek NOT LIKE '[0-9][0-9][0-9][0-9]%[0-9-][0-9]'
RETURN NULL;
IF @WeekDay < 1 OR @WeekDay > 7
RETURN NULL;
DECLARE @FirstWeekDay INT = CHARINDEX(LOWER(LEFT(@FirstWeekDayName,3)), ' montuewedthufrisatsun')/3;
IF @FirstWeekDay = 0 -- not found in string
SET @FirstWeekDay = @@DATEFIRST;
DECLARE @Year INT = TRY_CAST(LEFT(@YearWeek, 4) AS INT);
DECLARE @Week INT = ABS(TRY_CAST(RIGHT(@YearWeek, 2) AS INT));
DECLARE @Date DATE = TRY_CAST(CONCAT(@Year,'-01-01') AS DATE);
SET @Date = DATEADD(week, @Week-1, @Date);
DECLARE @DowDiff INT = (6-@FirstWeekday+@@DATEFIRST+DATEPART(weekday,@Date))%7;
SET @Date = DATEADD(day, -@DowDiff, @Date);
SET @Date = DATEADD(day, @WeekDay-1, @Date);
RETURN @Date;
END;
```
**Example usage:**
```
SELECT *
, [StartOfWeek_SundayFirst] = dbo.GetDateFromYearWeek(col, 1, 'sun')
, [StartOfWeek_MondayFirst] = dbo.GetDateFromYearWeek(col, 1, 'mon')
, [EndOfWeek_SundayFirst] = dbo.GetDateFromYearWeek(col, 7, 'sunday')
, [EndOfWeek_MondayFirst] = dbo.GetDateFromYearWeek(col, 7, 'monday')
FROM (VALUES (202201), (202202)) q(col)
ORDER BY 1;
```
| col | StartOfWeek\_SundayFirst | StartOfWeek\_MondayFirst | EndOfWeek\_SundayFirst | EndOfWeek\_MondayFirst |
| --- | --- | --- | --- | --- |
| 202201 | 2021-12-26 | 2021-12-27 | 2022-01-01 | 2022-01-02 |
| 202202 | 2022-01-02 | 2022-01-03 | 2022-01-08 | 2022-01-09 |
Test it on the *db<>fiddle [here](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=fa6e5fb32d9677b71052479ed8b7d2e2)*.
**ISO\_WEEK Version**
> ```
> CREATE FUNCTION dbo.GetDateFromIsoYearWeek (
> @YearWeek VARCHAR(7) = '0000-00', -- default
> @WeekDay INT = 1 -- default
> ) RETURNS DATE
> BEGIN
>
> IF @YearWeek = '0000-00'
> SET @YearWeek = CONCAT(DATEPART(year, GETDATE()), '-', DATEPART(iso_week, GETDATE()));
>
> IF @YearWeek NOT LIKE '[0-9][0-9][0-9][0-9]%[0-9-][0-9]'
> RETURN NULL;
>
> IF @WeekDay < 1 OR @WeekDay > 7
> RETURN NULL;
>
> DECLARE @FirstWeekDay INT = 1; -- monday
> DECLARE @Year INT = TRY_CAST(LEFT(@YearWeek, 4) AS INT);
> DECLARE @Week INT = ABS(TRY_CAST(RIGHT(@YearWeek, 2) AS INT));
>
> DECLARE @Date DATE = TRY_CAST(CONCAT(@Year,'-01-08') AS DATE);
> SET @Date = DATEADD(week, @Week - 2 + (DATEPART(week, @Date)-(DATEPART(iso_week, @Date))), @Date);
>
> DECLARE @DowDiff INT = (6-@FirstWeekday+@@DATEFIRST+DATEPART(weekday,@Date))%7;
> SET @Date = DATEADD(day, -@DowDiff, @Date);
> SET @Date = DATEADD(day, @WeekDay-1, @Date);
>
> RETURN @Date;
> END;
> ```
> ```
> DECLARE @Test TABLE ([column] char(7));
> INSERT INTO @Test VALUES
> ('2020-53'), ('2021-01'), ('2021-02')
> , ('2021-48')
> , ('2021-53'), ('2022-01'), ('2022-02')
> ;
>
> SELECT [column]
> , [FirstOfWeek] = dbo.GetDateFromIsoYearWeek([column], 1)
> , [LastOfWeek] = dbo.GetDateFromIsoYearWeek([column], 7)
> FROM @Test
> ORDER BY 1;
> ```
> | column | FirstOfWeek | LastOfWeek |
> | --- | --- | --- |
> | 2020-53 | 2020-12-28 | 2021-01-03 |
> | 2021-01 | 2021-01-04 | 2021-01-10 |
> | 2021-02 | 2021-01-11 | 2021-01-17 |
> | 2021-48 | 2021-11-29 | 2021-12-05 |
> | 2021-53 | 2022-01-03 | 2022-01-09 |
> | 2022-01 | 2022-01-03 | 2022-01-09 |
> | 2022-02 | 2022-01-10 | 2022-01-16 |
Test it on the *db<>fiddle [here](https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=1973e0b3af8e3979925c90cda231e858)*. | [SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) has the DATEADD functionality that should help...
```
DECLARE @date_string NCHAR(6)
SELECT @date_string = N'200852'
SELECT DATEADD(
WEEK,
CAST(RIGHT(@date_string, 2) AS INT),
DATEADD(
YEAR,
CAST(LEFT(@date_string, 4) AS INT) - 1900,
0
)
)
```
Once you have the value, use DATEPART to get what day of the week it is, and subtract that from your answer...
```
DECLARE @new_date DATETIME
SELECT @new_date = '2008 Dec 30'
SELECT DATEADD(DAY, 1-DATEPART(dw, @new_date), @new_date)
```
This will bring the value to the start of the week, depending on what you have set DATEFIRST to. | How can I convert a week (200851) into a date (2008-12-27)? | [
"",
"sql",
"sql-server",
"t-sql",
"date-arithmetic",
""
] |
I don't really understand [this article](http://developers.slashdot.org/article.pl?sid=08/11/19/2321230&from=rss). But it sounds like you can compile C/C++ for flash. If that's possible, how hard would it be to compile and run Mono inside flash?
Sounds stupid I know...maybe I'm going crazy with my age. | Probably is possible, at the first time, but just *compile*. Let me see if I got where you want go.
Mono can run on-the-fly code, but even now that there is a [C# Shell](http://www.mono-project.com/CsharpRepl) it first compiles to IL (and maybe JIT) and after that it executes. With that technology will be possible to make Flash generate .NET assemblies, but not run them!
We will need a .NET IL to AS3 bytecode converter in order to run .NET assemblies in Flash. Probably you are thinking in this, right? But that's not crazy at all, it's *compatibility*! | I'm sure a really good and dedicated hacker, able to change both the mono runtime and the flash player, could get a trivial hello-world-like program to run in a few months of work.
That said, implementing all the features would be either extremely complex or extremely slow, so, from a practical point of view using this approach wouldn't work.
If you'd like to run CLR-based managed code in the browser, check out the Moonlight 2.0 progress [here](http://tirania.org/blog/archive/2009/Feb-11.html): it works today, it is fast and it can be easily ported to run on a wide range of devices (there is also a Mono port to Android, for example). | With this technology, would it be possible to compile and run silverlight IL in Flash? | [
"",
".net",
"c++",
"flash",
"silverlight",
"mono",
""
] |
I am currently working on an application with a tabbed interface. I want to be able to split the workspace horizontally or vertically by dragging a tab to one edge of the window.
For example, open two tabs: <http://666kb.com/i/b65vvbusbxhvgy8mf.png>
Then drag one tab to the bottom of the screen and drop it. A second tabcontrol should appear: <http://666kb.com/i/b65vvjnd1ylz54jdz.png>
How can I achieve that with C# and WPF in .NET 3.5?
I think Photoshop does that and I'm sure many other applications too. | check out [AvalonDock](http://www.codeplex.com/AvalonDock), maybe this can help you to get into the right direction. | The Actipro tabbed workspace control is very elegant and I haven't seen any bugs myself. | Tabbed Interface in C#/WPF | [
"",
"c#",
"wpf",
"tabbed",
""
] |
My specific question has to do with JMX as used in JDK 1.6: if I am running a Java process using JRE 1.6 with
```
com.sun.management.jmxremote
```
in the command line, does Java pick a default port for remote JMX connections?
Backstory: I am currently trying to develop a procedure to give to a customer that will enable them to connect to one of our processes via JMX from a remote machine. The goal is to facillitate their remote debugging of a situation occurring on a real-time display console. Because of their service level agreement, they are strongly motivated to capture as much data as possible and, if the situation looks too complicated to fix quickly, to restart the display console and allow it to reconnect to the server-side.
I am aware the I could run [jconsole](http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html) on JDK 1.6 processes and [jvisualvm](http://java.sun.com/javase/6/docs/technotes/tools/share/jvisualvm.html) on post-JDK 1.6.7 processes given physical access to the console. However, because of the operational requirements and people problems involved, we are strongly motivated to grab the data that we need remotely and get them up and running again.
EDIT: I am aware of the command line port property
```
com.sun.management.jmxremote.port=portNum
```
The question that I am trying to answer is, if you do not set that property at the command line, does Java pick another port for remote monitoring? If so, how could you determine what it might be? | The [documentation](http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html) suggests that the JMX agent uses a **local** port -- something unreachable from outside the machine -- unless you specify the following property:
`com.sun.management.jmxremote.port=portNum`
This is for security reasons, as well as for the reason given by Mr Potato Head. Thus, it looks like Java 6 does not open a default *remotely accessible* port for JMX.
EDIT: Added after the OP added an answer with more information.
Another option you have is to somehow create a local proxy that listens to all local JMX connections and exports this information. This way, you don't need to have such magic configuration of each JVM instance on the server. Instead the local proxy can connect to all JVMs via JMX and then somehow expose this information remotely. I am not positive exactly how you would implement this, but something like this may be less work than what you otherwise have to do to expose all of your JVMs remotely via JMX. | *AFAIK,*
Here are the possibilites for connecting a *JMX client process* (a **management application** like jconsole, jmxterm, mc4j, jvmstat, jmxmonitor, jps, ...) to a *JMX server process* (the **agent**).
The protocol connecting JMX client and JMX server is assumed to be 'Java RMI' (aka 'RMI-JRMP'). This should be the default. One can configure [other protocols](http://docs.oracle.com/javase/6/docs/technotes/guides/jmx/overview/connectors.html#wp5529), in particular 'RMI-IIOP' and 'JMXMP'. Special protocols are possible: the [MX4J](http://mx4j.sourceforge.net/) project for example additionally provides SOAP/HTTP and various serialization protocols over HTTP.
Refer to [Sun/Oracle docs](http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html) for details on configuration.
Also have a look at the file `jre/lib/management/management.properties` in your JDK distribution.
So, the possibilities:
**Case 0: The JVM is started without any particular configuration**
Before Java 6: The JVM does not behave as a JMX server. Any program that is run inside the JVM may access the JVM's [MBeanServer](http://docs.oracle.com/javase/6/docs/api/javax/management/MBeanServer.html) programmatically and use it to do interesting data exchanges between threads or to do JVM monitoring, but no management from outside the JVM process is possible.
Since Java 6: Even if not explicitely configured, one can access JMX functionality of the JVM *locally* (from the same machine) as described in "Case 1".
**Case 1: The JVM is started with `-Dcom.sun.management.jmxremote`**
The JVM is configured to work as a *local* (same-machine-only) JMX server.
In this case (and in principle only for Sun/Oracle JVMs) a JMX client can connect to the JMX server through memory-mapped files found in `/tmp/hsperfdata_[user]`. This is alluded to in the Sun documentation and called "local monitoring" (and also the [Attach API](http://docs.oracle.com/javase/6/docs/jdk/api/attach/spec/index.html)). It does not work on FAT filesystems as permissions cannot be set correctly there. See [this blog entry](https://blogs.oracle.com/lmalventosa/entry/jconsole_local_process_list_on).
Sun recommends running `jconsole` on a machine separate from the JMX server as `jconsole` apparently is a resource hog, so this "local monitoring" thing is not necessarily a good idea.
Local monitoring is, however, rather secure, only being usable locally and being easily controlled through filesystem permissions.
**Case 2: The JMX server is started with `-Dcom.sun.management.jmxremote.port=[rmiregistryport]`**
The JVM is configured to work as a JMX server listening on several TCP ports.
The port specified on the command line will be allocated by the JVM and an RMI registry will be available there. The registry advertises a connector named 'jmxrmi'. It points to a second, randomly allocated TCP port (an 'ephemeral' port) on which the JMX RMI server listens and through which actual data exchange takes place.
Local as described in 'Case 1' is always enabled in 'Case 2'.
The JMX server listens on all interfaces by default, so you can connect to it (and control it) by locally connecting to 127.0.0.1:[rmiregistryport] as well by remotely connecting to [any outside IP address]:[some port] remotely.
*This implies that you have to look at the security implications*. You can make the JVM listen on 127.0.0.1:[rmiregistryport] only by setting `-Dcom.sun.management.jmxremote.local.only=true`.
It is rather unfortunate that one cannot specify where the ephemeral port will be allocated - it is always chosen randomly at startup. This may well mean that your firewall needs to become the swiss cheese of the damned! However, there are [workarounds](http://olegz.wordpress.com/2009/03/23/jmx-connectivity-through-the-firewall/). In particular, Apache Tomcat sets the ephemeral JMX RMI server port via its [JMX Remote Lifecycle Listener](http://tomcat.apache.org/tomcat-7.0-doc/config/listeners.html#Additional_Implementations). The code to perform this little magic can be found at [org.apache.catalina.mbeans.JmxRemoteLifecycleListener](http://grepcode.com/file/repo1.maven.org/maven2/org.apache.tomcat/tomcat-catalina-jmx-remote/7.0.14/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java/).
If you use this method, you might as well make sure that:
1. The JMX client has to authenticate to the JMX server
2. The TCP exchange between the client and server is encrypted using SSL
How that is done is described in [the Sun/Oracle documentation](http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html)
**Other approaches**
You can do interesting permutations to avoid having to use the RMI protocol. In particular, you could add a servlet engine (like Jetty) to your process. Then add servlets that translate some HTTP-based exchange internally into direct accesses to the JVM's `MBeanServer`. You would then be in 'case 0' but still have management capabilities, possibly through an HTML-based interface. The [JBoss JMX Console](http://docs.oracle.com/javase/1.5.0/docs/guide/management/SNMP.html) is an example of this.
More off-topic, you could use SNMP directly (something I haven't tried) according to [this document](http://docs.oracle.com/javase/1.5.0/docs/guide/management/SNMP.html).
**Show and Tell Time**
And now it's time for some code to illustrate a JXM exchange. We take inspiration from [a Sunoracle tutorial](http://docs.oracle.com/javase/tutorial/rmi/client.html).
This runs on Unix. We use a JVM that is configured as a JMX server using:
`-Dcom.sun.management.jmxremote.port=9001`
We use `lsof` to check what TCP ports it is holding open:
`lsof -p <processid> -n | grep TCP`
One should see something like this, the registry port and the ephemeral port:
```
java 1068 user 127u IPv6 125614246 TCP *:36828 (LISTEN)
java 1068 user 130u IPv6 125614248 TCP *:9001 (LISTEN)
```
We use `tcpdump` to inspect the packet exchange between JMX client and JMX server:
`tcpdump -l -XX port 36828 or port 9001`
We set up a file `.java.policy` in the home directory to allow the client to actually connect remotely:
```
grant {
permission java.net.SocketPermission
"<JMX server IP address>:1024-65535", "connect,resolve";
};
```
And then we can run this and see what happens:
```
package rmi;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javax.management.remote.rmi.RMIConnection;
import javax.management.remote.rmi.RMIServer;
public class Rmi {
public static void main(String args[]) throws Exception {
// We need a Security Manager (not necessarily an RMISecurityManager)
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
//
// Define a registry (this is just about building a local data structure)
//
final int comSunManagementJmxRemotePort = 9001;
Registry registry = LocateRegistry.getRegistry("<JMX server IP address>", comSunManagementJmxRemotePort);
//
// List registry entries. The client connects (using TCP) to the server on the
// 'com.sun.management.jmxremote.port' and queries data to fill the local registry structure.
// Among others, a definition for 'jmxrmi' is obtained.
//
System.out.print("Press enter to list registry entries");
System.in.read();
String[] names = registry.list();
for (String name : names) {
System.out.println("In the registry: " + name);
}
//
// 'Looking up' the entry registered under 'jmxrmi' involves opening and tearing down
// a TCP connection to the 'com.sun.management.jmxremote.port', as well as a TCP
// connection to an ephemeral secondary port chosen at server startup.
// The actual object locally obtained is a "javax.management.remote.rmi.RMIServerImpl_Stub"
// indicating where the ephemeral port is.
// "RMIServerImpl_Stub[UnicastRef [liveRef: [endpoint:[$IP:$EPHEMERAL_PORT](remote),objID:[-62fb4c1c:131a8c709f4:-7fff, -3335792051140327600]]]]"
//
System.out.print("Press enter to get the 'jmxrmi' stub");
System.in.read();
RMIServer jmxrmiServer = (RMIServer)registry.lookup("jmxrmi");
System.out.println(jmxrmiServer.toString());
//
// Now get a "RMI Connection" to the remote. This involves setting up and tearing
// down a TCP connection to the ephemeral port.
//
System.out.print("Press enter to get the 'RMIConnection'");
System.in.read();
RMIConnection rcon = jmxrmiServer.newClient(null);
//
// Ask away. This involves setting up and tearing
// down a TCP connection to the ephemeral port.
//
System.out.print("Press enter to get the 'domains'");
System.in.read();
for (String domain : rcon.getDomains(null)) {
System.out.println("Domain: " + domain);
}
//
// Ok, that will do. For serious applications, we better use the higher-level JMX classes
//
}
}
``` | Does Java 6 open a default port for JMX remote connections? | [
"",
"java",
"jmx",
"jconsole",
"jvisualvm",
""
] |
My company has purchased a product that renders an ASP.NET control on the page. This control uses jQuery 1.2.3 and adds a script tag to the page to reference it. The developers of the control will not support use of the control if it modified in any way (including modification to reference a different version of jQuery).
I'm about to start development of my own control and would like to use the features and speed improvements of jQuery 1.3. Both of these controls will need to exist on the same page.
How can I allow the purchased control to use jQuery 1.2.3 and new custom development to use jQuery 1.3? Also out of curiosity, what if we were to use an additional control that needed to reference yet another version of jQuery? | You can achieve this by running your version of jQuery in [no-conflict mode](http://docs.jquery.com/Using_jQuery_with_Other_Libraries). "No conflict" mode is the typical solution to get jQuery working on a page with other frameworks like [prototype](http://www.prototypejs.org/), and can be also be used here as it essentially namespaces each version of jQuery which you load.
```
<script src="jQuery1.3.js"></script>
<script>
jq13 = jQuery.noConflict(true);
</script>
<!-- original author's jquery version -->
<script src="jQuery1.2.3.js"></script>
```
This change will mean that any of the jQuery stuff you want to use will need to be called using `jq13` rather than `$`, e.g.
```
jq13("#id").hide();
```
It's not an ideal situation to have the two versions running on the same page, but if you've no alternative, then the above method should allow you to use two differing versions at once.
> Also out of curiosity, what if we were to use an additional control
> that needed to reference yet another version of jQuery?
If you needed to add another version of jQuery, you could expand on the above:
```
<script src="jQuery1.3.js"></script>
<script>
jq13 = jQuery.noConflict(true);
</script>
<script src="jQuery1.3.1.js"></script>
<script>
jq131 = jQuery.noConflict(true);
</script>
<!-- original author's jquery version -->
<script src="jQuery1.2.3.js"></script>
```
The variables `jq13` and `jq131` would each be used for the version-specific features you require.
It's important that the **jQuery used by the original developer is loaded last** - the original developer likely wrote their code under the assumption that `$()` would be using their jQuery version. If you load another version after theirs, the `$` will be "grabbed" by the last version you load, which would mean the original developer's code running on the latest library version, rendering the `noConflicts` somewhat redundant! | As said ConroyP you can do this with `jQuery.noConflict` but don't forget `var` when declaring variable.
Like this.
```
<script src="jQuery1.3.js"></script>
<script>
var jq13 = jQuery.noConflict(true);
</script>
<!-- original author's jquery version -->
<script src="jQuery1.2.3.js"></script>
```
You can connect all $'s to jq13 by adding (jq13) after function's `})`. like this
```
(function($) {
...
})(jq13);
``` | How do I run different versions of jQuery on the same page? | [
"",
"asp.net",
"javascript",
"jquery",
""
] |
I have a method to save an image, which is meant to deal gracefully with an error, setting $imageSrc to a particular image in the event of failure. My method works fine if the image is present, but no error conditions seems to be handled correctly.
```
$imageSrc = save_pic($PIC_URL, $pk);
function save_pic($pic_url, $pk) {
$imageDir = './';
if (!strlen($pic_url))
return "removed.jpg";
if (!is_dir($imageDir) || !is_writable($imageDir)) {
return "removed.jpg";
}
$image = file_get_contents($pic_url);
if (empty($image)) {
return "removed.jpg";
}
$r = file_put_contents($imageDir.$pk.".jpg", $image);
if ($r) {
return "./$pk.jpg";
} else {
return "removed.jpg";
}
}
```
If the image does not exist, I get :
```
Warning: getimagesize(http://127.0.0.1/555.jpg) [function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
in C:\Program Files\EasyPHP 2.0b1\www\get_auction.php on line 144
Array (
[type] => 2 [message] => getimagesize(http://127.0.0.1/555.jpg)
function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
[file] => C:\Program Files\EasyPHP 2.0b1\www\get_auction.php
[line] => 144
) 1
```
returned.jpg is never returned in any event.
edit: added imageResize code:
```
function imageResize($imageURL, $maxWidth, $maxHeight)
{
global $outputWidth, $outputHeight, $maxWidth, $maxHeight;
$size = getimagesize($imageURL);
if ($size) {
$imageWidth = $size[0];
$imageHeight = $size[1];
$wRatio = $imageWidth / $maxWidth;
$hRatio = $imageHeight / $maxHeight;
$maxRatio = max($wRatio, $hRatio);
if ($maxRatio > 1) {
$outputWidth = $imageWidth / $maxRatio;
$outputHeight = $imageHeight / $maxRatio;
} else {
$outputWidth = $imageWidth;
$outputHeight = $imageHeight;
}
} else {
die(print_r(error_get_last()));
}
}
``` | The problem was not a code issue, but was caused by file corruption. This was determined while testing on other machines. | Are you sure you're writing to the root folder? Because I can't see any problem with your code. `file_get_contents` and `file_put_contents` don't seem to be failing, so your image is being written somewhere. | Problem with php function to catch error on saving image | [
"",
"php",
""
] |
What is the argument against declaring protected-access members on interfaces? This, for example, is invalid:
```
public interface IOrange
{
public OrangePeel Peel { get; }
protected OrangePips Seeds { get; }
}
```
In this example, the interface `IOrange` would guarantee that implementors *at least* provide an `OrangePips` instance to their inheritors. If the implementor wanted to, they could expand the scope to full `public`:
```
public class NavelOrange : IOrange
{
public OrangePeel Peel { get { return new OrangePeel(); } }
protected OrangePips Seeds { get { return null; } }
}
public class ValenciaOrange : IOrange
{
public OrangePeel Peel { get { return new OrangePeel(); } }
public OrangePips Seeds { get { return new OrangePips(6); } }
}
```
The intent of `protected` members on interfaces is to provide a support contract for *inheritors* (sub-classes), for example:
```
public class SpecialNavelOrange : NavelOrange
{
...
// Having a seed value is useful to me.
OrangePips seeds = this.Seeds;
...
}
```
(Admittedly, this wouldn't work for `struct`s)
I can't see much of a case for `private` or `internal` modifiers in interfaces, but supporting both `public` and `protected` modifiers seems perfectly reasonable.
---
I'm going to try explaining the utility of `protected` members on `interface`s by separating them from `interface`s entirely:
Let's imagine a new C# keyword, `support`, to enforce inheritor contracts, so that we declare things as follows:
```
public support IOrangeSupport
{
OrangePips Seeds { get; }
}
```
This would allows us to contract classes to provide protected members to their inheritors:
```
public class NavelOrange : IOrange, IOrangeSupport
{
public OrangePeel Peel { get { return new OrangePeel(); } }
protected OrangePips Seeds { get { return null; } }
}
```
This is not particularly useful, because classes would already imply this contract by providing the `protected` members in the first place.
But then we could also do this:
```
public interface IOrange : IOrangeSupport
{
...
}
```
Thereby applying `IOrangeSupport` to all classes which implement `IOrange` and requiring them to provide particular `protected` members - which is not something we can currently do. | I think everyone hammered the point of an interface having only public members, no implementation details. What you are looking for is an [abstract class](http://msdn.microsoft.com/en-us/library/ms173150.aspx).
```
public interface IOrange
{
OrangePeel Peel { get; }
}
public abstract class OrangeBase : IOrange
{
protected OrangeBase() {}
protected abstract OrangePips Seeds { get; }
public abstract OrangePeel Peel { get; }
}
public class NavelOrange : OrangeBase
{
public override OrangePeel Peel { get { return new OrangePeel(); } }
protected override OrangePips Seeds { get { return null; } }
}
public class ValenciaOrange : OrangeBase
{
public override OrangePeel Peel { get { return new OrangePeel(); } }
protected override OrangePips Seeds { get { return new OrangePips(6); } }
}
```
Edit: It is fair to argue that if we have a PlasticOrange that derives from a class Ornament, it can only implement IOrange and not the Seeds protected method. That is fine. An interface by definition is a contract between a caller and an object, not between a class and its subclasses. The abstract class is as close as we come to this concept. And that is fine. What you are essentially proposing is another construct in the language through which we can switch subclasses from one base class to another without breaking the build. To me, this doesn't make sense.
If you are creating a subclass of a class, the subclass is a specialization of the base class. It should be fully aware of any protected members of the base class. But if you suddenly want to switch the base class out, it makes no sense that the subclass should work with any other IOrange.
I suppose you have a fair question, but it seems like a corner case and I don't see any benefit from it to be honest. | Can't see why would one want this. If you want derived class to provide an implementation of a particular method, go for abstract base classes. Interfaces are just that - interfaces. A public contract, nothing else. Think of interface as of specification which describes how should the implementation look to the outside world. A specification for a two-pin plug does not state (at least I assume that) what it's internal structure should be like. It just must be interface-compatible with a plug socket.
[](https://i.stack.imgur.com/qcE4O.jpg)
(source: [made-in-china.com](http://www.made-in-china.com/image/2f0j00MCetlafAYTWcM/Two-Round-pin-Plug-with-Power-Wire.jpg)) | Why can't I have protected interface members? | [
"",
"c#",
"interface",
"protected",
"access-modifiers",
""
] |
I have large data files stored in S3 that I need to analyze. Each batch consists of ~50 files, each of which can be analyzed independently.
I'd like to setup parallel downloads of the S3 data into the EC2 instance, and setup triggers that start the analysis process on each file that downloads.
Are there any libraries that handle an async download, trigger on complete model?
If not, I'm thinking of setting up multiple download processes with pyprocessing, each of which will download and analyze a single piece of the file. Does that sound reasonable or are there better alternatives? | Answering my own question, I ended up writing a simple modification to the Amazon S3 python library that lets you download the file in chunks or read it line by line. [Available here](http://parand.com/say/index.php/2009/03/13/python-s3-library-for-chunked-streaming-download/). | It sounds like you're looking for [twisted](http://twistedmatrix.com/trac/):
"Twisted is an event-driven networking engine written in Python and licensed under the MIT license."
<http://twistedmatrix.com/trac/>
I've used the twisted python for quite a few asynchronous projects involving both communicating over the Internet and with subprocesses. | Parallel/Async Download of S3 data into EC2 in Python? | [
"",
"python",
"amazon-s3",
"amazon-ec2",
""
] |
I need to be able to create guids on the fly. Is there a way to do that in MFC? I see how to do it in .net, but we haven't gone there yet. If not, do you have pointers to some code I can use? | ```
GUID guid;
HRESULT hr = CoCreateGuid(&guid);
// Convert the GUID to a string
_TUCHAR * guidStr;
UuidToString(&guid, &guidStr);
```
The application is responsible for calling `RpcStringFree` to deallocate the memory allocated for the string returned in the StringUuid parameter. | ```
//don't forget to add Rpcrt4.lib to your project
CString m_ListID(L"error");
RPC_WSTR guidStr;
GUID guid;
HRESULT hr = CoCreateGuid(&guid);
if (hr == S_OK)
{
if(UuidToString(&guid, &guidStr) == RPC_S_OK)
{
m_ListID = (LPTSTR)guidStr;
RpcStringFree(&guidStr);
}
}
``` | How can I create a guid in MFC | [
"",
"c++",
"mfc",
"guid",
""
] |
Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, `dir()` stuff, `help() stuff`, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling `cls` on Windows or `clear` on Linux, but I was hoping there was something I could command the interpreter itself to do.
**Note:** I'm running on Windows, so `Ctrl` + `L` doesn't work. | As you mentioned, you can do a system call:
For Windows:
```
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()
```
For Linux it would be:
```
>>> import os
>>> clear = lambda: os.system('clear')
>>> clear()
``` | Here is something handy that is a little more cross-platform:
```
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
# Now, to clear the screen
cls()
``` | How can I clear the interpreter console? | [
"",
"python",
"windows",
"console",
""
] |
I'm trying to use String.Format("{0:c}", somevalue) in C# but am having a hard time figuring out how to configure the output to meet my needs. Here are my needs:
1. 0 outputs to blank
2. 1.00 outputs to $1.00
3. 10.00 outputs to $10.00
4. 100.00 outputs to $100.00
5. 1000.00 outputs to $1,000.00
I've tried String.Format("{0:c}", somevalue) but for zero values it outputs $0.00 which is not what I want. I've also tried String.Format("{0:$0,0.00;$(0,0.00);#}", somevalue), but for 1.0 it outputs $01.00. String.Format("{0:$0.00;$(0.00);#}", somevalue) works for most cases, but when somevalue is 1000.00 the output is $1000.00.
Is there some format that will fit all 5 cases above? All of the documentation I've read only details the basics and doesn't touch on this type of scenario. | If you use
```
string.Format("{0:$#,##0.00;($#,##0.00);''}", value)
```
You will get "" for the zero value and the other values should be formatted properly too. | Try something like this:
```
String currency = (number == 0) ? String.Empty : number.ToString("c");
``` | Need a custom currency format to use with String.Format | [
"",
"c#",
"currency",
"string.format",
""
] |
Occasionally I have to do some profiling work on Java code, and I would like to know why I should have my boss investigate in a commercial profiler as opposed to just use the one in Netbeans or JConsole?
What would the killer features be that would warrant the investment? | I have experience using both NetBeans profiler and JProbe. For performance profiling I have found Netbeans quite useful but where JProbe is superior is for memory profiling.
JProbe has superior tools for comparing heap snapshots and finding the root cause of a memory leak. For example, in JProbe you can view heap shapshots visually as a graph, select nodes to investigate and then delete references to see if the instance could then be garbage collected. | In my experience with JProfiler, it's just an all-round slicker experience than the NetBeans profiler. It's easier to get started, easier to interpret the information and, although I haven't measured it, it seems that JProfiler has less of a negative impact on the performance of the application being profiled.
Also, JProfiler integrates nicely with IntelliJ IDEA. I have to use NetBeans to use the NetBeans profiler, which is an inconvenience because I have to manually configure a free-form project to match the layout of my project.
The NetBeans profiler is usable. Unlike IntelliJ, I wouldn't buy a JProfiler licence for my personal projects because, unlike an IDE, it's not a tool you use all day every day. However, for paid work there's no reason not to buy a better tool. It's not expensive compared to the cost of a developer's time. | What advantages have a commercial Java profiler over the free ones, e.g. the one in Netbeans? | [
"",
"java",
"profiler",
""
] |
I am a noob when it comes to SQL syntax.
I have a table with lots of rows and columns of course :P
Lets say it looks like this:
```
AAA BBB CCC DDD
-----------------------
Row1 | 1 A D X
Row2 | 2 B C X
Row3 | 3 C D Z
```
Now I want to create an advanced select statement that gives me this combined (pseudo SQLish here):
```
select 'Test1', * from TABLE Where CCC='D' AND DDD='X'
select 'Test2', * from TABLE Where CCC<>'D' AND DDD='X'
```
The output would be:
```
Test1, 1, A, D, X
Test2, 2, B, C, X
```
How would I combine those two select statements into one nice select statement?
Would it work if I complicated the SQL like below (because my own SQL statement contains an exists statement)? I just want to know how I can combine the selects and then try to apply it to my somewhat more advanced SQL.
```
select 'Test1', * from TABLE Where CCC='D' AND DDD='X' AND exists(select ...)
select 'Test2', * from TABLE Where CCC<>'D' AND DDD='X' AND exists(select ...)
```
My REAL SQL statement is this one:
```
select Status, * from WorkItems t1
where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
```
which gives me a result. But I want to combine it with a copy of this select statement with an added AND on the end and the 'Status' field would be changed with a string like 'DELETED'.
```
select 'DELETED', * from WorkItems t1
where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)
``` | You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the `WHERE` clause, and then `UNION` them together:
```
select
'Test1', *
from
TABLE
Where
CCC='D' AND DDD='X' AND exists(select ...)
UNION
select
'Test2', *
from
TABLE
Where
CCC<>'D' AND DDD='X' AND exists(select ...)
```
This might be an issue, because you are going to effectively scan/seek on TABLE twice.
The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:
```
select
case
when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1'
when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2'
end,
*
from
TABLE
Where
(CCC='D' AND DDD='X' AND exists(select ...)) or
(CCC<>'D' AND DDD='X' AND exists(select ...))
```
The catch here being that you will have to duplicate the filter conditions in the `CASE` statement and the `WHERE` statement. | If they are from the same table, I think [`UNION`](http://www.devguru.com/technologies/t-sql/7118.asp) is the command you're looking for.
(If you'd ever need to select values from columns of different tables, you should look at [`JOIN`](http://www.w3schools.com/Sql/sql_join.asp) instead...) | How do I combine 2 select statements into one? | [
"",
"sql",
"select",
"conditional-statements",
""
] |
I would like to be able to declare a function as
```
void foo(<any value type>[] data){}
```
in C# 2.0. If I declare it as
```
void foo(ValueType[] data){}
```
it compiles, but then the elements in data[] are treated as though they're derived from `object`, e.g. I can't say something like
```
fixed (void* pData = data){}
```
I'd like to avoid taking the void\* as the parameter -- I just want to be able to accept any value-type array and then do unmanaged things to it.
ETA: Also, this has the same problem:
```
public static unsafe void foo<T>(T[] data) where T:struct{
fixed(void *p = data){}
}
```
in case you were wondering. Fixed fails because it's treated as a managed type -- CS0208, cannot declare a pointer to a managed type. See "mm" below. I think he's right... it probably just can't be done. | I don't think this is possible using C#. Structs do not inherit (however loosely) from System.ValueType until after compile time so you can't match Foo's method signature via polymorphism. Generics are also out according to the language specification:
> "An unmanaged-type is any type that isn’t a reference-type, a **type-parameter**, or a generic struct-type and
> contains no fields whose type is not an unmanaged-type."
So that's why you can't take the address of T[] regardless of the struct constraint.
You could declare a struct type (say, Bar) as the argument to Foo, compile the code, and change the method signature at the IL level:
`.method private hidebysig static void Foo(valuetype [mscorlib]System.ValueType[] args) cil managed`
And then the call as well:
`IL_0020: call void ConsoleApplication1.Program::Foo(valuetype [mscorlib]System.ValueType[])`
While I was able to run the resulting program I don't know what kind of side effects this has. Also, even if you could reference the modified function you wouldn't be able to call it from C# because again structs don't inherit from System.ValueType until after compilation so the method signature wouldn't match. | ```
public void foo<T>(params T[] args) where T : struct {
}
public void SomeMethod() {
foo(1, 2, 3, 4);
}
```
You shouldn't have to enter the generic parameter because the compiler will pick up on the type from the first parameter of foo. | Take an array of any value type as formal parameter | [
"",
"c#",
"declaration",
"value-type",
""
] |
I have a webpage with an elastic layout that changes its width if the browser window is resized.
In this layout there are headlines (`h2`) that will have a variable length (actually being headlines from blogposts that I don't have control over). Currently - if they are wider than the window - they are broken into two lines.
Is there an elegant, tested (cross-browser) solution - for example with jQuery - that shortens the innerHTML of that headline tag and adds "..." if the text would be too wide to fit into one line at the current screen/container width? | I've got a solution working in FF3, Safari and IE6+ with single and multiline text
```
.ellipsis {
white-space: nowrap;
overflow: hidden;
}
.ellipsis.multiline {
white-space: normal;
}
<div class="ellipsis" style="width: 100px; border: 1px solid black;">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<div class="ellipsis multiline" style="width: 100px; height: 40px; border: 1px solid black; margin-bottom: 100px">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<script type="text/javascript" src="/js/jquery.ellipsis.js"></script>
<script type="text/javascript">
$(".ellipsis").ellipsis();
</script>
```
jquery.ellipsis.js
```
(function($) {
$.fn.ellipsis = function()
{
return this.each(function()
{
var el = $(this);
if(el.css("overflow") == "hidden")
{
var text = el.html();
var multiline = el.hasClass('multiline');
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(multiline ? el.width() : 'auto')
.height(multiline ? 'auto' : el.height())
;
el.after(t);
function height() { return t.height() > el.height(); };
function width() { return t.width() > el.width(); };
var func = multiline ? height : width;
while (text.length > 0 && func())
{
text = text.substr(0, text.length - 1);
t.html(text + "...");
}
el.html(t.html());
t.remove();
}
});
};
})(jQuery);
``` | The following CSS only solution for truncating text on a single line works with all browers listed at [http://www.caniuse.com](https://www.caniuse.com/#search=ellipsis) as of writing with the exception of Firefox 6.0. Note that JavaScript is totally unnecessary unless you need to support wrapping multiline text or earlier versions of Firefox.
```
.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
}
```
If you need support for earlier versions of Firefox check out [my answer on this other question](https://stackoverflow.com/a/1101702/2766). | Insert ellipsis (...) into HTML tag if content too wide | [
"",
"javascript",
"html",
"ellipsis",
"elasticlayout",
""
] |
### Duplicate of: [How can I evaluate a C# expression dynamically?](https://stackoverflow.com/questions/53844/how-can-i-evaluate-a-c-expression-dynamically)
See also: [C# eval equivalent?](https://stackoverflow.com/questions/4629/c-eval-equivalent)
---
How to evaluate expression. Maybe like:
```
int a=1;
int b=3;
int c=Eval("a+b");
```
or
```
int c=int.parse("1+3*(2+3)");
```
This seems stupid to me. is it possible in c#? | You can take code, and using the CSharpCodeProvider write an Eval function that actually compiles your code into an in-memory assembly and then executes that code.
See this [CodeProject article](http://www.codeproject.com/KB/cs/evalcscode.aspx) for sample source. | Not directly. C# contains no runtime compiler.
There is [an open source project](http://tirania.org/blog/archive/2008/Sep-10.html) attached to Mono that will do this. | in c#: expression evaluation function like flash script | [
"",
"c#",
"eval",
""
] |
I have multiple dropdownlist in a page and would like to disable all if user selects a checkbox which reads disable all. So far I have this code and it is not working. Any suggestions?
```
foreach (Control c in this.Page.Controls)
{
if (c is DropDownList)
((DropDownList)(c)).Enabled = false;
}
``` | Each control has child controls, so you'd need to use recursion to reach them all:
```
protected void DisableControls(Control parent, bool State) {
foreach(Control c in parent.Controls) {
if (c is DropDownList) {
((DropDownList)(c)).Enabled = State;
}
DisableControls(c, State);
}
}
```
Then call it like so:
```
protected void Event_Name(...) {
DisableControls(Page,false); // use whatever top-most control has all the dropdowns or just the page control
} // divs, tables etc. can be called through adding runat="server" property
``` | I know this is an old post but this is how I have just solved this problem. AS per the title "How do I disable all controls in ASP.NET page?" I used Reflection to achieve this; it will work on all control types which have an Enabled property. Simply call DisableControls passing in the parent control (I.e., Form).
C#:
```
private void DisableControls(System.Web.UI.Control control)
{
foreach (System.Web.UI.Control c in control.Controls)
{
// Get the Enabled property by reflection.
Type type = c.GetType();
PropertyInfo prop = type.GetProperty("Enabled");
// Set it to False to disable the control.
if (prop != null)
{
prop.SetValue(c, false, null);
}
// Recurse into child controls.
if (c.Controls.Count > 0)
{
this.DisableControls(c);
}
}
}
```
VB:
```
Private Sub DisableControls(control As System.Web.UI.Control)
For Each c As System.Web.UI.Control In control.Controls
' Get the Enabled property by reflection.
Dim type As Type = c.GetType
Dim prop As PropertyInfo = type.GetProperty("Enabled")
' Set it to False to disable the control.
If Not prop Is Nothing Then
prop.SetValue(c, False, Nothing)
End If
' Recurse into child controls.
If c.Controls.Count > 0 Then
Me.DisableControls(c)
End If
Next
End Sub
``` | How do I disable all controls in ASP.NET page? | [
"",
"c#",
"webforms",
"asp.net-controls",
""
] |
How does one check to see if a user has typed in the right password to log in?
This is what (out of a bunch of combinations...) I am doing:
```
<?
$login = $_POST['login'];
$password = $_POST['password'];
mysql_connect('localhost', 'root', 'abc123');
mysql_select_db('aun_vox') or die(mysql_error());
$q = mysql_query("SELECT password FROM customer WHERE login='$login'");
$db_pass = mysql_result($q, 0);
if(md5($password) == $db_pass)
{
echo "You did it.";
}
else echo "Wrong.";
?>
```
As I can see from the ouput, there's something wrong in the `mysql_result` bit, but I can't figure out the right way.
Can someone please help. | I see you are storing a hash of the password in the database, but for the benefit of other readers, *never* store passwords in plain text in the database. You don't want to be [like Monster.com.uk](http://www.dailymail.co.uk/sciencetech/article-1128822/Hackers-steal-details-4-5m-users-Monster-uk-Britains-biggest-cyber-theft-case.html)!
You should use a stronger hashing function than `MD5()`. Ideally you should use SHA256. This hash method is available in PHP using the [`hash()`](http://php.net/hash) function.
You should also apply a random [salt](http://en.wikipedia.org/wiki/Salt_(cryptography)) to the password. Store a different salt value for each user's account. This helps to defeat dictionary attacks and [rainbow table](http://en.wikipedia.org/wiki/Rainbow_table) attacks.
You should learn to use the [mysqli](http://php.net/mysqli) extension instead of the old mysql extension. Mysqli supports parameterized queries, so you can reduce vulnerability to some SQL injection attacks.
Here is some example code. I haven't tested it, but it should be pretty close to working:
```
$input_login = $_POST['login'];
$input_password = $_POST['password'];
$stmt = $mysqli->prepare("SELECT password, salt FROM customer WHERE login = ?");
$stmt->bind_param("s", $input_login);
$stmt->execute();
$stmt->bind_result($password_hash, $salt);
while ($stmt->fetch()) {
$input_password_hash = hash('sha256', $input_password . $salt);
if ($input_password_hash == $password_hash) {
return true;
}
// You may want to log failed password attempts here,
// for security auditing or to lock an account with
// too many attempts within a short time.
}
$stmt->close();
// No rows matched $input_login, or else password did not match
return false;
```
---
Some other people suggest the query should test for `login = ? AND password = ?` but I don't like to do that. If you do this, you can't know if the lookup failed because the login didn't exist, or because the user provided a wrong password.
Of course you shouldn't reveal to the user which caused the failed login attempt, but *you* may need to know, so you can log suspicious activity.
---
@Javier says in his answer that you shouldn't retrieve the password (or password hash in this case) from the database. I don't agree.
Javier shows calling `md5()` in PHP code and sending that the resulting hash string to the database. But this doesn't support salting the password easily. You have to do a separate query to retrieve this user's salt before you can do the hash in PHP.
The alternative is sending the *plaintext* password over the network from your PHP app to your database server. Anyone wiretapping your network can see this password. If you have SQL queries being logged, anyone who gains access to the logs can see the password. Motivated hackers can even dumpster-dive to find old filesystem backup media, and might read the log files that way!
The lesser risk is to fetch the password hash string from the database into the PHP app, compare it to the hash of the user's input (also in PHP code), and then discard these variables. | Firstly, make sure you properly escape your variables before using them in the query - use mysql\_real\_escape\_string().
Then, why not use the MySQL MD5 function to check for a valid login in your query?
```
SELECT login FROM customer WHERE login='$login' AND password = MD5('$password')
```
Then just use mysql\_num\_rows() to count the number of returned rows. | PHP & MySQL compare password | [
"",
"php",
"mysql",
"authentication",
"passwords",
""
] |
Should I use old synchronized Vector collection, ArrayList with synchronized access or Collections.synchronizedList or some other solution for concurrent access?
I don't see my question in Related Questions nor in my search ([Make your collections thread-safe?](https://stackoverflow.com/questions/164088/make-your-collections-thread-safe "Make your collections thread-safe?") isn't the same).
Recently, I had to make kind of unit tests on GUI parts of our application (basically using API to create frames, add objects, etc.).
Because these operations are called much faster than by a user, it shown a number of issues with methods trying to access resources not yet created or already deleted.
A particular issue, happening in the EDT, came from walking a linked list of views while altering it in another thread (getting a ConcurrentModificationException among other problems).
Don't ask me why it was a linked list instead of a simple array list (even less as we have in general 0 or 1 view inside...), so I took the more common ArrayList in my question (as it has an older cousin).
Anyway, not super familiar with concurrency issues, I looked up a bit of info, and wondered what to choose between the old (and probably obsolete) Vector (which has synchronized operations by design), ArrayList with a `synchronized (myList) { }` around critical sections (add/remove/walk operations) or using a list returned by Collections.synchronizedList (not even sure how to use the latter).
I finally chose the second option, because another design mistake was to expose the object (getViewList() method...) instead of providing mechanisms to use it.
But what are the pros and cons of the other approaches?
---
[EDIT] Lot of good advices here, hard to select one. I will choose the more detailed and providing links/food for thoughts... :-) I like Darron's one too.
To summarize:
* As I suspected, Vector (and its evil twin, Hashtable as well, probably) is largely obsolete, I have seen people telling its old design isn't as good as newer collections', beyond the slowness of synchronization forced even in single thread environment. If we keep it around, it is mostly because older libraries (and parts of Java API) still use it.
* Unlike what I thought, Collections.synchronizedXxxx aren't more modern than Vector (they appear to be contemporary to Collections, ie. Java 1.2!) and not better, actually. Good to know. In short, I should avoid them as well.
* Manual synchronization seems to be a good solution after all. There might be performance issues, but in my case it isn't critical: operations done on user actions, small collection, no frequent use.
* java.util.concurrent package is worth keeping in mind, particularly the CopyOnWrite methods.
I hope I got it right... :-) | Vector and the List returned by Collections.synchronizedList() are morally the same thing. I would consider Vector to be effectively (but not actually) deprecated and always prefer a synchronized List instead. The one exception would be old APIs (particularly ones in the JDK) that require a Vector.
Using a naked ArrayList and synchronizing independently gives you the opportunity to more precisely tune your synchronization (either by including additional actions in the mutually exclusive block or by putting together multiple calls to the List in one atomic action). The down side is that it is possible to write code that accesses the naked ArrayList outside synchronization, which is broken.
Another option you might want to consider is a CopyOnWriteArrayList, which will give you thread safety as in Vector and synchronized ArrayList but also iterators that will not throw ConcurrentModificationException as they are working off of a non-live snapshot of the data.
You might find some of these recent blogs on these topics interesting:
* [Java Concurrency Bugs #3 - atomic + atomic != atomic](http://tech.puredanger.com/2009/01/30/java-concurrency-bugs-atomic/)
* [Java Concurrency Bugs #4: ConcurrentModificationException](http://tech.puredanger.com/2009/02/02/java-concurrency-bugs-concurrentmodificationexception/)
* [CopyOnWriteArrayList concurrency fun](http://tech.puredanger.com/2009/02/02/copyonwritearraylist-concurrency-fun/) | I strongly recommend the book "[Java Concurrency in Practice](http://jcip.net)".
Each of the choices has advantages/disadvantages:
1. Vector - considered "obsolete". It may get less attention and bug fixes than more mainstream collections.
2. Your own synchronization blocks - Very easy to get incorrect. Often gives poorer performance than the choices below.
3. Collections.synchronizedList() - Choice 2 done by experts. This is still not complete, because of multi-step operations that need to be atomic (get/modify/set or iteration).
4. New classes from java.util.concurrent - Often have more efficient algorithms than choice 3. Similar caveats about multi-step operations apply but tools to help you are often provided. | Best way to control concurrent access to Java collections | [
"",
"java",
"collections",
"concurrency",
""
] |
I have a list with multiple class that contain a Property that is an Integer (Id).
I have a List of Integer too.
Now, I would like to trim the List of my object to only those class that has the Property in the list of the integer.
Example:
```
List of MyObject
[MyObjectA].Id = 1
[MyObjectB].Id = 2
[MyObjectC].Id = 3
[MyObjectD].Id = 4
List of Integer
1
2
Final list should be
[MyObjectA]
[MyObjectB]
```
How can I do it? | You could use contains:
```
var finalList = originalList.Where(x => idList.Contains(x.Id)).ToList();
```
Or a join:
```
var finalList = (from entry in originalList
join id in idList on entry.Id equals id
select entry).ToList();
``` | Or if you have two Lists each with Properties, try this:
```
List<someObj1> firstList ... //assume this has items
List<otherObj2> secondList ... //assume this has items
var finalList = firstList.Where(so1 => secondList.Select(oo2 => oo2.Prop1).Contains(so1.Prop1) && so1.Prop2 == "foo");
//Prop1 is a property of the someObj1 and otherObj objects.
//Prop2 is a property of the someObj1 object.
``` | How can I get data from a list with a where clause to another list? | [
"",
"c#",
"linq",
".net-3.5",
"c#-3.0",
""
] |
I'm building Boost (I'm using System and FileSystem) for MinGW using bjam:
```
bjam --toolset=gcc stage
```
And it builds fine, but I want to be able to statically link to it (I have to have a single file for the final product) so I tried:
```
bjam --link=static --toolset=gcc stage
```
But I get the same output. Any ideas?
*edit* second question in a row I've answered moments after posting :p guess I'll leave this up here for others though.
```
bjam --build-type=complete --toolset=gcc stage
```
Will build both dynamic and static for sure. | I think link is a property as opposed to an option for bjam. That means that there should be no -- before it.
This is my command line for building only static libraries (visual c++ though):
```
bjam install --toolset=msvc variant=release link=static threading=multi runtime-link=static
```
Mapping that to your original build command I would say it should look something like this:
```
bjam --toolset=gcc link=static stage
```
or perhaps:
```
bjam stage --toolset=gcc link=static
```
Try running
```
bjam --help
```
for more info on properties and options for bjam. | Just want note that with the newer boost (Feb 2011) you need to build bjam as well now.. for some reason the current downloadable bjam doesn't work cleanly.
So first:
`cd ...\boost_1_45_0\tools\build\v2\engine\src`
`build.bat mingw`
Youll need to add bjam to the PATH (from control panel, not just on the cmd prompt). Then
`cd ...\boost_1_45_0\`
`bjam --build-type=complete --toolset=gcc stage`
My setup is Vista, Boost 1.45, MinGW 4.5, and building from cmd.exe not msys.
<http://code-slim-jim.blogspot.com/2011/02/boost-in-vista-using-mingw-and-cmdexe.html> | Building Boost for static linking (MinGW) | [
"",
"c++",
"boost",
"build",
"linker",
"bjam",
""
] |
Is there a way to attach an image to an html formatted email message created in PHP?
We need to ensure that a corporate logo is on emails sent to clients who may not have access to the internet whilst reading their email (They will obviously have it to download the files). | Try the PEAR [Mail\_Mime](http://pear.php.net/package/Mail_Mime) package, which can [embed images for you](http://pear.php.net/manual/en/package.mail.mail-mime.addhtmlimage.php).
You need to use the [addHTMLImage()](https://pear.php.net/manual/en/package.mail.mail-mime.addhtmlimage.php) method and pass a content id (cid), which is a unique string of text you will also use in your img's src attribute as a `cid:` URL. For example:
```
include('Mail.php');
include "Mail/mime.php";
$crlf = "\r\n";
$hdrs = array(
'From' => 'foo@bar.org',
'Subject' => 'Mail_mime test message'
);
$mime = new Mail_mime($crlf);
//attach our image with a unique content id
$cid="mycidstring";
$mime->addHTMLImage("/path/to/myimage.gif", "image/gif", "", true, $cid);
//now we can use the content id in our message
$html = '<html><body><img src="cid:'.$cid.'"></body></html>';
$text = 'Plain text version of email';
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
$mail =& Mail::factory('mail');
$mail->send('person@somewhere.org', $hdrs, $body);
``` | It's probably easiest to use some library that can deal with email attachments. For example, PEAR's [Mail\_Mime](http://pear.php.net/package/Mail_Mime). | PHP Attaching an image to an email | [
"",
"php",
"email",
"attachment",
""
] |
We are trying to use Log4Net to log from our IIS 6-deployed WCF Application. We are trying to log to a file, but can't seem to get the log files to be created, let alone see the logging output in them. The pertinent pieces of out web.config are:
```
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
...
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.TraceLoggerFactoryAdapter, Common.Logging">
<arg key="level" value="INFO" />
<arg key="showLogName" value="true" />
<arg key="showDataTime" value="true" />
<arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:fff" />
</factoryAdapter>
</logging>
</common>
<log4net>
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="c:\logs\ApplicationInfoTest.log" />
<threshold value="INFO" />
<param name="AppendToFile" value="true" />
<param name="DatePattern" value="ddMMyyyy" />
<param name="MaxSizeRollBackups" value="10" />
<param name="MaximumFileSize" value="10MB" />
<param name="RollingStyle" value="Size" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="\r\n\r\n---------------------------------------------\r\n" />
<param name="Footer" value="\r\n---------------------------------------------\r\n\r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
```
With this configuration we can see INFO level logging coming out of our application when using DebugView, but it is clear that this is from the
piece and not the
piece.
Is there something that we have failed to set up in web.config? Is it a permissions issue with the directory we have created for the logs to be written to?
Please point out our obvious mistake. | Use [ProcessMonitor from SysInternals](http://live.sysinternals.com/tools/procmon.exe) to find out where permissions are being refused
(Potentially you can determine the same info by attaching a debugger and trapping on exceptions, not in Just My Code)
Are you sure that the process under which the service is running has permissions on the folder you're trying to write to? | I have also had to add this line to the AssemblyInfo.cs file of my application in order to get log4net working.
```
// LOG 4 net config
[assembly:log4net.Config.XmlConfigurator(Watch=true)]
``` | Can't get Log4Net to work in our WCF application | [
"",
"c#",
"iis-6",
"web-config",
"log4net",
""
] |
I'm developing some lower end code in my system that uses multiple child classes of the php exception class. Essentially I have the exceptions broken up to a few categories. What I'm wanting to do is two things.
1. I need all exceptions that are fired in the application to be handled in a single place.
2. I need to be able to log and then handle/generate the view for the user to receive feedback on the apps. error.
What I'm wondering is should I have some sort of try/catch encapsulating the application? I don't like that idea at all, it sounds like a very crappy implementation. I also don't like the idea of set\_exception\_handler unless i can sett the function to be a method of an object. The reason for this is that if I designate a function to handle the exceptions this will be the first function in the application. Everything else is a method of an object.
Hopefully I've provided enough details about the scenario. I'm trying to keep this clean and follow best practices. This code will be going OSS so I don't feel like writing it 10 times :) | 1. Run your web requests through a [Front Controller script](https://stackoverflow.com/questions/20277102/proper-separation-difference-between-index-php-and-front-controller/20299496#20299496)
2. call [`set_exception_handler`](http://www.php.net/set_error_handler) early in execution (don't forget to account for `error_reporting()`). `set_exception_handler` takes as its paramter what php calls a ["callback"](http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback). You can pass an object method like so:
```
// $object->methodName() will be called on errors
set_exception_handler(array($object, 'methodName'));
```
3. Wrap your dispatching code with `try/catch` to catch any code that DOES throw exceptions. The catch part of your code will catch all your own codes' exceptions, plus *some* php errors that didn't generate an exception natively (eg `fopen` or something), thanks to your `set_exception_handler` call above. The php manual states:
> The following error types cannot be
> handled with a user defined function:
> E\_ERROR, E\_PARSE, E\_CORE\_ERROR,
> E\_CORE\_WARNING, E\_COMPILE\_ERROR,
> E\_COMPILE\_WARNING, and most of
> E\_STRICT raised in the file where
> set\_error\_handler() is called.
4. Log errors as necessary.
5. Create an error page template (the "View") that operates on an Exception object (the "Model") and pretty prints the whole stack trace for you, in development. Create a different template that goes to production. Branch on your environment, for example:
```
catch(Exception $e) {
// log error as necessary here.
if("in developement") {
// $e would be available to your template at this point
include "errortemplates/dev.php";
} else {
include "errortemplates/prod.php";
}
}
``` | There's more specific information about PHP's "callbacks" [here](https://www.php.net/manual/en/language.pseudo-types.php#language.types.callback "here"). To use a static method, the callback is something like
```
<?php
set_exception_handler(array('MyClass','staticMethod'));
?>
```
To use a method from an instantiated object, it's:
```
<?php
set_exception_handler(array($myObject, 'objectMethod'));
?>
```
And to use a global function, it's just:
```
<?php
set_exception_handler('my_global_function');
?>
``` | Exceptions in PHP - Try/Catch or set_exception_handler? | [
"",
"php",
"exception",
""
] |
I currently learning ASP.NET MVC . I wondered if it is possible when a form is submitted to the get the id of the new record and then redirect to a new page with the new record id?
The information is entered into the database correctly, but I’m not sure how to get the id?
For example, complete a new customer details form and then redirect the page to an orders form where new orders can be added for the customer. | How are you accessing the database? If you are using an ORM (such as NHibernate or LINQ to SQL) then the object should have it's ID property updated after you insert it into the database.
If you are hand rolling the SQL then you need to do a select in the same statement as the insert of:
```
insert into ...
select scope_identity()
```
This will return the ID of the row you have just created.
Then you can do this within your action:
```
return RedirectToAction("YourActionName", new {id});
```
With the ID retrieved either from the saved object or the return value of the SQL. Whichever fits your scenario.
**Edit**
As you've mentioned you are using NHibernate then you can do this:
```
var myNewObject = // some way of creating the object
// some way of saving the object
// at this point NHibernate will have set the ID of the object for you
return RedirectToAction("YourActionName", new { id = myNewObject.Id });
``` | One question from me: What do you use for the DB layer? That will tell us how to better answer your question.
For the redirect, once you have your ID you could use:
```
return Redirect(string url); OR RedirectToAction(string actionPath)
```
where url is a combination of path and your new id. | ASP.NET MVC - Form Submission, Retrieve Database ID, and Redirect | [
"",
"c#",
"asp.net-mvc",
""
] |
I have come across this [PHP code to check email address using SMTP without sending an email](http://www.webdigi.co.uk/blog/2009/how-to-check-if-an-email-address-exists-without-sending-an-email/).
Has anyone tried anything similar or does it work for you? Can you tell if an email customer / user enters is correct & exists? | There are two methods you can *sometimes* use to determine if a recipient actually exists:
1. You can connect to the server, and issue a `VRFY` command. Very few servers support this command, but it is intended for exactly this. If the server responds with a 2.0.0 DSN, the user exists.
```
VRFY user
```
2. You can issue a `RCPT`, and see if the mail is rejected.
```
MAIL FROM:<>
RCPT TO:<user@domain>
```
If the user doesn't exist, you'll get a 5.1.1 DSN. However, just because the email is not rejected, does not mean the user exists. Some server will silently discard requests like this to prevent enumeration of their users. Other servers cannot verify the user and have to accept the message regardless.
There is also an antispam technique called greylisting, which will cause the server to reject the address initially, expecting a real SMTP server would attempt a re-delivery some time later. This will mess up attempts to validate the address.
Honestly, if you're attempting to validate an address the best approach is to use a simple regex to block obviously invalid addresses, and then send an actual email with a link back to your system that will validate the email was received. This also ensures that they user entered their actual email, not a slight typo that happens to belong to somebody else. | Other answers here discuss the various problems with trying to do this. I thought I'd show how you might try this in case you wanted to learn by doing it yourself.
You can connect to an mail server via telnet to ask whether an email address exists. Here's an example of testing an email address for `stackoverflow.com`:
```
C:\>nslookup -q=mx stackoverflow.com
Non-authoritative answer:
stackoverflow.com MX preference = 40, mail exchanger = STACKOVERFLOW.COM.S9B2.PSMTP.com
stackoverflow.com MX preference = 10, mail exchanger = STACKOVERFLOW.COM.S9A1.PSMTP.com
stackoverflow.com MX preference = 20, mail exchanger = STACKOVERFLOW.COM.S9A2.PSMTP.com
stackoverflow.com MX preference = 30, mail exchanger = STACKOVERFLOW.COM.S9B1.PSMTP.com
C:\>telnet STACKOVERFLOW.COM.S9A1.PSMTP.com 25
220 Postini ESMTP 213 y6_35_0c4 ready. CA Business and Professions Code Section 17538.45 forbids use of this system for unsolicited electronic mail advertisements.
helo hi
250 Postini says hello back
mail from: <me@myhost.com>
250 Ok
rcpt to: <fake@stackoverflow.com>
550-5.1.1 The email account that you tried to reach does not exist. Please try
550-5.1.1 double-checking the recipient's email address for typos or
550-5.1.1 unnecessary spaces. Learn more at
550 5.1.1 http://mail.google.com/support/bin/answer.py?answer=6596 w41si3198459wfd.71
```
Lines prefixed with numeric codes are responses from the SMTP server. I added some blank lines to make it more readable.
Many mail servers will not return this information as a means to prevent against email address harvesting by spammers, so you cannot rely on this technique. However you may have some success at cleaning out some obviously bad email addresses by detecting invalid mail servers, or having recipient addresses rejected as above.
Note too that mail servers may blacklist you if you make too many requests of them.
---
In PHP I believe you can use `fsockopen`, `fwrite` and `fread` to perform the above steps programmatically:
```
$smtp_server = fsockopen("STACKOVERFLOW.COM.S9A1.PSMTP.com", 25, $errno, $errstr, 30);
fwrite($smtp_server, "helo hi\r\n");
fwrite($smtp_server, "mail from: <me@myhost.com>\r\n");
fwrite($smtp_server, "rcpt to: <fake@stackoverflow.com>\r\n");
``` | How to check if an email address exists without sending an email? | [
"",
"php",
"email",
"smtp",
"telnet",
"email-validation",
""
] |
I have a WebBrowser control that is created and added to the form during run-time.
How do I connect this control to subroutine that can handle its events at run-time? | Use [AddHandler](http://msdn.microsoft.com/en-us/library/7taxzxka(VS.80).aspx)
e.g.
```
AddHandler Obj.Ev_Event, AddressOf EventHandler
```
and when you want to get rid of it (and you should get rid of it when you're done using it)
```
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
```
in your case, you might have something like
```
Dim web as New WebBrowser()
AddHandler web.DocumentCompleted, AddressOf HandleDocumentCompleted
```
assuming you'd created an event handler called HandleDocumentCompleted
Depending on your needs, you could also use the [WithEvents](http://msdn.microsoft.com/en-us/library/stf7ebaz(VS.71).aspx) keyword when you declare your webbrowser; see the [documentation](http://msdn.microsoft.com/en-us/library/stf7ebaz(VS.71).aspx). | An alternative to using `AddHandler` is the declarative events syntax in VB. To use it, you *declare* the control (as a private member), using the `WithEvents` keyword. Then, the `Handles` keyword can be used on methods to handle the appropriate events:
```
Private WithEvents m_WebBrowser As WebBrowser
Private Sub WebBrowser_Navigate(ByVal sender As Object, ByVal e As WebBrowserNavigatedEventArgs) Handles m_WebBrowser.Navigate
MsgBox("Hi there")
End Sub
Private Sub SomeActionThatCreatesTheControl()
m_WebBrowser = New WebBrowser()
End Sub
```
There are mainly two advantages to this method:
* No need for `RemoveHandler`,
* No need to wire all event handlers manually: this is done automatically. | Handle events for dynamic (run-time) controls - VB.NET | [
"",
"c#",
"vb.net",
"dynamic",
"runtime",
"controls",
""
] |
I let a user reconfigure the location of a set of rows in a table by giving them ability to move them up and down. The changes are done by swapping nodes in the DOM.
After the user has moved rows around, when I do a view source, I see the HTML in the original state (before the user made any changes).
Can someone explain why that is? My understanding was when we do any DOM operations, the underlying HTML will be changed as well.
**EDIT: Does that mean on the server side, when attempt to get the state after user's changes, I will be able to get what I need? I am using C#/ASP.NET. Could it be because this is a HTML table (not ASP.NET Server control), that it's not maintaining the state of the changes?** | When you view source, you're viewing the content that the browser downloaded initially. To see the current state, use a plugin like [Firebug](https://addons.mozilla.org/firefox/addon/1843) for Firefox or [DebugBar](http://www.debugbar.com/) for IE | @Your edit:
Unless you have some script that tells the server what the updated order is (i.e. javascript makes a call to a server side script, passing the new order to it), your server will not have any way of knowing what the user did. | DOM and Javascript | [
"",
"javascript",
"dom",
""
] |
I am deciding on how to develop a GUI for a small c++/win32 api project (working Visual Studio C++ 2008). The project will only need a few components to start off the main process so it will be very light weight (just 1 button and a text box pretty much...). My question is this:
I don't have experience developing GUIs on windows but I can learn easily. So, what should I use? A Visual editor (drag and drop code generationg: my preference for desktop GUI designing by far (java/swing)). Or should I use a speicific library? Either way, WHICH library or visual editor should I use? I heard someone mention writing the GUI in C#, then calling the C++ code... the thing is, that this is such a simple GUI I would find it easier to just keep it all in C++, but I'm open to whatever the best suggestion is. | If you're doing a very simple GUI and you're already using Visual Studio then it may make sense to just go with MFC. You can just use the Visual Studio MFC wizard to create a dialog based application, drop two controls on it and away you go.
MFC is dated and has its fair share of annoyances, but it will certainly do the job for you if you're just talking about a button and a text box.
I don't have any experience with Qt, so I can't compare the two. | by far the best C++ GUI library out there is [Qt](http://www.qt.io/), it's comprehensive, easy to learn, really fast, and multiplattform.
ah, it recently got a LGPL license, so now you can download it for free and include on commercial programs | How do I create a GUI for a windows application using C++? | [
"",
"c++",
"visual-studio",
"user-interface",
"winapi",
""
] |
i have a problem, i want to know when a program is open with javascript.This is possible? | I assume, that you mean JavaScript running in a browser and by program you mean an real application running on the clients operating system (such as bash, vim or emacs).
Then this is not possible. | I'm assuming you're talking about javascript running inside a browser? No, that's not possible. Javascript running in a browser is not allowed to interact with the host OS for security reasons. | How to know when a program is open with javascript? | [
"",
"javascript",
""
] |
So, I have a table where StartDate and EndDate's are used to determine the activeness of a record. I thought of using NULLs to relieve the maintainers from having to manufacture some crazy dates for some of the records. For example, if NULL had defined as positive infinite when used in EndDate, the data maintainers wouldn't need to come up with something like 1-1-2100 for long-lived records.
I can speculate some of the trade offs on my own: defining NULL as infinities means cleaner data and elimination of periodic maintenance work, but it also means longer queries and stored procedures. So I was wondering how you guys in the real world weigh in on this.
EDIT: the opinions are about half-half. If I had clarified that the StartDate and EndDate are used solely for the purpose of determining the activeness of a record in the where clause, and never appears in the select list, would that tilt the scale? One subject I need to read on is probably indexing. Thanks'all. | I've used NULL for this purpose before with no problems, but I haven't developed any large-scale applications. | If either `StartDate` or `EndDate` of your record will be `NULL`, then the following condition:
```
BETWEEN StartDate AND EndDate
```
will never match this record.
You'll need to do following:
```
BETWEEN IFNULL(StartDate, '01.01.1000') AND IFNULL(EndDate, '01.01.3000')
```
, which, of course, is not good for indices.
Of course, you may create a function based index, but you'll need to provide a constant for it anyway.
*Summary: if you want performance, use constants, do not use NULLs* | I have StartDate and EndDate for each record. Should I give NULL a special meaning when used in these 2 fields? | [
"",
"sql",
"database-design",
""
] |
At this point most people will be thinking "Ah ill post this..:"
```
byte[] dataB= System.Text.Encoding.ASCII.GetBytes(data);
```
However.. the problem I have is i need the exact value of the bytes with no encoding just the pure value for each byte. For example if the value of the string is (0xFF32) i want it to convert it too {255,50}. he reason for this is I have a file format I am attempting to read which stores int's as bytes saves them and then reads them when the program opens.
This is what I have so far:
```
...
dialog.InitialDirectory =
Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) +
"/Test";
dialog.Title="Open File";
if (dialog.ShowDialog(this) == DialogResult.OK)
{
StreamReader reader = new StreamReader(dialog.FileName);
string data = reader.ReadToEnd();
reader.Close();
byte[] fileC = System.Text.Encoding.ASCII.GetBytes(data);
File_Read(dialog.FileName,fileC);
}
...
```
So when I try and read the file it converts the file convents of say 0xFF into 0x3F because 0xFF is greater then 127 and 0x3F is a ?.
Sorry if i seem a bit confusing :)
Thanks,
Michael | The problem is with your approach to start with:
> I need the exact value of the bytes with no encoding
...
> For example if the value of the string is (0xFF32)
That's a bit like looking at an oil painting and saying, "I want the bytes for that picture, with no encoding." It doesn't make sense. Text isn't the same as binary data. Once you understand that, it's easy to get to the root of the problem. What you really want is the contents of a *file* as a byte array. That's easy, because files are binary data! You shouldn't be reading it as text in the first place if it isn't really text. Fortunately, .NET makes this really easy:
```
byte[] fileC = File.ReadAllBytes(dialog.FileName);
``` | > However.. the problem I have is i need the exact value of the bytes with no encoding just the pure value for each byte.
Then use this:
```
byte[] dataB = System.Text.Encoding.Unicode.GetBytes(data);
```
It returns the bytes as stored internally by .NET strings.
But all this is codswallop: A string is *always* linked to a particular encoding and there's no way around it. The above will fail e.g. if the file contains invalid Unicode code sequences (which may happen) or through normalization. Since you obviously don't *want* a `string`, don't read one. Read the file as binary data instead. | C# convert string into its byte[] equivalent | [
"",
"c#",
"string",
"encoding",
"hex",
"byte",
""
] |
An extension to my previous question:
[Text cleaning and replacement: delete \n from a text in Java](https://stackoverflow.com/questions/542226/text-cleaning-and-replacement-delete-n-from-a-text-in-java)
I am cleaning this incoming text, which comes from a database with irregular text. That means, there' s no standard or rules. Some contain HTML characters like ®, &trade, <, and others come in this form: ”, –, etc. Other times I just get the HTML tags with < and >.
I am using String.replace to replace the characters by their meaning (this should be fine since I'm using UTF-8 right?), and replaceAll() to remove the HTML tags with a regular expression.
Other than one call to the replace() function for each replacement, and compiling the **HTML** tags regular expression, is there any recommendation to make this replacement efficient? | My first suggestion is to measure the performance of the simplest way of doing it (which is probably multiple replace/replaceAll calls). Yes, it's potentially inefficient. Quite often the simplest way of doing this is inefficient. You need to ask yourself: **how much do you care?**
Do you have sample data and a threshold at which point the performance is acceptable? If you don't, that's the first port of call. Then test the naive implementation, and see whether it really *is* a problem. (Bear in mind that string replacement is almost certainly only *part* of what you're doing. As you're fetching the text from a database to start with, that *may* well end up being the bottleneck.)
Once you've determined that the replacement really is the bottleneck, it's worth performing some tests to see which *bits* of the replacement are causing the biggest problem - it sounds like you're doing several different kinds of replacement. The more you can narrow it down, the better: you may find that the real bottleneck in the simplest code is caused by something which is easy to make efficient in a *reasonably* simple way, whereas trying to optimise *everything* would be a lot harder. | You're going to run into performance bottlenecks with replace with replaceAll.
If you want to increase performance
1. don't use replace - strings are immutable. Will create copies each time you call replace
2. don't use regular expressions (replaceAll) - though being compiled it's not as bad.
3. parse and replace your own strings using StringBuilder
Some code on your end might help discussion.
```
String str = ...
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char toAppend = 'a';
switch (str.charAt(i)) {
case '&' : toAppend = '&'; break;
case ...
...
default: toAppend = str.charAt(i);
}
sb.append(toAppend);
}
```
this is from: [Sun Forums](http://forums.sun.com/thread.jspa?threadID=723094&start=0&tstart=0) | Text replacement efficiency | [
"",
"java",
"string",
"performance",
""
] |
I was working with some C# code today in the morning and I had something like:
```
foreach(DataRow row in MyMethod.GetDataTable().Rows) {
//do something
}
```
So, as I dont have a full understanding of the language framework I would like to know if GetDataTable() gets called each time an iteration is done or if it just gets called once and the resulting data (which would be Rows) is saved in memory to loop through it. In any case, I declared a new collection to save it and work from there...
I added a new variable so instead I did:
```
DataRowCollection rowCollection = MyMethod.GetDataTable().Rows;
foreach(DataRow row in rowCollection) {
//do something
}
```
But im not quite sure if this is necessary.
Thanks in advance. | Don't worry about it; it'll only execute GetDataTable() once internally to get the enumerator object from the DataRowCollection, and then fetch a new item from it every run through the loop. | A foreach loop is only syntaxic sugar for
```
var enumerator = MyMethod.GetDataTable().Rows.GetEnumerator();
while (enumerator.MoveNext())
{
DataRow row = enumerator.Current;
// Initial foreach content
}
``` | Does a method that returns a collection get called in every iteration in a foreach statement in C#? | [
"",
"c#",
".net",
"loops",
"iterator",
""
] |
## Question
Hello All,
I've had some confusion for quite some time with essentially flooring a DateTime SQL type using T-SQL. Essentially, I want to take a DateTime value of say 2008-12-1 14:30:12 and make it 2008-12-1 00:00:00. Alot of the queries we run for reports use a date value in the WHERE clause, but I either have a start and end date value of a day and use a BETWEEN, or I find some other method.
Currently I'm using the following:
`WHERE CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam`
However, this seems kinda clunky. I was hoping there would be something more simple like
`CAST([tstamp] AS DATE)`
Some places online recommend using DATEPART() function, but then I end up with something like this:
```
WHERE DATEPART(year, [tstamp]) = DATEPART(year, @dateParam)
AND DATEPART(month, [tstamp]) = DATEPART(month, @dateParam)
AND DATEPART(day, [tstamp]) = DATEPART(day, @dateParam)
```
Maybe I'm being overly concerned with something small and if so please let me know. I just want to make sure the stuff I'm writing is as efficient as possible. I want to eliminate any weak links.
Any suggestions?
Thanks,
C
## Solution
Thanks everyone for the great feedback. A lot of useful information. I'm going to change around our functions to eliminate the function on the left hand side of the operator. Although most of our date columns don't use indexes, it is probably still a better practice. | that is very bad for performance, take a look at [Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-database-can-you-get-1000-impr)
functions on the left side of the operator are bad
here is what you need to do
```
declare @d datetime
select @d = '2008-12-1 14:30:12'
where tstamp >= dateadd(dd, datediff(dd, 0, @d)+0, 0)
and tstamp < dateadd(dd, datediff(dd, 0, @d)+1, 0)
```
Run this to see what it does
```
select dateadd(dd, datediff(dd, 0, getdate())+1, 0)
select dateadd(dd, datediff(dd, 0, getdate())+0, 0)
``` | If you're using SQL Server 2008 it has this built in now, see this in [books online](http://msdn.microsoft.com/en-us/library/bb630352.aspx)
`CAST(GETDATE() AS date)` | MS SQL Date Only Without Time | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the `shutil.copytree()` function expects that the destination path not exist beforehand.
The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this. | [`distutils.dir_util.copy_tree`](http://docs.python.org/distutils/apiref.html#distutils.dir_util.copy_tree) does what you want.
> Copy an entire directory tree src to a
> new location dst. Both src and dst
> must be directory names. If src is not
> a directory, raise DistutilsFileError.
> If dst does not exist, it is created
> with mkpath(). The end result of the
> copy is that every file in src is
> copied to dst, and directories under
> src are recursively copied to dst.
> Return the list of files that were
> copied or might have been copied,
> using their output name. The return
> value is unaffected by update or
> dry\_run: it is simply the list of all
> files under src, with the names
> changed to be under dst.
(more documentation at the above url) | For highlevel file operations like that use the [shutil](http://docs.python.org/library/shutil.html) module and in your case the copytree function. I think that is cleaner than "abusing" distutils.
**UPDATE:**: Forget the answer, I overlooked that the OP did try shutil. | How to copy a directory and its contents to an existing location using Python? | [
"",
"python",
"operating-system",
"filesystems",
"copy",
""
] |
can anyone think of a good way to ignore the single click that comes with a double-click in Java ?
I'm looking to have different behaviors for each such that:
* single-click paints crosshairs on the click point
* double-click selects an object on the screen, but should **not** paint crosshairs on the click point
... can anyone think of a way to do this ? Some sort of timer set-up maybe ? An ideas appreciated :-)
<disclaimer> ...and yes, I know I'm committing a most heinous usability / UI faux pas. </disclaimer>
**EDIT #2:**
Even though this works the delay due to the timer is maddening - I'm abandoning this solution, and using middle-click for selection instead of double-click...
**EDIT:**
Thanks [cgull](https://stackoverflow.com/users/23325/cgull) - this is what I was able to come up with given your confirmation that there's no easy way to do this (note that if I set the timer < 200 odd racing is seen between the click & the timer, but as long as I set this to a value > 200 things work just peachy) :
```
public void mouseClicked(MouseEvent e) {
System.out.println( "Click at (" + e.getX() + ":" + e.getY() + ")" );
if (e.getClickCount() == 2) {
System.out.println( " and it's a double click!");
wasDoubleClick = true;
}else{
Integer timerinterval = (Integer)
Toolkit.getDefaultToolkit().getDesktopProperty(
"awt.multiClickInterval");
timer = new Timer(timerinterval.intValue(), new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (wasDoubleClick) {
wasDoubleClick = false; // reset flag
} else {
System.out.println( " and it's a simple click!");
}
}
});
timer.setRepeats(false);
timer.start();
}
}
``` | Indeed you'll need to set up a Timer in your overridden mouseClicked() method of your MouseAdapter to detect the time interval between the two clicks. The default interval in ms can be found by querying
`Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval")`. If another mouse click is detected before the timer expires, then you have a double-click, else once the timer expires, you can process the single-click. | Actually I think there is a simpler solution (use InputEvent's getWhen() method):
```
class DCListener extends MouseAdapter{
private long maxTimeBetweenClicks; // in millis
private long firstClickTime=0;
private Runnable eventHandler;
public DCListener(long maxTimeBetweenClicks,Runnable eventHandler){
this.maxTimeBetweenClicks=maxTimeBetweenClicks;
this.eventHandler=eventHandler;
}
public void mouseClicked(MouseEvent e){
if((e.getWhen()-firstClickTime)<=maxTimeBetweenClicks){
firstClickTime=0; // 3 clicks are not 2 double clicks
eventHandler.run();
}else{
firstClickTime=e.getWhen();
}
}
}
``` | Java : ignore single click on double click? | [
"",
"java",
"events",
"click",
"mouse",
"double-click",
""
] |
I would like to know what are ruby's alternatives to the Java methods :
* wait
* notify
* notifyAll
Could you please post a small snippet or some links ? | With the caveat that I don't know Java, based on your comments, I think that you want a condition variable. Google for "Ruby condition variable" comes up with a bunch of useful pages. The [first link I get](http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Threads_and_Processes_Condition_Variables.html), seems to be a nice quick introduction to condition vars in particular, while [this](http://phrogz.net/ProgrammingRuby/tut_threads.html) looks like it gives a much broader coverage of threaded programming in Ruby. | What you are looking for is `ConditionVariable` in `Thread`:
```
require "thread"
m = Mutex.new
c = ConditionVariable.new
t = []
t << Thread.new do
m.synchronize do
puts "A - I am in critical region"
c.wait(m)
puts "A - Back in critical region"
end
end
t << Thread.new do
m.synchronize do
puts "B - I am critical region now"
c.signal
puts "B - I am done with critical region"
end
end
t.each {|th| th.join }
``` | ruby thread programming , ruby equivalent of java wait/notify/notifyAll | [
"",
"java",
"ruby",
"multithreading",
"synchronization",
""
] |
Most of the examples I see say to put it on the clipboard and use paste, but that doesn't seem to be very good because it overwrites the clipboard.
I did see [one method](http://www.codeproject.com/KB/edit/csexrichtextbox.aspx) that manually put the image into the RTF using a pinvoke to convert the image to a wmf. Is this the best way? Is there any more straightforward thing I can do? | The most straightforward way would be to modify the RTF code to insert the picture yourself.
In RTF, a picture is defined like this:
'{' \pict (brdr? & shading? & picttype & pictsize & metafileinfo?) data '}'
A question mark indicates the control word is optional.
"data" is simply the content of the file in hex format. If you want to use binary, use the \bin control word.
For instance:
```
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860 hex data}
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860\bin binary data}
```
\pict = starts a picture group,
\pngblip = png picture
\picwX = width of the picture (X is the pixel value)
\pichX = height of the picture
\picwgoalX = desired width of the picture in twips
So, to insert a picture, you just need to open your picture, convert the data to hex, load these data into a string and add the RTF codes around it to define a RTF picture. Now, you have a self contained string with picture data which you can insert in the RTF code of a document. Don't forget the closing "}"
Next, you get the RTF code from your RichTextBox (rtbBox.Rtf), insert the picture at the proper location, and set the code of rtbBox.Rtf
One issue you may run into is that .NET RTB does not have a very good support of the RTF standard.
I have just made a small application\* which allows you to quickly test some RTF code inside a RTB and see how it handles it. You can download it here:
[RTB tester](http://your-translations.com/toys/) (<http://your-translations.com/toys>).
You can paste some RTF content (from Word, for instance) into the left RTF box and click on the "Show RTF codes" to display the RTF codes in the right RTF box, or you can paste RTF code in the right RTB and click on "Apply RTF codes" to see the results on the left hand side.
You can of course edit the codes as you like, which makes it quite convenient for testing whether or not the RichTextBox supports the commands you need, or learn how to use the RTF control words.
You can download a full specification for RTF online.
---
NB It's just a little thing I slapped together in 5 minutes, so I didn't implement file open or save, drag and drop, or other civilized stuff. | I use the following code to first get the data from clipboard, save it in memory, set the image in clipboard, paste it in Rich Text Box and finally restore the data in Clipboard.
```
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.Filter = "All files |*.*"
OpenFileDialog1.Multiselect = True
Dim orgdata = Clipboard.GetDataObject
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each fname As String In OpenFileDialog1.FileNames
Dim img As Image = Image.FromFile(fname)
Clipboard.SetImage(img)
RichTextBox1.Paste()
Next
End If
Clipboard.SetDataObject(orgdata)
End Sub
```
The OpenFileDailog1, RichTextBox1 and Button1 are Open File Dialog, Rich Text Box and button controls respectively. | How can I insert an image into a RichTextBox? | [
"",
"c#",
"vb.net",
"image",
"richtextbox",
"rtf",
""
] |
(**Disclaimer:** This question is **not** specific to ASP.NET)
I have a control which may be templated, similar to the login controls:
```
public abstract class TemplatedControl : CompositeControl
{
public ITemplate Template { get; set; }
protected override void CreateChildControls()
{
var template = this.Template ?? CreateDefaultTemplate();
// ...
}
protected virtual ITemplate CreateDefaultTemplate()
{
return null;
}
}
```
A templated control would look like:
```
public class FooControl : TemplatedControl
{
public override ITemplate CreateDefaultTemplate()
{
return new FooTemplate();
}
}
```
My question is: would a Singleton be appropriate here instead?
```
public override ITemplate CreateDefaultTemplate()
{
return FooTemplate.Instance;
}
```
Singletons are associated with global variables; in this case, there is no state.
Singletons are also associated with hard-coded dependencies. In this case, knowledge of the specific type is warranted. | In this case I would say not. In the pattern you are proposing, there would only ever be one FooTemplate, which would be shared across multiple controls, pages and threads. You would have to be very careful that the template did not contain any request or user specific information, and also synchronize any method calls. It is much easier, and just a bit less performant to instantiate it each time.
The only reason I see doing it that was is that it takes a long time to instantiate the control. In that case, I would go with a factory pattern, where any initialization is done once, but all the data copied into a new instance every time. | If you only want the template created once for the control, you could use lazy initialization instead and achieve nearly the same effect.
```
private ITemplate defaultTemplate;
public override ITemplate CreateDefaultTemplate()
{
if (defaultTemplate == null)
{
defaultTemplate = new FooTemplate();
}
return defaultTemplate;
}
```
You should only use a Singleton implementation if you are sure that you only want one instance of any particular object ever in your application. | Is this a legitimate use of a Singleton? | [
"",
"c#",
"singleton",
""
] |
Is there any (preferably native) C# library which allows me to send some messages via the ICQ protocol? Is there something better than just wrapping libgaim or something? | Perhaps this can help you out:
<http://sourceforge.net/projects/oscarlib/>
Download the source and check the OscarLib. | There aren't any libraries I know of, so if you want to do this in C# you're probably going to have to make it yourself. You can find the ICQ protocol specification [here](http://iserverd.khstu.ru/oscar/). | Where can I find an ICQ library for C#? | [
"",
"c#",
".net",
"protocols",
"instant-messaging",
""
] |
I have a static library that may get linked into either a `.exe` or a `.dll`. At runtime I want one of my library functions to get the `HMODULE` for whatever thing the static library code has been linked into.
I currently use the following trick (inspired from [this forum](http://www.ureader.com/message/1095160.aspx)):
```
const HMODULE GetCurrentModule()
{
MEMORY_BASIC_INFORMATION mbi = {0};
::VirtualQuery( GetCurrentModule, &mbi, sizeof(mbi) );
return reinterpret_cast<HMODULE>(mbi.AllocationBase);
}
```
Is there a better way to do this that doesn't look so hacky?
*(Note: The purpose of this is to load some Win32 resources that I know my users will have linked in at the same time as my static library.)* | ```
HMODULE GetCurrentModule()
{ // NB: XP+ solution!
HMODULE hModule = NULL;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)GetCurrentModule,
&hModule);
return hModule;
}
``` | `__ImageBase` is a linker generated symbol that is the DOS header of the module (MSVC only). From that you can cast its address to an `HINSTANCE` or `HMODULE`. So it's more convenient than going through an API.
So you just need to do this:
```
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase)
```
From <https://web.archive.org/web/20100123173405/http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx> | How do I get the HMODULE for the currently executing code? | [
"",
"c++",
"c",
"winapi",
""
] |
In the final stage of development I started looking at code to try to find some bad practices. I discovered that while accessing a page, I'm querying the DB n times (n is the number of rows of an HTML table) just to get the translation (different languages) for a given record... I immediately thought that was bad and I tried a small optimization.
Running the SQL profiler shows that those query took 0ms.
Since these tables I'm querying are small (20-100 records) I thought I could fetch all data and cache them into the web server RAM, retrieving later using LINQ to Objects. Execution time this way is also 0ms.
The environment where I'm running these test is a DB and Web server with 0% load on the same machine. It's only me using the application.
The question starts here. Since I have no performance difference **at all** should I avoid that optimization? Should I keep it in the way to balance the usage of both DB and web server (the servers will be on 2 different machines in the production environment)?
In my opinion this optimization can't damage the performances, it could only make some better in case of heavy loaded DB. I have something in my brain that say it's wrong to optimize if there is no need...
Thanks for your opinion. | I don't think you've actually shown that there's no performance difference at all.
Try running the query a million times each way, and time how long it takes in total... I think you'll see a big difference.
The SQL profiler only shows you (as far as I'm aware) the time taken *on the database* to perform the query. It doesn't take into account:
* The time taken to set up the connection or prepare the query
* The time taken in network latency issuing the query
* The time taken in network latency returning the results
* The time taken converting the results into useful objects.
Of course, premature optimisation is a bad thing in general, but this does sound like a reasonable change to make - *if* you know that the contents of the tables won't change. | SQL Server is a bit peculiar in that way, all query execution times between 0 and 15 ms are rounded down to 0 ms. So you don't actually know from looking at the number if your query is taking 0 ms or 15 ms. It's a big difference between doing 1000 \* 1 ms queries and doing 1000 \* 15 ms.
Regarding translations, I've found that the best way is using Resources and tying them to a SQL database and the cache the translations in the web application for a reasonable amount of time. That is pretty efficient.
Other than that, what Jon Skeet says... :) | Optimize 0ms query (or optimizing ahead)? | [
"",
"sql",
"performance",
"optimization",
""
] |
I have some code from my VB.NET 1.1 days that allowed me to dynamically check if Debug was enabled in web.config. I figured why re-invent the wheel in turning on/off logging if I could simply have the web administrator enable debug. Here is the code I used in VB.NET that worked just fine:
```
ConfigurationSettings.GetConfig("system.web/compilation").Debug.ToString()
```
When I wanted to convert this to C# and use it in .NET 3.5 I ran into some trouble and it wouldn't work. Additionally, I would like to use the newer construct of ConfigurationManager.GetSection. Can anyone suggest how best to read the `system.web/compilation/debug=true|false` value?
Much appreciated! | Use:
```
HttpContext.Current.IsDebuggingEnabled
```
This property actually looks at the web.config configuration setting. If you look at it using Reflector you will find that it gets the actual ConfigurationSection object using some internal classes. | the following should work
```
var cfg=(System.Web.Configuration.CompilationSection) ConfigurationManager.GetSection("system.web/compilation");
if (cfg.Debug)
{
...
}
``` | How do I check if Debug is enabled in web.config | [
"",
"c#",
"asp.net",
"debugging",
""
] |
I have a problem writing a SQL statement for both Oracle and MS SQL server. I'd like to write the SQL so that it works in both. I don't want to have to mess around with setting a database type variable and switching
I have a column of course names that have values like this:
> 9RA923.2008W
>
> 1223.200710
>
> P0033330.200901
I want to select everything right of the ".".
In oracle I am using this:
```
SELECT substr(bom_course_id, instr(bom_course_id, '.')+1) FROM ...
```
In MSSQL Server I could use this:
```
SELECT SUBSTRING(bom_course_id, CHARINDEX('.', bom_course_id)+1 ) FROM ...
```
Does anyone have a clever way that I can select the last characters after the dot, using the same SQL statement in either Oracle or MS SQL.
Unfortunately, I won't know how many characters there will be before or after the "."
It's not completely numeric either, I can't count on only numbers.
I really wish there was an SQL standard. | Looking at [this link](http://sqlzoo.net/lfun), I do not see a standard way to achieve what you want to do.
```
ORACLE uses: INSTR
SQL SERVER uses: PATINDEX, CHARINDEX
ORACLE uses: SUBSTR
SQL SERVER uses: SUBSTRING
```
I could not think of a common method to obtain a character position.
A *VIEW* is probably the easiest way to proceed, or to do it *within the client application* itself. | Have you considered just hiding the select in a database view ?
From the application point of view, it will just be a plain, vanilla SELECT with no functions and all the database-specific stuff remains in the database.
May not suit everyone, but its an idea. | Platform Neutral SQL Statement for INSTR or CHARINDEX | [
"",
"sql",
"sql-server",
"oracle",
"standards",
"platform-independent",
""
] |
Say I've got a query
```
SELECT TOP 10 ... FROM ... ORDER BY ...
```
in Access (well, really Jet). The question is: how can I get all the other rows... everything *except* the top 10? | Couldn't you do something like
```
SELECT ... FROM ...
WHERE PK NOT IN (SELECT TOP 10 PK FROM ...)
ORDER BY ...
```
it might not be that efficient but that's the only way off the top of my head I can think to do something like that. AFAIK there's no "BOTTOM" clause in SQL :) | ```
SELECT ... FROM ....
WHERE myID NOT IN
(SELECT TOP 10 myID FROM ... ORDER BY rankfield)
ORDER BY sortfield
```
Note that your sorted order could, (if you wish) be different than your ranked order.
**Edit**: Another idea: If you already knew how many TOTAL rows were there, you could do (assuming 1000 rows):
```
SELECT TOP 990 ... FROM .... ORDER BY sortfield DESC
```
Just flip the sort, and take the remaining portion.
Of course, if you still wanted the results in the original order, you'd have to do something silly like:
```
SELECT ...
FROM (SELECT TOP 990 ... FROM .... ORDER BY sortfield DESC)
ORDER BY sortfield ASC
``` | Select Top (all but 10) from ... in Microsoft Access | [
"",
"sql",
"ms-access",
"jet",
""
] |
I tried changing a default parameter value with this:
```
ALTER PROCEDURE [dbo].[my_sp]
@currentDate datetime = GETDATE()
```
and all the SQL pre-compiler gave me was this error:
> Msg 102, Level 15, State 1, Procedure my\_sp, Line 8 Incorrect syntax near '('.
I have already created the procedure. (I'm not sure if that's relevant.) I was using a null default value and checking for that later, but that doesn't seem proper. Can I do this in one line?
---
Update: I was going off of [MSDN's description of stored procedure parameters](http://msdn.microsoft.com/en-us/library/ms186755.aspx "CREATE FUNCTION (Transact-SQL)"):
> [ = default ] Is a default value for the parameter. If a default value is defined, the function can be executed without specifying a value for that parameter.
>
> > Note:
> > Default parameter values can be specified for CLR functions except for the varchar(max) and varbinary(max) data types.
>
> When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
Am I reading this wrong?
Many thanks. | Default value for stored procedures parameter have to be ***constants***.
You'd need to do the following...
```
ALTER Procedure [dbo].[my_sp]
@currentDate datetime = null
AS
IF @currentDate is null
SET @currentDate = getdate()
``` | I don't think that is possible, you have to use a literal (constant) value as the default.
However you can do this:
```
Set @currentDate = Coalesce(@currentDate , GetDate())
``` | SQL function as default parameter value? | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the `c.vim` syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?
Example C code with unmatched parens:
```
int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
```
Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).
BTW, I tried out [this vim plugin](http://www.vim.org/scripts/script.php?script_id=350) but I wasn't happy with the behavior.
Edit:
I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a `file.write()` method call. It would be nice if I could get vim to make that mistake more visually obvious.
**Update:**
Ok, here's what I've tried so far.
```
:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
```
Unfortunately, all this does is highlight as an error the right paren of all **balanced** parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it. | If I understand correctly and you are trying to look at non-matching parenthesis in C code (that was generated in python), I would recommend you install rainbow.vim from [Dr Chip's Site](http://www.drchip.org/astronaut/vim/#RAINBOW). This will highlight braces in different colours depending on the levels of indentation and will highlight unmatching braces in red as you have requested. A screenshot [http://img294.imageshack.us/img294/8586/rainbow.jpg http://img294.imageshack.us/img294/8586/rainbow.jpg](http://img294.imageshack.us/img294/8586/rainbow.jpg "Rainbow Brace Error")
To install, download **`rainbow.vim`** and place in `vimfiles/after/syntax/c/` (create this directory if it is not present).
On Linux, this will be `~/.vim/after/syntax/c/rainbow.vim`
On Windows, it may be `c:\vim\vimfiles\after\syntax\c\rainbow.vim` or possibly somewhere else, see `:help runtimepath`.
Note that there are some plugins that conflict with `rainbow.vim`, but it's not too hard to make them co-operate.
If you are trying to highlight non-matching parenthesis in the python code, you could modify rainbow.vim to use the python syntax clusters instead of the C ones, but this is a little more involved, but you could use something along the lines of (modified version of Dr Chip's rainbow code):
```
syn cluster pyParenGroup contains=pythonString,pythonRawString,pythonEscape,pythonNumber,pythonBuiltin,pythonException
syn match pyParenError display ')'
syn region pyParen transparent matchgroup=hlLevel0 start='(' end=')' contains=@pyParenGroup,pyParen1
syn region pyParen1 transparent matchgroup=hlLevel1 start='(' end=')' contains=@pyParenGroup,pyParen2
syn region pyParen2 transparent matchgroup=hlLevel2 start='(' end=')' contains=@pyParenGroup,pyParen3
syn region pyParen3 transparent matchgroup=hlLevel3 start='(' end=')' contains=@pyParenGroup,pyParen4
syn region pyParen4 transparent matchgroup=hlLevel4 start='(' end=')' contains=@pyParenGroup,pyParen5
syn region pyParen5 transparent matchgroup=hlLevel5 start='(' end=')' contains=@pyParenGroup,pyParen6
syn region pyParen6 transparent matchgroup=hlLevel6 start='(' end=')' contains=@pyParenGroup,pyParen7
syn region pyParen7 transparent matchgroup=hlLevel7 start='(' end=')' contains=@pyParenGroup,pyParen8
syn region pyParen8 transparent matchgroup=hlLevel8 start='(' end=')' contains=@pyParenGroup,pyParen9
syn region pyParen9 transparent matchgroup=hlLevel9 start='(' end=')' contains=@pyParenGroup,pyParen
hi link pyParenError Error
if &bg == "dark"
hi default hlLevel0 ctermfg=red guifg=red1
hi default hlLevel1 ctermfg=yellow guifg=orange1
hi default hlLevel2 ctermfg=green guifg=yellow1
hi default hlLevel3 ctermfg=cyan guifg=greenyellow
hi default hlLevel4 ctermfg=magenta guifg=green1
hi default hlLevel5 ctermfg=red guifg=springgreen1
hi default hlLevel6 ctermfg=yellow guifg=cyan1
hi default hlLevel7 ctermfg=green guifg=slateblue1
hi default hlLevel8 ctermfg=cyan guifg=magenta1
hi default hlLevel9 ctermfg=magenta guifg=purple1
else
hi default hlLevel0 ctermfg=red guifg=red3
hi default hlLevel1 ctermfg=darkyellow guifg=orangered3
hi default hlLevel2 ctermfg=darkgreen guifg=orange2
hi default hlLevel3 ctermfg=blue guifg=yellow3
hi default hlLevel4 ctermfg=darkmagenta guifg=olivedrab4
hi default hlLevel5 ctermfg=red guifg=green4
hi default hlLevel6 ctermfg=darkyellow guifg=paleturquoise3
hi default hlLevel7 ctermfg=darkgreen guifg=deepskyblue4
hi default hlLevel8 ctermfg=blue guifg=darkslateblue
hi default hlLevel9 ctermfg=darkmagenta guifg=darkviolet
endif
```
EDIT:
As a test, I downloaded **gvim70.zip** and **vim70rt.zip** from <ftp://ftp.vim.org/pub/vim/pc/> (these are the Windows versions of Vim 7.0). I unzipped the two files into a new directory and ran `gvim.exe` from `vim/vim70/gvim.exe`. I **do not** have any vim configuration stored in "C:\Documents and Settings", so running this vim is the same as running a 'vanilla' configuration. I then downloaded `pyprint.py` from [amk.ca/python/simple/pyprint.html](http://www.amk.ca/python/simple/pyprint.html) as a piece of sample code and copied the above code into a file called code.vim. In gVim, I entered `:e pyprint.py`. It opened in the white-background window, with no syntax highlighting. I then entered `:syntax on`, which switched the default syntax highlighting on. I added a second `)` character on line 8. Finally, I entered `:source code.vim`, which made the second `)` character be highlighted in red.
I've also carried out this test on Linux (with Vim 7.2), by entering the following command sequence:
```
cd ~
mv .vimrc old_dot_vimrc
mv .gvimrc old_dot_gvimrc
mv .vim old_dot_vim
vim pyprint.py
:e pyprint.py
" Add extra bracket here!
:syntax on
:source code.vim
```
Again, the second bracket is highlighted and everything else seems normal. | You can get vim to do the opposite: do a
> :set showmatch
and it will highlight matching parens. You'll know when you're unbalanced when it doesn't highlight something.
I'm also assuming you're familiar with the '%' command, which bounces you to the matching element. | Highlighting unmatched brackets in vim | [
"",
"python",
"vim",
"syntax-highlighting",
""
] |
For example, given two dates in input boxes:
```
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
```
How do I get the number of days between two dates in JavaScript? | Here is a **quick and dirty** implementation of `datediff`, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).
```
/**
* Take the difference between the dates and divide by milliseconds per day.
* Round to nearest whole number to deal with DST.
*/
function datediff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
/**
* new Date("dateString") is browser-dependent and discouraged, so we'll write
* a simple parse function for U.S. date format (which does no error checking)
*/
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0] - 1, mdy[1]);
}
alert(datediff(parseDate(first.value), parseDate(second.value)));
```
```
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
```
You should be aware that the "normal" Date APIs (without "UTC" in the name) operate in the local timezone of the user's browser, so in general you could run into issues if your user is in a timezone that you don't expect, and your code will have to deal with Daylight Saving Time transitions. You should carefully read the documentation for the Date object and its methods, and for anything more complicated, strongly consider using a library that offers more safe and powerful APIs for date manipulation.
* [Numbers and Dates -- MDN JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates)
* [`Date` -- MDN JavaScript reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
Also, for illustration purposes, the snippet uses [named access on the `window` object](https://www.w3.org/TR/html5/browsers.html#named-access-on-the-window-object) for brevity, but in production you should use standardized APIs like [getElementById](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById), or more likely, some UI framework. | As of this writing, only one of the other answers correctly handles DST (daylight saving time) transitions. Here are the results on a system located in California:
```
1/1/2013- 3/10/2013- 11/3/2013-
User Formula 2/1/2013 3/11/2013 11/4/2013 Result
--------- --------------------------- -------- --------- --------- ---------
Miles (d2 - d1) / N 31 0.9583333 1.0416666 Incorrect
some Math.floor((d2 - d1) / N) 31 0 1 Incorrect
fuentesjr Math.round((d2 - d1) / N) 31 1 1 Correct
toloco Math.ceiling((d2 - d1) / N) 31 1 2 Incorrect
N = 86400000
```
Although `Math.round` returns the correct results, I think it's somewhat clunky. Instead, by explicitly accounting for changes to the UTC offset when DST begins or ends, we can use exact arithmetic:
```
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}
alert(daysBetween($('#first').val(), $('#second').val()));
```
## Explanation
JavaScript date calculations are tricky because `Date` objects store times internally in UTC, not local time. For example, 3/10/2013 12:00 AM Pacific Standard Time (UTC-08:00) is stored as 3/10/2013 8:00 AM UTC, and 3/11/2013 12:00 AM Pacific Daylight Time (UTC-07:00) is stored as 3/11/2013 7:00 AM UTC. On this day, midnight to midnight local time is only 23 hours in UTC!
Although a day in local time can have more or less than 24 hours, a day in UTC is always exactly 24 hours.1 The `daysBetween` method shown above takes advantage of this fact by first calling `treatAsUTC` to adjust both local times to midnight UTC, before subtracting and dividing.
1. JavaScript ignores leap seconds. | How to calculate number of days between two dates? | [
"",
"javascript",
"date",
""
] |
I read this [post about card shuffling](http://www.codinghorror.com/blog/archives/001015.html) and in many shuffling and sorting algorithms you need to swap two items in a list or array. But what does a good and efficient Swap method look like?
Let's say for a `T[]` and for a `List<T>`. How would you best implement a method that swaps two items in those two?
```
Swap(ref cards[i], ref cards[n]); // How is Swap implemented?
``` | Well, the code you have posted (`ref cards[n]`) can only work with an array (not a list) - but you would use simply (where `foo` and `bar` are the two values):
```
static void Swap(ref int foo, ref int bar) {
int tmp = foo;
foo = bar;
bar = tmp;
}
```
~~Or possibly (if you want atomic):~~
```
Interlocked.Exchange(ref foo, ref bar);
```
Personally, I don't think I'd bother with a swap method, though - just do it directly; this means that you can use (either for a list or for an array):
```
int tmp = cards[n];
cards[n] = cards[i];
cards[i] = tmp;
```
If you really wanted to write a swap method that worked on either a list **or** an array, you'd have to do something like:
```
static void Swap(IList<int> list, int indexA, int indexB)
{
int tmp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = tmp;
}
```
(it would be trivial to make this generic) - however, the original "inline" version (i.e. not a method) working on an array will be faster. | 11 years later and we have tuples...
```
(foo, bar) = (bar, foo);
``` | C#: Good/best implementation of Swap method | [
"",
"c#",
"sorting",
"shuffle",
""
] |
In C# rounding a number is easy:
```
Math.Round(1.23456, 4); // returns 1.2346
```
However, I want to round a number such that the fractional part of the number rounds to the closest fractional part of a predefined fraction (e.g. 1/8th) and I'm trying to find out if the .NET library already has this built in.
So, for example, if I want to round a decimal number to a whole eighth then I'd want to call something like:
```
Math.RoundFractional(1.9, 8); // and have this yield 1.875
Math.RoundFractional(1.95, 8); // and have this yield 2.0
```
So the first param is the number that I want to round and the second param dictates the rounding fraction. So in this example, after rounding has taken place the figures following the decimal point can only be one of eight values: .000, .125, .250, .375, .500, .625, .750, .875
The Questions: Is this function built into .NET somewhere? If not, does anybody have a link to a resource that explains how to approach solving this problem? | You could do this:
```
Math.Round(n * 8) / 8.0
``` | Don't know if it's built into .NET but I would simply do:
```
Math.Round(x * 8, 0) / 8;
```
to round it to the nearest 8th.
Substitute your favorite number for other "resolutions". | How do I round a decimal to a specific fraction in C#? | [
"",
"c#",
".net",
"algorithm",
"math",
""
] |
I'm wanting to find the number of mantissa digits and the unit round-off on a particular computer. I have an understanding of what these are, just no idea how to find them - though I understand they can vary from computer to computer.
I need this number in order to perform certain aspects of numerical analysis, like analyzing errors.
What I'm currently thinking is that I could write a small c++ program to slowly increment a number until overflow occurs, but I'm not sure what type of number to use.
Am I on the right track? How exactly does one go about calculating this? | I would think that whatever language you were using would specify how floats were stored. I know Java does this by use of a specific IEEE standard (754, I think).
If it's not specified, I would think you could just do your own check by adding 0.5 to 1 to see if the actual number changes. If it does, then add 0.25 to 1, the 0.125 to 1, and so on until the number doesn't change, something like:
```
float a = 1;
float b = 0.5;
int bits = 0;
while (a + b != a) {
bits = bits + 1;
b = b / 2;
}
```
If you only had 3 mantissa bits, then 1 + 1/16 would be equal to 1.
Then you've exhausted your mantissa bits.
You might actually need the base number to be 2 rather than 1, since IEEE754 uses an implied '1+' at the start.
EDIT:
It appears the method described above may have some issues as it gives 63 bits for a system that clearly has 4-byte floats.
Whether that's to do with intermediate results (I doubt it since the same code with explicit casts [`while (((float)(a + b) != (float)(a))`] has similar problems) or (more likely, I believe) the possibility that the unit value `a` can be represented with bits closer to the fractional `b` by adjusting the exponent, I don't yet know.
For now, it's best to rely on the language information I mentioned above such as use of IEEE754 (if that information is available).
I'll leave the problematic code in as a trap for wary players. Maybe someone with more floating point knowledge then I can leave a note explaining why it acts strangely (no conjecture, please :-).
EDIT 2:
This piece of code fixes it by ensuring intermediates are stored in floats. Turns out Jonathan Leffler was right - it was intermediate results.
```
#include <stdio.h>
#include <float.h>
int main(void) {
float a = 1;
float b = 0.5;
float c = a + b;
int bits = 1;
while (c != a) {
bits = bits + 1;
b = b / 2;
c = a + b;
}
printf("%d\n",FLT_MANT_DIG);
printf("%d\n",bits);
return 0;
```
}
This code outputs (24,24) to show that the calculated value matches the one in the header file.
Whilst written in C, it should be applicable to any language (specifically one where the information isn't available in a header or by virtue that it's specified in the language documentation). I only tested in C because Eclipse takes so long to start on my Ubuntu box :-). | You might want to check out `<limits>` in your C++ library:
```
#include <iostream>
#include <limits>
#include <typeinfo>
template <typename T>
void printDetailsFor() {
std::cout
<< "Printing details for " << typeid(T).name() << ":\n"
<< "\tradix: " << std::numeric_limits<T>::radix << "\n"
<< "\tradix digits: " << std::numeric_limits<T>::digits << "\n"
<< "\tepsilon: " << std::numeric_limits<T>::epsilon() << "\n"
<< std::endl;
}
int main() {
printDetailsFor<int>();
printDetailsFor<float>();
printDetailsFor<double>();
printDetailsFor<long double>();
return 0;
}
```
I think that you want `std::numeric_limits<T>::digits` which should be one more than the number of mantissa bits. My machine prints out:
```
Printing details for i:
radix: 2
radix digits: 31
epsilon: 0
Printing details for f:
radix: 2
radix digits: 24
epsilon: 1.19209e-07
Printing details for d:
radix: 2
radix digits: 53
epsilon: 2.22045e-16
Printing details for e:
radix: 2
radix digits: 64
epsilon: 1.0842e-19
``` | How to find mantissa length on a particular machine? | [
"",
"c++",
"floating-point",
"numerical-methods",
"rounding-error",
"mantissa",
""
] |
Should I initialize class fields at declaration like this?
```
public class SomeTest extends TestCase
{
private final List list = new ArrayList();
public void testPopulateList()
{
// Add stuff to the list
// Assert the list contains what I expect
}
}
```
Or in setUp() like this?
```
public class SomeTest extends TestCase
{
private List list;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.list = new ArrayList();
}
public void testPopulateList()
{
// Add stuff to the list
// Assert the list contains what I expect
}
}
```
I tend to use the first form because it's more concise, and allows me to use final fields. If I don't *need* to use the setUp() method for set-up, should I still use it, and why?
**Clarification:**
JUnit will instantiate the test class once per test method. That means `list` will be created once per test, regardless of where I declare it. It also means there are no temporal dependencies between the tests. So it seems like there are no advantages to using setUp(). However the JUnit FAQ has many examples that initialize an empty collection in setUp(), so I figure there must be a reason. | If you're wondering specifically about the examples in the JUnit FAQ, such as the [basic test template](https://web.archive.org/web/20221017015856/https://junit.sourceforge.net/doc/faq/faq.htm#tests_16), I think the best practice being shown off there is that the *class under test* should be instantiated in your setUp method (or in a test method).
When the JUnit examples create an ArrayList in the setUp method, they all go on to test the behavior of that ArrayList, with cases like testIndexOutOfBoundException, testEmptyCollection, and the like. The perspective there is of someone writing a class and making sure it works right.
You should probably do the same when testing your own classes: create your object in setUp or in a test method, so that you'll be able to get reasonable output if you break it later.
On the other hand, if you use a Java collection class (or other library class, for that matter) in your test code, it's probably not because you want to test it--it's just part of the test fixture. In this case, you can safely assume it works as intended, so initializing it in the declaration won't be a problem.
For what it's worth, I work on a reasonably large, several-year-old, TDD-developed code base. We habitually initialize things in their declarations in test code, and in the year and a half that I've been on this project, it has never caused a problem. So there's at least some anecdotal evidence that it's a reasonable thing to do. | I started digging myself and I found one potential advantage of using `setUp()`. If any exceptions are thrown during the execution of `setUp()`, JUnit will print a very helpful stack trace. On the other hand, if an exception is thrown during object construction, the error message simply says JUnit was unable to instantiate the test case and you don't see the line number where the failure occurred, probably because JUnit uses reflection to instantiate the test classes.
None of this applies to the example of creating an empty collection, since that will never throw, but it is an advantage of the `setUp()` method. | Best Practice: Initialize JUnit class fields in setUp() or at declaration? | [
"",
"java",
"junit",
""
] |
I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model's state).
Is there something in Java similar to Cocoa's NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects "fire off" a notification? | Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don't worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it "ScanListener", like
```
public interface ScanListener
{
public void scanStarted();
public void scanCompleted();
}
```
Now the Loader defines a method for your other code to register for callbacks, like
```
public void addScanListener(ScanListener listener)
{
listeners.add(listener);
}
```
The Loader, when it starts a scan, executes the following code
```
for (ScanListener listener : listeners)
{
listener.scanStarted();
}
```
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls "loader.addScanListener(this)". Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It's all up to you. | There's no pre-existing per-process service that dispatches events in java that's equivalent to the default NSNotificationCenter. In java, the type of the event is specified by the event object being a particular type (which also means that the notification method depends on that type) rather than using a string. Prior to generics, writing a general event dispatcher and receiver that is also typesafe isn't really possible (witness the proliferation of \*Event classes and \*EventListener interfaces in the AWT and Spring libraries).
There are some facilities for event dispatch. As [Paul](https://stackoverflow.com/questions/488919/java-equivalent-of-cocoa-nsnotification/488950#488950) mentioned, there's `java.util.Observable`, which as you point out, requires subclassing. There's also `java.beans.PropertyChangeSupport`, which could be useful depending on your situation.
You could also write one yourself. The source for `PropertyChangeSupport` is likely available in the openjdk, and you could look at the abandoned [Apache Commons Event](http://commons.apache.org/sandbox/events/) project. Depending on your needs, you may have to worry about stuff like threading, seralization, memory leaks (ensuring deregistration or using weak references), and concurrent modification (iterate over a copy of your list of listeners, as a listener may decide to unregister itself in response to a change).
Now that generics exist in Java, a generic event dispatch library would be possible; however, I haven't come across any. Anyone? | Java equivalent of Cocoa NSNotification? | [
"",
"java",
"objective-c",
"cocoa",
"events",
"notifications",
""
] |
In my project I have two separate DBs on the same server. The DBs are self-sufficient except for three columns in DB "B" that need to be accessed in DB "A".
Are there performance considerations if I were to have a stored proc in A that accessed three columns from B directly?
Currently, we run a nightly job to import the needed data from table B to table A, so that the stored proc isn't going out of the scope of A.
Is that the best method?
Are cross DB stored procs within best practices? | To clarify the other posters comments.
There is no "direct" negative performance impact when using cross database access via stored procedures. Performance will be determined by the underlying architecture of the individual databases, i.e. indexes available, physical storage locations etc.
This is actually quite a common practice and so long as you follow standard query tuning principals you will be just fine. | There should be no problem since the databases are on the same server. Usually problems occur when you do this with linked servers and you could run into network latency | Cross Database Stored Procedure performance considerations | [
"",
"sql",
"stored-procedures",
""
] |
I wasn't able to find an answer anywhere about this seemingly simple topic: **is it possible to align text of a single subitem in a WinForms ListView control?**
If so, how?
I would like to have text in the same column aligned differently. | For future reference, here's how I solved it:
```
// Make owner-drawn to be able to give different alignments to single subitems
lvResult.OwnerDraw = true;
...
// Handle DrawSubItem event
private void lvResult_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
// This is the default text alignment
TextFormatFlags flags = TextFormatFlags.Left;
// Align text on the right for the subitems after row 11 in the
// first column
if (e.ColumnIndex == 0 && e.Item.Index > 11)
{
flags = TextFormatFlags.Right;
}
e.DrawText(flags);
}
// Handle DrawColumnHeader event
private void lvResult_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
// Draw the column header normally
e.DrawDefault = true;
e.DrawBackground();
e.DrawText();
}
```
It was necessary to handle the DrawColumnHeader, otherwise no text or column separators would be drawn. | example :
```
listView1.Columns[1].TextAlign = HorizontalAlignment.Right;
```
will set Column's "1" alignment to right | How do I align text for a single subitem in a ListView using C#? | [
"",
"c#",
"listview",
"text-alignment",
""
] |
I was told I can add the `-XX:+HeapDumpOnOutOfMemoryError` parameter to my JVM start up options to my JBoss start up script to get a heap dump when we get an out of memory error in our application. I was wondering where this data gets dumped? Is it just to the console, or to some log file? If it's just to the console, what if I'm not logged into the Unix server through the console? | Here's what [Oracle's documentation](http://www.oracle.com/technetwork/java/javase/clopts-139448.html) has to say:
> By default the heap dump is created in
> a file called java\_*pid*.hprof in the
> working directory of the VM, as in the
> example above. You can specify an
> alternative file name or directory
> with the `-XX:HeapDumpPath=` option. For
> example `-XX:HeapDumpPath=/disk2/dumps`
> will cause the heap dump to be
> generated in the `/disk2/dumps`
> directory. | You can view this dump from the UNIX console.
The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.
E.g.:
```
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"
```
You can view the dump from the console on the mentioned path. | Where dump is dumped, using HeapDumpOnOutOfMemoryError parameter for JBoss | [
"",
"java",
"memory-leaks",
"jboss",
"heap-memory",
""
] |
Can somebody tell me how to get the header height of a ListView. | This might be a little bit hacky but you can do:
```
listView.Items[0].Bounds.Top
```
This will only work if there is only one item in the list. So you might want to temporarily add one when you first create the list and keep the height value.
Else, you can always use:
```
listView.TopItem.Bounds.Top
```
To make the test at any moment, but you still need at least one item in the list. | Here's how to get the listview header height using Win32 Interop calls.
```
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
const long LVM_FIRST = 0x1000;
const long LVM_GETHEADER = (LVM_FIRST + 31);
[DllImport("user32.dll", EntryPoint="SendMessage")]
private static extern IntPtr SendMessage(IntPtr hwnd, long wMsg, long wParam, long lParam);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
RECT rc = new RECT();
IntPtr hwnd = SendMessage(ListView1.Handle, LVM_GETHEADER, 0, 0);
if (hwnd != null)
{
if (GetWindowRect(new HandleRef(null, hwnd), out rc))
{
int headerHeight = rc.Bottom - rc.Top;
}
}
``` | How do I get the header height of a Listview | [
"",
"c#",
".net",
"winforms",
"listview",
""
] |
I need to call a couple of methods asynchronously with different priorities.
My first idea was to use the ThreadPool and change the priority of the Thread like this:
```
static void Run()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(SomeMethod));
}
static void SomeMethod(object o)
{
Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; // is this ok?
// do some work here
}
```
Does that work or what do you recommend? | According to <http://msdn.microsoft.com/en-us/library/0ka9477y.aspx>, it won't work if you are targeting 2.0, it alludes to there being some differences in 3.5 but doesn't specifically mention priority:
> **When Not to Use Thread Pool Threads**
>
> There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:
>
> * You require a foreground thread.
> * ***You require a thread to have a particular priority.***
> * You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting.
> * You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment.
> * You need to have a stable identity associated with the thread, or to dedicate a thread to a task.
You'll likely need to come up with your own implementation, and handle creation of Threads directly.
*Question:* What are you trying to achieve do you have a set of tasks to be processed and you want high priority tasks to happen first, and lower ones to happen later; or do you actually want Threads of differing priority? | That's **definitely** a **horrible** idea.
Generally speaking, setting a thread or process priority is a bad idea, because it is non deterministic, and you might starve out other threads/processes in the act. Also, you might actually elevate the priority of lower priority threads/processes because of starvation.
On top of that, the thread pool's threads are meant to be reused, and by changing the priority of the thread, you are changing the expectation of the task that will get the thread for use after your routine runs.
That being said, you have two options. If you only need to prioritize your tasks and don't mind if other items not related to your tasks get executed before yours, then you can use the thread pool with a producer consumer pattern, with some wrapper code which will take the highest priority item from your queue.
If you want the threads only to run your tasks, then you have to create your own thread pool (using the System.Thread class) and then do the same thing, using wrapper code to get the task to execute based on priority.
The new classes in the System.Threading namespace in .NET 4.0 (not released yet) will handle the creation of a separate thread pool for you. | How to call a method async with some kind of priority? | [
"",
"c#",
".net",
"multithreading",
"asynchronous",
"threadpool",
""
] |
Let's say you have a small calculator program that takes numbers and an operator to perform on those numbers as input, then prints out the result of applying the specified operation. So if you input "4 + 5" it will print out "9". Simple, right? Well what I want to be able to write is something this:
```
a, op, b = raw_input().split()
print somehowInvokeOperator(op, a, b)
```
The problem is that "somehowInvokeOperator()" part. Is there anyway to do this without resorting to either (a) eval() or (b) some type of dictionary mapping keys like "+" and "-" to functions that perform the appropriate operation? getattr() doesn't appear to work for this. I don't really need this code for anything, I'm just curious to see if this can be solved in Python as elegantly as it can in other dynamic languages. | Basically no, you will at least need to have a dictionary or function to map operator characters to their implementations. It's actually a little more complicated than that, since not all operators take the form `a [op] b`, so in general you'd need to do a bit of parsing; see <https://docs.python.org/library/operator.html> for the full list of correspondences, and for the functions you'll probably want to use for the operator implementations.
If you're only trying to implement the binary arithmetic operators like + - \* / % \*\* then a dictionary should be good enough. | If you really wanted to do this, you would need the standard `operator` module. See also [Emulating numeric types](http://docs.python.org/reference/datamodel.html#object.__add__). And, yes, a dictionary full of functions would be a perfectly sound dynamic way to make this happen.
```
import operator
operations = {'+' : operator.add}
result = operations[op](a, b)
``` | Invoking built-in operators indirectly in Python | [
"",
"python",
""
] |
I'm using an Infragistics grid on a form and am handling multiple client-side events on the cells (e.g. cell click, before cell edit, before cell update, etc).
On the cell click event, I'm spawning a secondary window (successfully) as follows:
```
var convChartWindow = window.open("conversioncharts/" + currentCell.getValue() + ".html", "chart", "location=0,0, status=1, scrollbars=1, width=" + screen.width + ", height=175");
convChartWindow.focus();
```
However, the `convChartWindow` does not maintain the focus, and gets covered with the parent window. None of my other cell events fire after this, but there seems to be some Infragistics JavaScript that runs.
Is there a something I can put after the `.focus()` above to prevent further JavaScript from running and keep the focus on the correct window? | i dont know what infragistics is. ill assume its some framework over which you have no control. if i were you i would try the following:
1) set a timeout to take focus back to the window after 1000 ms, or set a timeout loop to set focus to the window you need. this is a hack.
2) figure out what functions fire the events that ruin your life, override those functions in your code and add a flag that will prevent them from doing something evil
3) last, atleast read this:
<http://www.quirksmode.org/js/events_order.html>
there might be something useful for you in there | Call this:
```
// Prevents event bubble up or any usage after this is called.
// pE - event object
function StopEvent(pE)
{
if (!pE)
if (window.event)
pE = window.event;
else
return;
if (pE.cancelBubble != null)
pE.cancelBubble = true;
if (pE.stopPropagation)
pE.stopPropagation();
if (pE.preventDefault)
pE.preventDefault();
if (window.event)
pE.returnValue = false;
if (pE.cancel != null)
pE.cancel = true;
} // StopEvent
```
This was snipped from here: [What is equivalent of 'event.returnValue=false' in Firefox](http://forums.asp.net/t/1071858.aspx)
and was written by Peter Blum
See: [PeterBlum.com](http://www.peterblum.com/Home.aspx) | How to stop further JavaScript events from executing | [
"",
"javascript",
"asp.net",
"dom-events",
"infragistics",
""
] |
I think this is a dumb question but I could not find it on php. Why is a + with the = in the following code:
```
function calculateRanking()
{
$created = $this->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
$time = $diff['days'] * 24;
$time += $diff['hours'];
$time += ($diff['minutes'] / 60);
$time += (($diff['seconds'] / 60)/60);
$base = $time + 2;
$this->ranking = ($this->points - 1) / pow($base, 1.5);
$this->save();
}
```
Is this so $time has all those values or rather it is adding all the values to $time?
Thanks | It's adding all those values to time.
```
something += somethingelse
```
is a shortcut for
```
something = something + somethingelse
```
-Adam | ```
$time += $diff['hours'];
```
is the same as saying
```
$time = $time + $diff['hours'];
``` | What is += used for? | [
"",
"php",
""
] |
Is it possible to set up a mysql trigger that fires back the id number of that record when ever there is an insert into the database AND how do i capture that using php? | Unless I don't fully understand your question, you don't need a trigger for this - just use the "last inserted ID" functionality of your database driver.
Here's an example using the basic mysql driver in PHP.
```
<?php
$db = mysql_connect( 'localhost', 'user', 'pass' );
$result = mysql_query( "insert into table (col1, col2) values ('foo', 'bar')", $db );
$lastId = mysql_insert_id();
```
This is a connection-safe way to obtain the ID. | As explained in the previous answers, you'd don't need to use a trigger to return the identity. You can use the mysql\_insert\_id() command as described in the [documentation][1].
However if you need to use the new insert id in a trigger, use NEW.[identity\_column\_name] as follows:
```
CREATE TABLE temp (
temp_id int auto_increment,
value varchar(10),
PRIMARY_KEY(temp_id)
);
CREATE TRIGGER after_insert_temp AFTER INSERT ON temp
FOR EACH ROW
BEGIN
DECLARE @identity;
SET @identity = NEW.temp_id;
-- do something with @identity
END
``` | My SQL triggers | [
"",
"php",
"mysql",
"triggers",
""
] |
While creating and inserting DOM element's, it seems that the functions used for the task are returning before the elements show in the page.
Before starting to insert the elements I set the display property of a div to 'block' and after inserting the elements I set the property to 'none', the problem is, the indicator is not showing in the page. It's possible to accomplish this?
Where $ is an alias for document.getElementById.
```
$('loading').className="visible";
var container = document.getElementById('container');
for(var i=0; i< 50000; i++){
var para = document.createElement('p');
para.appendChild(document.createTextNode('Paragraph No. ' + i));
container.appendChild(para);
}
$('loading').className="hidden";
```
It appears as createElement and/or appendChild run asynchronously, so I'm hiding the indicator almost immediately? | I believe that the DOM won't refresh until after the script has finished running.
To make it run asynchronously, you could try wrapping it in a `setTimeout` call, with a timeout of zero milliseconds. In pseudocode:
```
showLoadingIndicator();
setTimeout(addElements, 0);
function addElements() {
// perform your loop here
hideLoadingIndicator();
}
``` | setTimeout() is the answer. A simple 'one-line' change for you:
```
$('loading').className="visible";
setTimeout(function() {
var container = document.getElementById('container');
for(var i=0; i< 50000; i++){
var para = document.createElement('p');
para.appendChild(document.createTextNode('Paragraph No. ' + i));
container.appendChild(para);
}
$('loading').className="hidden";
}, 0);
``` | how to show a 'working' indicator while inserting a big numbers of dom elements | [
"",
"javascript",
"dom",
""
] |
I have some code that needs to know how many actual cores are available on my particular machine, and whether or not Hyperthreading is enabled.
Is there a way to do this in C#?
Update: The machines are a mix of XP and Vista
Update: Accessing 'Win32\_Processor.NumberOfCores' or 'Win32\_Processor.NumberOfLogicalProcessors' throws an exception (a ManagmentException with the message "Not Found") on one of the machines (but not all of them) | On Vista and higher you can use GetLogicalProcessorInformation via PInvoke to get the number of logical processor units.
On Windows XP there's no way via C# to reliably differentiate hyper-threading from other multi-processor/core configurations. The WMI solution that someone posted will class multi-core processors as hyper-threaded.
Prior to Vista the only reliable means is to check the CPUID of the processor. To use this you could create a native DLL that can be called from your managed code. The following Intel code [sample](http://www.mail-archive.com/redhat-devel-list@redhat.com/msg06114.html) would be a good starting point. | Simple answer to the first question at least: *Environment.ProcessorCount* should return the number of cores on the machine.
**Edit**: [Here](http://community.devpinoy.org/blogs/cvega/archive/2006/04/07/2658.aspx)'s a non-WMI-based method of checking for whether Hyperthreading is enabled (not that it's any nicer necessarily). Also see [this](http://www.codeproject.com/KB/system/countingprocessors.aspx?df=100&forumid=149329&exp=0&select=1577587) article. | How do I tell if the machine my program is running on uses hyperthreading? (C#) | [
"",
"c#",
"hyperthreading",
""
] |
I am invoking PHP cURL method on a server and the response is XML type. cURL is saving the output (after removing the tags) in a scalar type variable. Is there a way to store it in an object/hash/array so that it's easy to parse? | ```
<?php
function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}
$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);
foreach($oXML->entry as $oEntry){
echo $oEntry->title . "\n";
}
``` | Just add `header('Content-type: application/xml');` before your echo of the XML response and you will see an XML page. | PHP cURL, extract an XML response | [
"",
"php",
"curl",
""
] |
I want to use JDOM to read in an XML file, then use XPath to extract data from the JDOM Document. It creates the Document object fine, but when I use XPath to query the Document for a List of elements, I get nothing.
My XML document has a default namespace defined in the root element. The funny thing is, when I remove the default namespace, it successfully runs the XPath query and returns the elements I want. What else must I do to get my XPath query to return results?
XML:
```
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.foo.com">
<dvd id="A">
<title>Lord of the Rings: The Fellowship of the Ring</title>
<length>178</length>
<actor>Ian Holm</actor>
<actor>Elijah Wood</actor>
<actor>Ian McKellen</actor>
</dvd>
<dvd id="B">
<title>The Matrix</title>
<length>136</length>
<actor>Keanu Reeves</actor>
<actor>Laurence Fishburne</actor>
</dvd>
</collection>
```
Java:
```
public static void main(String args[]) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document d = builder.build("xpath.xml");
XPath xpath = XPath.newInstance("collection/dvd");
xpath.addNamespace(d.getRootElement().getNamespace());
System.out.println(xpath.selectNodes(d));
}
``` | **XPath 1.0** doesn't support the concept of a default namespace (**XPath 2.0** does).
Any unprefixed tag is always assumed to be part of the no-name namespace.
When using **XPath 1.0** you need something like this:
```
public static void main(String args[]) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document d = builder.build("xpath.xml");
XPath xpath = XPath.newInstance("x:collection/x:dvd");
xpath.addNamespace("x", d.getRootElement().getNamespaceURI());
System.out.println(xpath.selectNodes(d));
}
``` | I had a similiar problem, but mine was that I had a mixture of XML inputs, some of which had a namespace defined and others that didn't. To simplify my problem I ran the following JDOM snippet after loading the document.
```
for (Element el : doc.getRootElement().getDescendants(new ElementFilter())) {
if (el.getNamespace() != null) el.setNamespace(null);
}
```
After removing all the namespaces I was able to use simple *getChild("elname")* style navigation or simple XPath queries.
I wouldn't recommend this technique as a general solution, but in my case it was definitely useful. | Default XML namespace, JDOM, and XPath | [
"",
"java",
"xml",
"xpath",
"jdom",
""
] |
In c# when you want to divide the result of a method such as below, what is the best way to force it to return a double value rather than the default integer.
```
(int)Math.Ceiling((double)(System.DateTime.DaysInMonth(2009, 1) / 7));
```
As you can see I need the division to return a double so I can use the ceiling function. | A division of two `int` numbers returns an `int`, truncating any decimal points. This is generally true for other data types as well: arithmetic operations don't change the type of their operands.
To enforce a certain return type, you must therefore convert the operands appropriately. In your particular case, it's actually sufficient to convert one of the operators to `double`: that way, C# will perform the conversion for the other operand automatically.
You've got the choice: You can explicitly convert either operand. However, since the second operand is a *literal*, it's better just to make that literal the correct type directly.
This can either be done using a type suffix (**`d`** in the case of `double`) or to write a decimal point behind it. The latter way is generally preferred. in your case:
```
(int)Math.Ceiling(System.DateTime.DaysInMonth(2009, 1) / 7.0);
```
Notice that this decimal point notation always yields a *`double`*. To make a `float`, you need to use its type suffix: `7f`.
This behaviour of the fundamental operators is the same for nearly all languages out there, by the way. One notable exception: VB, where the division operator generally yields a `Double`. There's a special integer division operator (`\`) if that conversion is not desired. Another exception concerns C++ in a weird way: the difference between two pointers of the same type is a `ptrdiff_t`. This makes sense but it breaks the schema that an operator always yields the same type as its operands. In particular, subtracting two `unsigned int` does *not* yield a `signed int`. | Change the 7 to a double:
```
(int) Math.Ceiling(System.DateTime.DaysInMonth(2009, 1) / 7.0);
``` | What is the best practice to make division return double in C# | [
"",
"c#",
""
] |
I have a small list of checkboxes (see below), and I noticed I can use an input element with type="reset" and it will uncheck all the boxes.
I know using the input would be better than an "onClick" event of the link, because I wouldn't be relying on JavaScript, but for this example I have both.
```
<a onclick="javascript:document.myList.reset();" href="#">select none</a> |
<a href="#">select all</a>
<form name="myList">
<input type="checkbox" name="item1"/>Item 1<br/>
<input type="checkbox" name="item2"/>Item 2<br/>
<input type="reset" name="none"/>
<input type="submit" name="submit"/>
</form>
```
What is the best way of implementing the "Select all"?
I would probably need to write a JavaScript function that loops through all "input" elements of the form "myList" with type="checkbox" and set the value to "0" or something.
Also, what is the correct "cross-browser" way of doing this?
I assume there is no HTML form way of doing this like the reset? (I couldn't find one.) | Yeah, you'd use JS.
```
for(var ix = 0; ix < document.myList.elements.count; ix++)
if(document.myList.elements[ix].type == 'checkbox')
document.myList.elements[ix].checked = true;
``` | Reset will set it to its initial state. That means that if all of your checkboxes were set to checked before and then changed pressing reset would take them back to that state.
I would suggest using jQuery for for making changes to many elements at a time:
```
$("form[name='myList'] :checkbox").attr("checked", true);
```
or with pure JavaScript:
```
for(var i in document.myList.childNodes)
if(document.myList.childNodes[i].type == "checkbox")
document.myList.childNodes[i].checked = true;
``` | Select all HTML checkboxes | [
"",
"javascript",
"html",
"forms",
""
] |
Can someone please explain what the `partition by` keyword does and give a simple example of it in action, as well as why one would want to use it? I have a SQL query written by someone else and I'm trying to figure out what it does.
An example of partition by:
```
SELECT empno, deptno, COUNT(*)
OVER (PARTITION BY deptno) DEPT_COUNT
FROM emp
```
The examples I've seen online seem a bit too in-depth. | The `PARTITION BY` clause sets the range of records that will be used for each "GROUP" within the `OVER` clause.
In your example SQL, `DEPT_COUNT` will return the number of employees within that department for every employee record. (It is as if you're de-nomalising the `emp` table; you still return every record in the `emp` table.)
```
emp_no dept_no DEPT_COUNT
1 10 3
2 10 3
3 10 3 <- three because there are three "dept_no = 10" records
4 20 2
5 20 2 <- two because there are two "dept_no = 20" records
```
If there was another column (e.g., `state`) then you could count how many departments in that State.
It is like getting the results of a `GROUP BY` (`SUM`, `AVG`, etc.) without the aggregating the result set (i.e. removing matching records).
It is useful when you use the `LAST OVER` or `MIN OVER` functions to get, for example, the lowest and highest salary in the department and then use that in a calculation against this records salary *without* a sub select, which is much faster.
Read the linked [AskTom article](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3170642805938) for further details. | The concept is very well explained by the accepted answer, but I find that the more example one sees, the better it sinks in. Here's an incremental example:
1. **Boss says** "get me number of items we have in stock grouped by brand"
**You say**: "no problem"
```
SELECT
BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
```
Result:
```
+--------------+---------------+
| Brand | Count |
+--------------+---------------+
| H&M | 50 |
+--------------+---------------+
| Hugo Boss | 100 |
+--------------+---------------+
| No brand | 22 |
+--------------+---------------+
```
2. **The boss says** "Now get me a list of all items, with their brand AND number of items that the respective brand has"
You may try:
```
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
```
But you get:
```
ORA-00979: not a GROUP BY expression
```
This is where the `OVER (PARTITION BY BRAND)` comes in:
```
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID) OVER (PARTITION BY BRAND)
FROM
ITEMS;
```
Which means:
* `COUNT(ITEM_ID)` - get the number of items
* `OVER` - Over the set of rows
* `(PARTITION BY BRAND)` - that have the same brand
And the result is:
```
+--------------+---------------+----------+
| Items | Brand | Count() |
+--------------+---------------+----------+
| Item 1 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 2 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 3 | No brand | 22 |
+--------------+---------------+----------+
| Item 4 | No brand | 22 |
+--------------+---------------+----------+
| Item 5 | H&M | 50 |
+--------------+---------------+----------+
```
etc... | Oracle "Partition By" Keyword | [
"",
"sql",
"oracle",
"window-functions",
""
] |
Is there any practical difference between `WCHAR` and `wchar_t`? | Well, one practical difference would be that `WCHAR` doesn't exist on my platform. For Windows only (and with no intention of ever porting the program to another platform) and with the necessary headers included, it's the same (since `WCHAR` is just a `typedef`). | `wchar_t` is a distinct type, defined by the C++ standard.
`WCHAR` is *non*standard, and as far as I know, exists only on Windows. However, it is simply a `typedef` (or possibly a macro) for `wchar_t`, so it makes no practical difference.
Older versions of MSVC did not have `wchar_t` as a first-class type—instead it was simply a `typedef` for `short`
Most likely, Microsoft introduced `WCHAR` to represent a "wide character type" across any compiler version, whether or not `wchar_t` existed as a native type.
You should use `wchar_t` in your code though. That's what it's for. | What is the difference between 'WCHAR' and 'wchar_t'? | [
"",
"c++",
""
] |
Is there a portable wchar\_t in C++? On Windows, its 2 bytes. On everything else is 4 bytes. I would like to use wstring in my application, but this will cause problems if I decide down the line to port it. | If you're dealing with use internal to the program, don't worry about it; a wchar\_t in class A is the same as in class B.
If you're planning to transfer data between Windows and Linux/MacOSX versions, you've got more than wchar\_t to worry about, and you need to come up with means to handle all the details.
You could define a type that you'll define to be four bytes everywhere, and implement your own strings, etc. (since most text handling in C++ is templated), but I don't know how well that would work for your needs.
Something like `typedef int my_char; typedef std::basic_string<my_char> my_string;` | What do you mean by "portable wchar\_t"? There is a `uint16_t` type that is 16bits wide everywhere, which is often available. But that of course doesn't make up a string yet. A string has to know of its encoding to make sense of functions like `length()`, `substring()` and so on (so it doesn't cut characters in the middle of a code point when using utf8 or 16). There are some unicode compatible string classes i know of that you can use. All can be used in commercial programs for free (the Qt one will be compatible with commercial programs for free in a couple of months, when Qt 4.5 is released).
[`ustring`](http://www.gtkmm.org/docs/glibmm-2.4/docs/reference/html/classGlib_1_1ustring.html) from the [`gtkmm`](http://www.gtkmm.org/) project. If you program with gtkmm or use glibmm, that should be the first choice, it uses `utf-8` internally. [`Qt`](http://qt.nokia.com/) also has a string class, called QString. It's encoded in `utf-16`. [`ICU`](http://www.icu-project.org/) is another project that creates portable unicode string classes, and has a `UnicodeString` class that internally seems to be encoded in utf-16, like Qt. Haven't used that one though. | Portable wchar_t in C++ | [
"",
"c++",
"windows",
"portability",
"wchar-t",
"wstring",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.