Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Here's a snippet of code that I saw in some code I'm maintaining.
```
Object lock = new Object();
synchronized( lock )
{
try
{
lock.wait( 50000 );
Thread.sleep( 3000 );
}
catch(Exception ex)
{
}
}
```
The developer wants to suspend the current thread for some amount of time and is using Object#wait as the mechanism. Obviously it is bad form to use the wait/notify protocol for this reason; however, is there any major difference between calling wait(millisec) and a Thread.sleep ? | Aside from having to get a monitor before waiting() there's no major difference anymore so long as no one external is going to be .notify()ing.
In ancient Java code you'd see people using wait() instead of Thread.sleep() because Thread.sleep() would freeze the whole application on systems without preemptive multitasking (I'm looking at you OS9). Technically wait() also let's you use nano-resolution waits, but in practice they're seldom that accurate. | Note that there is one key difference in using Object.wait() and Thread.sleep() *inside* a synchronization block: Thread.sleep() does not release the locked monitor, so no-one else can become the owner of the monitor.
In addition, Object.wait() does not guarantee that the delay indicated will be obeyed strictly. First of all, after the delay passes, the thread may still be waiting for another thread that has become the monitor owner in the meantime; and it may compete with other threads waiting to grab the monitor.
Second, the mythical spurious wake-up, as it is described in the Java 6 API javadoc:
> A thread can also wake up without
> being notified, interrupted, or timing
> out, a so-called spurious wakeup.
Unlikely as it is, every piece of code using Object.wait() should take it into consideration. | Using Object.wait(millisec) to simulate sleep | [
"",
"java",
"multithreading",
"concurrency",
""
] |
I am trying to write a Factory Pattern to create either a MainMode or a TestMode in my program. The code I was previously using to create these objects was:
```
play = (isMode) ? new MainMode(numberRanges, numberOfGuesses) :
new TestMode(numberRanges, numberOfGuesses, randNo());
```
My Game (play) would either create a MainMode object or a TestMode object depending on a boolean value (isMode). As you can see I am adding an extra value into my TestMode object (randNo()). This value is used within TestMode to allow the user to input their own "Random Number", whereas within the MainMode constructor this was randomly generated. In this program both MainMode and TestMode are sub-classes of the abstract class Game.
Now I want to replace this line with a Factory Pattern, although I am unsure as my TestMode constructor requires an extra object and I am unsure where I would need to pass this value. If I were going to create a Factory it'd need to be in a new class, probably named GameFactory or ModeFactory or something along those lines.
How would I go about this?
**EDIT:** The problem here is that the code above is in my GUI, where the values for numberRanges, numberOfGuesses and the randNo() method are. I want to create a Factory class but I am unable to pass these values through because randNo() activates itself. Here is my randNo() method.
```
private int randNo() {
boolean isValidNumber = true;
int testRandomNum = 0;
while(isValidNumber) {
try {
testRandomNum = Integer.parseInt(JOptionPane.showInputDialog("Enter Random Number"));
isValidNumber = false;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Sorry, but the number you entered was invalid");
}
}
return testRandomNum;
}
```
The problem is that whenever I pass randNo() it displays the JOptionPane. As I've said already the GUI and Logic is separate. The GUI is in a GUI package whilst the rest of the code is in the logic package. | Note that some of the other answers may arguably describe factories, but don't describe the *GOF Factory Pattern*.
> Now I want to replace this line with a
> Factory Pattern, although I am unsure
> as my TestMode constructor requires an
> extra object and I am unsure where I
> would need to pass this value.
Well, you could think of it this way: MainMode, not TestMode, is the one that does a special thing. The special thing it does, is to *ignore* the given number, in order to ensure it's really random. In this way of thinking about it, it's MainMode that does something extra.
Or, if other than the randomness, MainMode and TestMode are not different, then you'd be thinking perhaps that you can factor out that similarity into one class, which is provided one of two Strategies for calculating random numbers. One Strategy would actually be random, and one would be perverse, with a random range of only 1 value.
But let's assume that there are other differences between MainMode and TestMode -- presumably TestMode outputs extra debugging to System.out or something.
We can still factor out "how do we supply randomness" from are we testing or playing the game for real". These are *orthogonal* concerns.
So now we know that in addition to whatever else a 'Mode does, it should accept a Randomness Strategy. Then we could, for example, when you're told that the standard platform random isn't really random enough, you can replace it with a better random.
Or you can do testing where the range of randoms is constrained to only two choices, or always alternates from one to zero, or returns on each call the next value in some Vecrtor or Iterator.
So we use the GOF Strategy Pattern to build the randomness strategies:
```
interface RandomStrategy {
public double random();
}
public class NotSoRandom implements RandomStrategy {
private double r;
public NotSoRandom( final double r ) { this.r = r; }
public double random() { return r; }
}
public class PlatformRandom implements RandomStrategy {
public double random() { return Math.random(); }
}
```
Now, if your whole app only ever creates one 'Mode, there's no need for a factory; you use a factory when you need to create the same class type over and over; the Factory is in fact just a Strategy for creating the right kind of (sub) class.
In production code, I've used factories where I have some generic class that creates stuff, and I need to tell how to create the right subclass to create; I pass in a factory to do that.
Now we create a Factory pattern for the 'Mode; this will be surprisingly similar to the Strategy pattern:
```
abstract class Mode() {
private RandomStrategy r;
public Mode( final RandomStrategy r ) { this.r = r; }
// ... all the methods a Mode has
}
public class MainMode implements Mode {
public MainMode( final RandomStrategy r ) { super(r); }
}
public class TestMode implements Mode {
public TestMode( final RandomStrategy r ) { super(r); }
}
interface ModeFactory{
public Mode createMode( final RandomStrategy r );
}
public class MainFactory() {
public Mode createMode( final RandomStrategy r ) {
return new MainMode(r);
}
}
public class TestFactory() {
public Mode createMode( final RandomStrategy r ) {
return new TestMode(r);
}
}
```
So now you know about the Factory Pattern and Strategy Pattern, and how they're similar in "shape", but different in how they're used: Factory Pattern is Object Creational and returns an object to be used; Strategy is Object Behavioral, and an instance is usually created explicitly and a reference is held to the instance, to encapsulate an algorithm. But in terms of the structure, they're quite similar.
Edit: the OP asks, in a comment, "How would I integrate this into my GUI?"
Well, none of this belongs in the GUI of your program, except possibly the 'Mode. You'd create the ConcreteStrategy and pass it to the preferred Factory in some setup routine, possibly determining which to use based on command line arguments or config files. basically, you'd select the correct factory very much as you selecting the correct class in your original post. *Again, if you're only ever creating one of something, you don't need a Factory; factories are for mass production (or creating families of related concrete types -- though that's beyond the scope of this question).*
(Assume we have a game where the user can select on the command line whether to fight robots or dragons; then we'd want to instantiate an OpponentFactory that produce Opponents (an interface), with derived classes RobotOpponent and DragonOpponent, and pass that factory to the part of the game that spawnsNewOpponent(). Similarly, a user might select brave or cowardly opponents, which we'd set up as a Strategy. We don't need to make more Strategy instances, as a Strategy is usually idempotent (stateless and singleton).)
```
static int main( String[] args ) {
// setup game world
final RandomStrategy r = "random".equals(args[0])
? new PlatformRandom() : new NotSoRandom( Integer.intValue(args[0]) ) ;
// notice the simlarity to the code you originally posted;
// we factored out how to achieve "randomness" as a Strategy.
// now we will use our Strategy to setup our Factory;
final ModeFactory f = "test".equals(args[1])
? new TestFactory(r) : new MainFactory(r);
// also similar to your code
// we've just added an extra level of indirection:
// instead of creating a Mode, we've created an object that can create Modes
// of the right derived type, on demand.
// call something that uses our factory
functionThatRunsameAndNeedstoProduceModesWhenevertNeedsTo( f );
}
``` | The whole point of a Factory is that it should have the needed state to create your Game appropriately.
So I would build a factory like this:
```
public class GameFactory {
private boolean testMode;
public GameFactory(boolean testMode) {
this.testMode = testMode;
}
public Game getGame(int numberRanges, int numberOfGuesses) {
return (testMode) ? new MainMode(numberRanges, numberOfGuesses) :
new TestMode(numberRanges, numberOfGuesses, getRandom());
}
private int getRandom() {
. . . // GUI code here
}
}
```
Now you can initialize this factory somwhere in your app, and pass it in to whatever code needs to create a Game. This code now doesn't need to worry about what mode it is, and passing extra random params - it uses a well known interface to create Games. All the needed state is internalized by the GameFactory object. | Best way to implement the Factory Pattern in Java | [
"",
"java",
"factory-pattern",
""
] |
I've been struggling with event handling in backgroundworker threads.
All the documentation I've come across make me believe that when a DoWork event handler throws an exception that exception should be dealt with in the RunWorkerCompleted handler and that exception will be available in the Error property of the RunWorkerCompletedEventArgs.
This is fine, but during debug time I always see an exception unhandled by user code message. This makes me believe there is a problem with my approach.
What steps should I take to resolve this?
Regards,
Jonathan | I've seen this behavior before, and I've gotten around it by decorating the DoWork handler with the `System.Diagnostics.DebuggerNonUserCode` attribute:
```
[System.Diagnostics.DebuggerNonUserCode]
void bw_DoWork(object sender, DoWorkEventArgs e)
{ ... }
```
Note that you'll only see this if you're running in the debugger; even without the attribute, all is as it should be when running from the shell.
I looked this up again, and I still can't see any good reason why you need to do this. I'm calling it a debugger misfeature. | I've had this problem before. The e.Error only gets set when you don't run in Debug mode. If you run in Debug, exectuion stops at the spot of the Exception. However, run the same program in Non debug mode (in VS Debug -> Start Without Debugging or Ctrl+F5) and the nasty exception dialog WON'T come up, and e.Error will be the exception. Not sure why, but that's how it works.... | Background Worker Event Handling | [
"",
"c#",
"multithreading",
"debugging",
"backgroundworker",
""
] |
The application I work uses XML for save/restore purposes. Here's an example snippet:
```
<?xml version="1.0" standalone="yes"?>
<itemSet>
<item handle="2" attribute1="30" attribute2="blah"></item>
<item handle="5" attribute1="27" attribute2="blahblah"></item>
</itemSet>
```
I want to be able to **efficiently pre-process** the XML which I read in from the configuration file. In particular, I want to extract the *handle* values from the example configuration above.
Ideally, I need a function/method to be able to pass in an opaque XML string, and return all of the handle values in a list. For the above example, a list containing 2 and 5 would be returned.
I know there's a regular expression out there that will help, but is it the most efficient way of doing this? String manipulation can be costly, and there may be potentially 1000s of XML strings I would need to process in a configuration file. | You are looking for a stream oriented XML parser that reads each node in your XML one at a a time rather then loading the whole thing into memory.
One of the best known is the [SAX - Simple API for XML](http://sourceforge.net/projects/sax/)
Here's a [good article](http://www.xml.com/pub/a/1999/11/cplus/index.html?page=2) describing why to use SAX and also specific of using SAX in C++.
You can think of SAX as a parser of XML that only loads the bare minimum into memory and so works well on very large XML documents. As compare to the Regex or DOM approach that will require you to load the entire document into memory. | I'd guess a regex of some sort is going to be your best option for efficiency. It's going to be faster than parsing the XML into any sort of structural construct, and as long as you can extract all the information you will need in one pass, it's likely the most efficient method. | Efficient way of extracting specific numerical attributes from XML | [
"",
"c++",
"xml",
"regex",
"performance",
""
] |
I've created a class with properties that have default values. At some point in the object's lifetime, I'd like to "reset" the object's properties back to what they were when the object was instantiated. For example, let's say this was the class:
```
public class Truck {
public string Name = "Super Truck";
public int Tires = 4;
public Truck() { }
public void ResetTruck() {
// Do something here to "reset" the object
}
}
```
Then at some point, after the `Name` and `Tires` properties have been changed, the `ResetTruck()` method could be called and the properties would be reset back to "Super Truck" and 4, respectively.
What's the best way to reset the properties back to their initial hard-coded defaults? | You can have the initialization in a method instead of inlining with the declaration. Then have the constructor and reset method call the initialization method:
```
public class Truck {
public string Name;
public int Tires;
public Truck() {
Init();
}
public void ResetTruck() {
Init();
}
private void Init() {
Name = "Super Truck";
Tires = 4;
}
}
```
Another way is not to have a reset method at all. Just create a new instance. | Reflection is your friend. You could create a helper method to use Activator.CreateInstance() to set the default value of Value types and 'null' for reference types, but why bother when setting null on a PropertyInfo's SetValue will do the same.
```
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < properties.Length; ++i)
properties[i].SetValue(this, null); //trick that actually defaults value types too.
```
To extend this for your purpose, have private members:
```
//key - property name, value - what you want to assign
Dictionary<string, object> _propertyValues= new Dictionary<string, object>();
List<string> _ignorePropertiesToReset = new List<string>(){"foo", "bar"};
```
Set the values in your constructor:
```
public Truck() {
PropertyInfo[] properties = type.GetProperties();
//exclude properties you don't want to reset, put the rest in the dictionary
for (int i = 0; i < properties.Length; ++i){
if (!_ignorePropertiesToReset.Contains(properties[i].Name))
_propertyValues.Add(properties[i].Name, properties[i].GetValue(this));
}
}
```
Reset them later:
```
public void Reset() {
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < properties.Length; ++i){
//if dictionary has property name, use it to set the property
properties[i].SetValue(this, _propertyValues.ContainsKey(properties[i].Name) ? _propertyValues[properties[i].Name] : null);
}
}
``` | How do I reinitialize or reset the properties of a class? | [
"",
"c#",
"class",
"properties",
"instantiation",
""
] |
On a customer machine (WinXP SP2) to which I have no access, I have a Win32 EXE (unmanaged C++) that crashes on startup. I guess the best way to troubleshoot this is to obtain a (mini-)dump and analyze it later with windbg or similar.
Now, I would normally tell the customer to install Debugging Tools for Windows and run
```
cscript adplus.vbs -crash
```
However, it appears that you can't use adplus for apps that crash on startup (<http://support.microsoft.com/kb/q286350/> says that "Do not use ADPlus in the following situations: If you must troubleshoot a program or process that quits unexpectedly during startup"). The same article says "use User Mode Process Dump", but I failed to install it successfully.
Any idea of how to get a dump of a process that crashes on startup on Win32? | You can install [WinDBG](http://www.microsoft.com/whdc/devtools/debugging/) on the client machine and then use "[Image File Execution Options](http://support.microsoft.com/kb/824344)" and set WinDBG to open once that the process has started. Then run the crashing process and WinDBG will open up immediately. press ***g*** (Go) and wait for the process to crash then type "**.dump /mfh dumpFileName.dmp**". Now you have dump file that you can debug. | Alternatively you may set up your own dump generation framework which automatically creates a process dump when any Unhandled exception is encountered. This would avoid clients having to install Windbg.
Use SetUnhandledExceptionFilter Win32 API to register the application level exception handler at the application start up. The registered callback function is called whenever there is any exception which is not handled. U may then create the process dump using MiniDumpWriteDump api from DbgHelp.dll.
Sample Code:-
```
LONG WINAPI My_UnhandledExceptionFilter(struct _EXCEPTION_POINTERS* ExceptionInfo)
{
HANDLE hFile = CreateFile("FileName",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
MINIDUMP_EXCEPTION_INFORMATION aMiniDumpInfo;
aMiniDumpInfo.ThreadId = GetCurrentThreadId();
aMiniDumpInfo.ExceptionPointers = ExceptionInfo;
aMiniDumpInfo.ClientPointers = TRUE;
MiniDumpWriteDump(GetCurrentProcess(),
GetCurrentProcessId(),
hFile,
(MINIDUMP_TYPE) (MiniDumpWithFullMemory|MiniDumpWithHandleData),
&aMiniDumpInfo,
NULL,
NULL);
CloseHandle(hFile);
return EXCEPTION_EXECUTE_HANDLER;
}
int main(int argc, char* argv[])
{
SetUnhandledExceptionFilter(&My_UnhandledExceptionFilter);
// User code throwing exception..
return 0;
}
```
NB:- The registered exception filter is not called when the process is being debugged. So during debugging if you put breakpoint in the exception filter function dont be surprised if it does not hit even after causing an Unhandled Exception. | Getting a dump of a process that crashes on startup | [
"",
"c++",
"winapi",
"startup",
"crash-dumps",
""
] |
Why is there so may ways to convert to a string in .net? The ways I have seen are .ToString, Convert.ToString() and (string). What is the Difference. | ## `Convert.ToString(obj)`
Converts the specified value to its equivalent String representation. Will return `String.Empty` if specified value is `null`.
## `obj.ToString()`
Returns a String that represents the current Object. This method returns a human-readable string that is culture-sensitive. For example, for an instance of the Double class whose value is zero, the implementation of Double.ToString might return "0.00" or "0,00" depending on the current UI culture. The default implementation returns the fully qualified name of the type of the Object.
This method can be overridden in a derived class to return values that are meaningful for that type. For example, the base data types, such as Int32, implement ToString so that it returns the string form of the value that the object represents. Derived classes that require more control over the formatting of strings than ToString provides must implement IFormattable, whose ToString method uses the current thread's CurrentCulture property.
## `(string)obj`
It's a cast operation, not a function call. Use it if you're sure that the object is of type string OR it has an implicit or explicit operator that can convert it to a string. Will return `null` if the object is `null AND of type String or of type which implements custom cast to string operator. See examples.`
## `obj as string`
Safe cast operation. Same as above, but instead of throwing an exception it will return `null` if cast operation fails.
---
**Hint**: Don't forget to use CultureInfo with `obj.ToString()` and `Convert.ToString(obj)`
## Example:
```
12345.6D.ToString(CultureInfo.InvariantCulture); // returns 12345.6
12345.6D.ToString(CultureInfo.GetCultureInfo("de-DE")); // returns 12345,6
Convert.ToString(12345.6D, CultureInfo.InvariantCulture); // returns 12345.6
Convert.ToString(12345.6D, CultureInfo.GetCultureInfo("de-DE")); // 12345,6
Convert.ToString(test); // String.Empty, "test" is null and it's type
// doesn't implement explicit cast to string oper.
Convert.ToString(null); // null
(string) null; // null
(string) test; // wont't compile, "test" is not a string and
// doesn't implement custom cast to string operator
(string) test; // most likely NullReferenceException,
// "test" is not a string,
// implements custom cast operator but is null
(string) test; // some value, "test" is not a string,
// implements custom cast to string operator
null as string; // null
```
Here is an example of custom cast operator:
```
public class Test
{
public static implicit operator string(Test v)
{
return "test";
}
}
``` | * **`.ToString()`** can be called from *any* object. However, if the type you call it on doesn't have a good implementation the default is to return the type name rather than something meaningful about the instance of that type. This method is inherited from the base `Object` type, and you can overload it in your own types to do whatever you want.
* **`(string)`** is a *cast*, not a function call. You should only use this if the object you need already is a string in some sense, or if you know there is a good implicit conversion available (like from `int`). This will throw an exception is the object cannot be converted (including when the object is `null`)
* **`as string`** is another way to write `(string)`, but it differs in that it returns `null` rather than throwing an exception if the cast fails.
* **`Convert.ToString()`** attempts to actually *convert* the argument into a string. This is the best option if you don't really know much about the argument. It can be slow because it has to do a lot of extra work to determine what kind of results to return, but that same work also makes it the most robust option when you don't know very much about the argument. If nothing else is available, it will fall back to calling the argument's `.ToString()` method.
* **`String.Format`** The string class' `.Format` method can also be used to convert certain types to strings, with the additional advantage that you have some control over what the resulting string will look like.
* **`Serialization`** This is a little more complicated, but .Net includes a couple different mechanisms for converting objects into a representation that can be safely stored and re-loaded from disk or other streaming mechanism. That includes a binary formatter, but most often involves converting to a string in some format or other (often xml). Serialization is appropriate when you want to later convert the your string back into it's originating type, or if you want a complete representation of a complex type. | String casts in .NET | [
"",
"c#",
".net",
"string",
"casting",
""
] |
I am trying to bring focus to window using jquery. The window is popup initiated through a button click on the parent page. I have some ajax calls going on in the child window, so data is being updated. My issue is that if the user clicks on the parent window and hides the child behind it, i would like to bring that child window back to the forefront if there is a data update.
inside $(document).ready I wire up these events:
```
$(window).blur(function(){
WindowHasFocus =false;
}).focus(function(){
WindowHasFocus =true;
});
```
Then, if data is updated, I call this function:
```
function FocusInput(){
if(!WindowHasFocus){
$(window).focus();
}
}
```
This works as expected in IE8, but in FireFox(and all other browsers) the Blur event nevers seem to fire if I click the parent window. Any suggestions/ideas on how achieve this?
update:
Total facepalm moment:
In FireFox:
\* Tools
\* Options…
\* Content tab
\* Advanced button next to “Enable JavaScript”
\* check the box named "Raise or Lower Windows" | Total facepalm moment: In FireFox:
* Tools
* Options…
* Content tab
* Advanced button next to “Enable JavaScript”
* check the box named "Raise or Lower Windows"
This is turned off by default and must be enabled. And also, i assumed that since it didnt work in Chrome, that Safari would be the same, but you know what they say about "assuming" (it works in Safari, but not Chrome). | If there is not a strong reason for having two separate windows then it would be better use "modal boxes", there are plenty of examples out there and jquery plugins to achieve that. An example of such a plugin:
<http://www.84bytes.com/2008/06/02/jquery-modal-dialog-boxes/> | How to bring focus to a window in jquery? | [
"",
"javascript",
"jquery",
""
] |
What would be the best way to store a tree like the one below in app.config and how would I deserialize this information from it?
```
Tree
|-node1-
| |-name - value
| |-name - value
| | ......
|-node2-
| |-name - value
| |-name - value
| | ......
|-node3-
| |-name - value
| |-name - value
| | ......
```
I can convert that tree to xml if that helps.
Thanks for any assistance in advance. | Use a custom configuration section. For one way to do this, see [Configuration Section Designer](http://www.codeplex.com/csd/). You can do it manually, but you might like to play with CSD and see the code it generates. | You can extend .config with your own types. These can be elements containing other elements and attributes. This area does seem to be poorly documented but there are examples out there.
Start with the `System.Configuration.ConfigurationElement` class. | the best way to store tree like information in app.config | [
"",
"c#",
".net",
"asp.net",
"c#-3.0",
"scsf",
""
] |
My Java program uses ProcessBuilder (with redirectErrorStream set true) and has a loop that runs the processes's inputstream's read method, which is blocking. The external program I'm calling then comes to a stop waiting for input and stdin. I now want to kill the process. Is this not done by (in a seperate thread) calling the process's destroy method, and calling the inputstream's close method to stop the read method from blocking anymore, so that my initial thread can end its life?
For some reason `process.getInputStream().close()` blocks. From the JavaDoc I don't see why this can happen. Furthermore, I don't understand why the javadoc says "The close method of InputStream does nothing." ([link to javadoc](http://java.sun.com/javase/6/docs/api/java/io/InputStream.html#close())) Could someone explain this?
Thanks :-) | Regarding the blocking behavior, there is a known issue in Java that can cause deadlock when communicating with another process. I can't tell if this is what you're seeing but it's worth looking into. The document for [java.lang.Process](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html) says:
> Because some native platforms only
> provide limited buffer size for
> standard input and output streams,
> failure to promptly write the input
> stream or read the output stream of
> the subprocess may cause the
> subprocess to block, and even
> deadlock. | I think I figured this out. Obviously it is important to call process.getOutputStream().close() before process.getInputStream().close() and process.getErrorStream().close(). | why does java's inputstream.close() block? | [
"",
"java",
"inputstream",
""
] |
I am trying to build Groovy from source (on RH Linux) using ant, but for some reason it thinks that my Java version is 1.4, and not 1.6, and thus it won't compile. The offending lines seem to be
```
<condition property="groovy.build.vm5">
<not>
<contains string="${ant.java.version}" substring="1.4"/>
</not>
</condition>
```
in build.xml.
When I type javac -version on the command line, it displays "javac 1.6.0\_11". Any ideas? | Check the value of the environment variables JDK\_HOME and JAVA\_HOME.
EDIT: "which java" will tell you which Java you're getting when you run java from the command line. If this tells you, for example, that you're getting "/usr/lib/jvm/java-6-sun/bin/java", you can set "JAVA\_HOME" to "/usr/lib/jvm/java-6-sun" | The answer of Jon Bright hints in a good direction: Possibly your installation of ant uses another java-version than the one you access via 'java -version'. This is influenced by the environment-variables JDK\_HOME and JAVA\_HOME.
**EDIT:** If these variables are not present, then ant should find the Java from the installation that called ant. But if you set these variables, ant will pick these. So setting this variables to the installation of JDK1.6 should be worth a try. On Linux your Java could be on a subdirectory of /usr/lib/jvm. | Why does ant think I have an old version of Java? | [
"",
"java",
"ant",
"groovy",
""
] |
In firefox, using this javascript:
```
top.location.hash = "#here%20are%20spaces";
```
changes the browser url to:
```
http://mysite.com/#here are spaces
```
I expected firefox to show the encoded spaces as %20 in the browser url.
1. What's going on here? Why is firefox not setting the url to the string as I passed it?
2. How can I force firefox to update the url with the encoded characters?
*and...*
If I add set the url to
```
top.location.hash = "#here%20are%20spaces%";
```
It works(!?), albeit with an extra unwanted % appended to the end. I am not sure if this is a bug or a feature. Ideas or references on how to proceed? | `%20` are replaced with an empty space (in firefox 3) just for readability purpose. You shouldn't worry about it. | It still seems to be an active [Firefox Bug](https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/245521) for this issue (albeit reported for Firefox in Ubuntu, but also seen for other OS).... | setting top.location.hash with %20 in firefox | [
"",
"javascript",
"firefox",
"hash",
"swfaddress",
""
] |
I've got a String column defined with
```
@Column(length = 4000)
```
The attribute contains log information and can be longer than the defined length. In this case, the field can be safely truncated without throwing an error message.
I'd like to find out the determined length of the column in the DAO class for the pojo so that I can truncate the string if necessary. How can I do that?
Regards,
Chris | Check out EJB's [answer](https://stackoverflow.com/questions/1816780/how-to-reuse-fieldlength-in-form-validation-and-ddl/1946901#1946901) to this question;
> [How to reuse fieldlength in form, validation and ddl ?](https://stackoverflow.com/questions/1816780/)
To paraphrase, if you wanted the length from the firstName column in the person table, you use this code.
```
person.getClass().getDeclaredField("firstName").getAnnotation(Column.class).length()
``` | Well, the easiest way to do it would be using [reflection](http://www.java2s.com/Code/Java/Language-Basics/JavaAnnotationAnnotationandReflection.htm) with your annotations. I won't be cheap though, in terms of performance. | How can I find out the length of a column in a JPA @Entity? | [
"",
"java",
"jpa",
""
] |
I've been writing a lot of code recently that involves interop with the Win32 API and have been starting to wonder what's the best way to deal with native (unmanaged) errors that are caused by calls to Windows API functions.
Currently, the calls to native functions look something like this:
```
// NativeFunction returns true when successful and false when an error
// occurred. When an error occurs, the MSDN docs usually tell you that the
// error code can be discovered by calling GetLastError (as long as the
// SetLastError flag has been set in the DllImport attribute).
// Marshal.GetLastWin32Error is the equivalent managed function, it seems.
if (!WinApi.NativeFunction(param1, param2, param3))
throw new Win32Exception();
```
The line that raises the exception can be equivalently rewritten as such I believe:
```
throw new Win32Exception(Marshal.GetLastWin32Error());
```
Now, this is all well in that it throws an exception appropriately containing the Win32 error code that was set as well as a (generally) human-readable description of the error as the `Message` property of the `Exception` object. However, I have been thinking that it would be advisable to modify/wrap at least some, if not all, of these exceptions so that they give a slightly more context-oriented error message, i.e. one more meaningful in whatever situation the native code is being used. I have considered several alternatives for this:
1. Specifying a custom error message in the constructor for `Win32Exception`.
```
throw new Win32Exception(Marshal.GetLastWin32Error(), "My custom error message.");
```
2. Wrapping the `Win32Exception` in another Exception object so that both the original error code and message are retained (the `Win32Exception` is now the `InnerException` of the parent exception).
```
throw new Exception("My custom error message.",
Win32Exception(Marshal.GetLastWin32Error()));
```
3. The same as 2, except using another `Win32Exception` as the wrapper exception.
4. The same as 2, except using a custom class derived from `Exception` as the wrapper exception.
5. The same as 2, except using a BCL (Base Class Library) exception as the parent when appropiate. Not sure whether it's even appropiate to set the `InnerException` to the `Win32Exception` in this case (perhaps for a low-level wrapper but not a higher-level/abstracted interface that doesn't make it obvious that Win32 interop is happening behind the scenes?)
Essentially what I want to know is: what is the recommended practice on dealing with Win32 errors in .NET? I see it done in open-source code in all sorts of different ways, but I was curious whether there were any design guidelines. If not, I'd be interested in your personal preferences here. (Perhaps you even use none of the above methods?) | This isn't really specific to Win32 exceptions; the question is, when should two different error cases be identified by two different Exception-derived types, and when should they throw the same type with different values stored inside it?
Unfortunately this is impossible to answer without knowing in advance all the situations your code will be called in. :) This is the problem with only being able to filter exceptions by type. Broadly speaking, if you have a strong feeling that it would be useful to treat two error cases differently, throw different types.
Otherwise, it is frequently the case that the string returned by Exception.Message just needs to be logged or displayed to the user.
If there is additional information, wrap the Win32Exception with something more high-level of your own. For example, you're trying to do something to a file, and the user you're running under doesn't have permission to do it. Catch the Win32Exception, wrap it in an exception class of your own, whose message gives the filename and the operation being attempted, followed by the inner exception's message. | My view has always been that the appropriate way to handle this depends on the target audience and how your class is going to be used.
If the caller of your class/method is going to realize that they are calling into Win32 in one form or another, I would use option 1) you have specified. This seems the most "clear" to me. (However, if this is the case, I'd name your class in a manner that makes it clear that the Win32 API is going to be used directly). That being said, there are exceptions in the BCL that actually subclass Win32Exception to be more clear, instead of just wrapping it. For example, SocketException derives from Win32Exception. I've never personally used that approach, but it does seem like a potentially clean way to handle this.
If the caller of your class is going to have no idea that you're calling into the Win32 API directly, I would handle the exception, and use a custom, more descriptive exception you define. For example, if I'm using your class, and there's no indication that you're using the Win32 api (since you're using it internally for some specific, non-obvious reason), I would have no reason to suspect that I may need to handle a Win32Exception. You could always document this, but it seems more reasonable to me to trap it and give an exception that would have more meaning in your specific business context. In this case, I might wrap the initial Win32Exception as an inner exception (ie: your case 4), but depending on what caused the internal exception, I might not.
Also, there are many times when a Win32Exception would be thrown from a native call, but there are other exceptions in the BCL that are more relevant. This is the case when you're calling into a native API that isn't wrapped, but there are similar functions that ARE wrapped in the BCL. In that case, I would probably trap the exception, make sure that it is what I'm expecting, but then throw the standard, BCL exception in its place. A good example of this would be to use SecurityException instead of throwing a Win32Exception.
In general, though, I would avoid option 2 and 3 you listed.
Option two throws a general Exception type - I would pretty much recommend avoiding that entirely. It seems unreasonable to wrap a specific exception into a more generalized one.
Option three seems redundant - There's really no advantage over Option 1. | Throwing a Win32Exception | [
"",
"c#",
"winapi",
"exception",
"win32exception",
""
] |
I am attempting to create a web application using Spring MVC, with Hibernate as its ORM layer. However, due to my inexperience with both frameworks I'm struggling.
The following code will properly display all the records I am looking for but still throw a stack trace into my logs. I'm having trouble finding thorough documentation concerning integrating Hibernate and SpringMVC (I've looked on springsource.org and read various articles on the interweb). Could anyone point out what I could be doing wrong here?
Please note that I have spent a few trying to track down answers on the internet for this, including looking at [this](https://stackoverflow.com/questions/345705/hibernate-lazyinitializationexception-could-not-initialize-proxy) SO question. Which was unfortunately no help.
I should also note that the ORM part of this application has been used and tested in a stand alone Java application without problems. So I believe the integration of Spring MVC and Hibernate is causing the issue.
Here is the stack trace (truncated) with the famous lazy initialization issue;
```
2009-03-10 12:14:50,353 [http-8084-6] ERROR org.hibernate.LazyInitializationException.<init>(LazyInitializationException.java:19) - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
at com.generic.orm.generated.SearchRule$$EnhancerByCGLIB$$92abaed6.toString(<generated>)
at java.lang.String.valueOf(String.java:2827)
at java.lang.StringBuffer.append(StringBuffer.java:219)
at org.apache.commons.lang.builder.ToStringStyle.appendDetail(ToStringStyle.java:578)
at org.apache.commons.lang.builder.ToStringStyle.appendInternal(ToStringStyle.java:542)
at org.apache.commons.lang.builder.ToStringStyle.append(ToStringStyle.java:428)
at org.apache.commons.lang.builder.ToStringBuilder.append(ToStringBuilder.java:840)
at org.apache.commons.lang.builder.ReflectionToStringBuilder.appendFieldsIn(ReflectionToStringBuilder.java:606)
.....
```
Here is a code from my web page controller;
```
private List<Report> getReports() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Report> reports = session.createCriteria(Report.class).list();
Hibernate.initialize(reports);
session.getTransaction().commit();
return reports;
}
```
Which is employed on the web page using this display html;
```
<table border="1">
<c:forEach items="${model.reports}" var="report">
<tr>
<td><c:out value="${report.id}"/></td>
<td><c:out value="${report.username}"/></td>
<td><c:out value="${report.thresholdMet}"/></td>
<td><c:out value="${report.results}"/></td>
<td><c:out value="${report.searchRule.name}"/></td>
<td><c:out value="${report.uuid}"/></td>
</tr>
</c:forEach>
</table>
```
Note: That I added report.searchRule.name to test if I could get at the objects within the report object. It displays fine.
And in my applicationContext.xml;
```
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
```
Here are the ORM mappings, just in case;
The hibernate.cfg.xml (as requested)
```
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://<removed></property>
<property name="hibernate.connection.username"><removed></property>
<property name="hibernate.connection.password"><removed></property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<mapping resource="com/generic/orm/generated/Report.hbm.xml"/>
<mapping resource="com/generic/orm/generated/FieldRule.hbm.xml"/>
<mapping resource="com/generic/orm/generated/Reconciliation.hbm.xml"/>
<mapping resource="com/generic/orm/generated/SearchRule.hbm.xml"/>
<mapping resource="com/generic/orm/generated/IndexTemplate.hbm.xml"/>
<mapping resource="com/generic/orm/generated/Field.hbm.xml"/>
<mapping resource="com/generic/orm/generated/ErrorCode.hbm.xml"/>
</session-factory>
</hibernate-configuration>
```
From report.hbm.xml
```
<hibernate-mapping>
<class name="com.generic.orm.generated.Report" table="Report" schema="dbo" catalog="CoolRecon">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<timestamp name="timeStamp" column="TimeStamp" />
<many-to-one name="searchRule" class="com.generic.orm.generated.SearchRule" fetch="select">
<column name="SearchRuleName" length="50" not-null="true" />
</many-to-one>
<many-to-one name="errorCode" class="com.generic.orm.generated.ErrorCode" fetch="select">
<column name="ErrorCodeId" />
</many-to-one>
<many-to-one name="reconciliation" class="com.generic.orm.generated.Reconciliation" fetch="select">
<column name="ReconciliationName" length="100" />
</many-to-one>
<property name="username" type="string">
<column name="Username" length="50" />
</property>
<property name="supersheetDate" type="timestamp">
<column name="SupersheetDate" length="23" not-null="true" />
</property>
<property name="milliSecondsTaken" type="long">
<column name="MilliSecondsTaken" not-null="true" />
</property>
<property name="thresholdMet" type="boolean">
<column name="ThresholdMet" not-null="true" />
</property>
<property name="results" type="int">
<column name="Results" not-null="true" />
</property>
<property name="exception" type="string">
<column name="Exception" length="750" />
</property>
<property name="uuid" type="string">
<column name="UUID" length="36" not-null="true" />
</property>
</class>
</hibernate-mapping>
``` | I am just guessing but from the stack trace it seems that toString is being called on SearchRule. Does SearchRule have any child objects that may not have been loaded? If SearchRule.toString was trying to get the value for an uninitialised child object that could result in the LazyInitializationException. | I just went through this LazyInitialization marathon.
The core problem is that you're trying to access an hibernate-managed entity outside of the lifecycle of the `Session`, i.e. in the web view of Spring MVC. In my case, this was a `List<>` `@OneToMany` association, which are lazily loaded by default.
There are a few different approaches -- Mark mentioned one, where you do a "dummy" iteration over the lazy associations. You can also force eager loading, either via the configuration (class-wide) (in JPA it'd be `@Fetch(value = FetchType.EAGER)`) or more specifically through the HQL. But this will prove more [problematic if your lazy associations are `Lists`](http://jroller.com/eyallupu/entry/hibernate_exception_simultaneously_fetch_multiple).
The cleanest solution I found was to use Spring's [`OpenEntityManagerInViewFilter`](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.html) (there's an `OpenSessionInViewFilter` for Hibernate) -- a simple servlet filter you drop in to `web.xml` (ahead of your other servlet filters), and Spring will automatically create a thread-safe, transaction-aware `Session` *per-HTTP-request*. No more `LazyInitializationException`! | Why am I getting a Hibernate LazyInitializationException in this Spring MVC web application when the data displays correctly? | [
"",
"java",
"hibernate",
"spring",
"web-applications",
"netbeans",
""
] |
The current project I inherited mainly revolves around one unnormalized table. There are some attempts at normalization but the necessary constraints weren't put in place.
Example: In the Project table, there is a client name (among other values) and there is also a clients table which just contains client names [no keys anywhere]. The clients table is just used as a pool of values to offer the user when adding a new project. There isn't a primary key on the clients table or a foreign key.
"Design patterns" such as this is common through the current state of the database and in the applications that use it. The tools I have my disposal are SQL Server 2005, SQL Server Management Studio, and Visual Studio 2008. My initial approach has been to manually determine which information needs normalization and running Select INTO queries. Is there a better approach than a case by case or anyway this could be automated?
**Edit:**
Also, I've discovered that a "work order number" isn't an IDENTITY (autonumber, unique) field and they are generated sequentially and are unique to each work order. There are also some gaps in the existing numbering but all are unique. Is the best approach for this writing a store procedure to generate dummy rows before migrating? | The best approach to migrating to a usable design? **CAREFULLY**
Unless you're willing to break (and fix) every application that currently uses the database, your options are limited, because you can't change the existing structure very much.
Before you begin, think carefully about your motivations - if you have an existing issue (a bug to fix, an enhancement to make) then go ahead slowly. However, it's rarely worthwhile to monkey around with a working production system just to achieve an improvement that nonone else will ever notice. Note that this can play into your favour - if there's an existing issue, you can point out to management that the most cost-effective way to fix things is to alter the database structure in *this* way. This means you have management support for the changes - and (hopefully) their backup if something turns pear shaped.
Some practical thoughts ...
**Make one change at a time** ... and **only** one change. Make sure each change is correct before you move on. The old proverb of "measure twice, cut once" is relevant.
**Automate Automate Automate** ... Never ever make the changes to the production system "live" using SQL Server Management Studio. Write SQL scripts that perform the entire change in one go; develop and test these against a **copy** of the database to make sure you get them right. Don't use production as your test server - you might accidentally run the script against production; use a dedicated test server (if the database size is under 4G, use SQL Server Express running on your own box).
**Backups** ... the first step in any script should be to backup the database, so that you've got a way back if something does go wrong.
**Documentation** ... if someone comes to you in twelve months, asking why feature **X** of their application is broken, you'll need a history of the exact changes made to the database to help diagnosis and repair. First good step is to keep all your change scripts.
**Keys** ... it's usually a good idea to keep the primary and foreign keys abstract, within the database and not revealed through the application. Things that look like keys at a business level (like your work order number) have a disturbing habit of having exceptions. Introduce your keys as additional columns with appropriate constraints, but don't change the definitions of existing ones.
Good luck! | 1. Create the new database the way you think it should be structured.
2. Create an importError table in the new database with columns like "oldId" and "errorDesc"
3. Write a straightforward, procedural, legible script that attempts to select a row from the old structure and insert it into the new structure. If an insert fails, log as specific an error as possible to the importError table (specifically, *why* the insert failed).
4. Run the script.
5. Validate the new data. Check whether there are errors logged to the importError table. If the data is invalid or there are errors, refactor your script and run it again, possibly modifying your new database structure where necessary.
6. Repeat steps 1-5 until you have a solid conversion script.
The result of this process will be that you have:
a) a new db structure that is validated against the old structure and tested against "pragmatism";
b) a log of potential issues you may need to code against (such as errors that you can't fix through your conversion because they require a concession in your schema that you don't want)
(I might note that it's helpful to write the script in your scripting/programming language of choice, rather than in, say, SQL.) | How should I approach migrating data from a "bad" database design to a usable design? | [
"",
"sql",
"sql-server",
"refactoring",
"rdbms",
"normalization",
""
] |
So I've been reading the Expert F# book by Apress, mostly using it as a reference when building a toy-ish F# library, but there's one thing I've failed to grasp and that's the "Option" type.
How does it work and what is it's real world usage? | The option type is at least *similar* to `Nullable<T>` and reference types in C#. A value of type `Option<T>` is either `None` which means there's no encapsuated value, or `Some` with a particular value of `T`. This is just like the way a `Nullable<int>` in C# is *either* the null value, *or* has an associated `int` - and the way a `String` value in C# is *either* a null reference, *or* refers to a String object.
When you use an option value, you generally specify two paths - one for the case where there *is* an associated value, and one where there *isn't*. In other words, this code:
```
let stringLength (str:Option<string>) =
match str with
| Some(v) -> v.Length
| None -> -1
```
is similar to:
```
int StringLength(string str)
{
if (str != null)
{
return str.Length;
}
else
{
return -1;
}
}
```
I believe the general idea is that *forcing* you (well, nearly) to handle the "no associated value/object" case makes your code more robust. | One of the best examples of real-world usage is for the [TryParse](http://msdn.microsoft.com/en-us/library/ms229009.aspx) pattern in .Net. See the first half of
<http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!181.entry>
for a discussion. | How does the option type work in F# | [
"",
"c#",
".net",
"f#",
""
] |
I've got a form that I'm handling with PHP. Before the user submits it, the Reset button works. But when they submit and the page reloads (I've made the form fields sticky based on the $\_POST values) the reset doesn't work. How can I fix that?
EDIT:
For example, a checkbox on the form:
```
<input type="checkbox" <?php if (isset($_POST['cb12'])){echo 'checked="checked"';} ?> name="cb12" tabindex="34" id=cb value="Education">
```
And the HTML:
```
<tr>
<td colspan="5" valign="top" class="addit" ><div class="sectionbreak topsp" >
<input type="hidden" name="failure" value="failure.html" >
<p>
<input type="submit" name="Submit" value="Submit" tabindex="49">
Sends your application by email to The Boggs</p>
<p>
<input type="reset" name="Reset" value="Reset" tabindex="50">
Clears all the fields</p>
</div></td>
</tr>
```
EDIT:
In the end, I just hid the button if the form has been submitted (but isn't complete). Maybe no one will notice. | I've just been through this exact thing, see my [previous question & the incredible helpful answers](https://stackoverflow.com/questions/680241/reset-form-with-jquery).
In the end I had to do a manual reset of the values in PHP.
EDIT: Not quite the same scenario for you as you seem to be populating the form values based on $\_POST rather than $\_SESSION as I did. In which case, see the answer I accepted via the link above. | The reset button undoes changes to the form, made by the user, it doesn't erase default values. If you want to erase all default values, you could use JavaScript to do something like:
```
<script type="text/javascript">
function resetForm(myFormId)
{
var myForm = document.getElementById(myFormId);
for (var i = 0; i < myForm.elements.length; i++)
{
if ('submit' != myForm.elements[i].type && 'reset' != myForm.elements[i].type)
{
myForm.elements[i].checked = false;
myForm.elements[i].value = '';
myForm.elements[i].selectedIndex = 0;
}
}
}
</script>
```
...
```
<form id="myFormId" ...>
<input name="reset" type="reset" onclick="resetForm('myFormId'); return false;" />
```
... | How can I use a reset button for php form? | [
"",
"php",
"forms",
"reset",
""
] |
I have the following code to do a postback to a remote URL:
```
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
checksLogger.error('HTTPError = ' + str(e.code))
except urllib2.URLError, e:
checksLogger.error('URLError = ' + str(e.reason))
except httplib.HTTPException, e:
checksLogger.error('HTTPException')
```
The postBackData is created using a dictionary encoded using urllib.urlencode. checksLogger is a logger using [logging](http://docs.python.org/library/logging.html).
I have had a problem where this code runs when the remote server is down and the code exits (this is on customer servers so I don't know what the exit stack dump / error is at this time). I'm assuming this is because there is an exception and/or error that is not being handled. So are there any other exceptions that might be triggered that I'm not handling above? | Add generic exception handler:
```
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
checksLogger.error('HTTPError = ' + str(e.code))
except urllib2.URLError, e:
checksLogger.error('URLError = ' + str(e.reason))
except httplib.HTTPException, e:
checksLogger.error('HTTPException')
except Exception:
import traceback
checksLogger.error('generic exception: ' + traceback.format_exc())
``` | From the [docs page](https://docs.python.org/2/library/urllib2.html#urllib2.urlopen) `urlopen` entry, it looks like you just need to catch [URLError](https://docs.python.org/2/library/urllib2.html#urllib2.URLError). If you really want to hedge your bets against problems within the urllib code, you can also catch `Exception` as a fall-back. Do **not** just `except:`, since that will catch `SystemExit` and `KeyboardInterrupt` also.
Edit: What I mean to say is, you're catching the errors it's supposed to throw. If it's throwing something else, it's probably due to urllib code not catching something that it should have caught and wrapped in a `URLError`. Even the stdlib tends to miss simple things like `AttributeError`. Catching `Exception` as a fall-back (and logging what it caught) will help you figure out what's happening, without trapping `SystemExit` and `KeyboardInterrupt`. | What errors/exceptions do I need to handle with urllib2.Request / urlopen? | [
"",
"python",
""
] |
I've been trying to replicate [Gnu Find](http://www.gnu.org/software/findutils/) ("find .") in PHP, but it seems impossible to get even close to its speed. The PHP implementations use at least twice the time of Find. Are there faster ways of doing this with PHP?
EDIT: I added a code example using the SPL implementation -- its performance is equal to the iterative approach
EDIT2: When calling find from PHP it was actually slower than the native PHP implementation. I guess I should be satisfied with what I've got :)
```
// measured to 317% of gnu find's speed when run directly from a shell
function list_recursive($dir) {
if ($dh = opendir($dir)) {
while (false !== ($entry = readdir($dh))) {
if ($entry == '.' || $entry == '..') continue;
$path = "$dir/$entry";
echo "$path\n";
if (is_dir($path)) list_recursive($path);
}
closedir($d);
}
}
// measured to 315% of gnu find's speed when run directly from a shell
function list_iterative($from) {
$dirs = array($from);
while (NULL !== ($dir = array_pop($dirs))) {
if ($dh = opendir($dir)) {
while (false !== ($entry = readdir($dh))) {
if ($entry == '.' || $entry == '..') continue;
$path = "$dir/$entry";
echo "$path\n";
if (is_dir($path)) $dirs[] = $path;
}
closedir($dh);
}
}
}
// measured to 315% of gnu find's speed when run directly from a shell
function list_recursivedirectoryiterator($path) {
$it = new RecursiveDirectoryIterator($path);
foreach ($it as $file) {
if ($file->isDot()) continue;
echo $file->getPathname();
}
}
// measured to 390% of gnu find's speed when run directly from a shell
function list_gnufind($dir) {
$dir = escapeshellcmd($dir);
$h = popen("/usr/bin/find $dir", "r");
while ('' != ($s = fread($h, 2048))) {
echo $s;
}
pclose($h);
}
``` | PHP just cannot perform as fast as C, plain and simple. | I'm not sure if the performance is better, but you could use a recursive directory iterator to make your code simpler... See `RecursiveDirectoryIterator` and ['SplFileInfo`](http://uk.php.net/SplFileInfo).
```
$it = new RecursiveDirectoryIterator($from);
foreach ($it as $file)
{
if ($file->isDot())
continue;
echo $file->getPathname();
}
``` | Is it possible to speed up a recursive file scan in PHP? | [
"",
"php",
"performance",
"recursion",
"find",
"iteration",
""
] |
I want to compress a folder using NTFS compression in .NET. I found [this post](http://bytes.com/groups/net-c/262874-making-folder-compressed), but it does not work. It throws an exception ("Invalid Parameter").
```
DirectoryInfo directoryInfo = new DirectoryInfo( destinationDir );
if( ( directoryInfo.Attributes & FileAttributes.Compressed ) != FileAttributes.Compressed )
{
string objPath = "Win32_Directory.Name=" + "\"" + destinationDir + "\"";
using( ManagementObject dir = new ManagementObject( objPath ) )
{
ManagementBaseObject outParams = dir.InvokeMethod( "Compress", null, null );
uint ret = (uint)( outParams.Properties["ReturnValue"].Value );
}
}
```
Anybody knows how to enable NTFS compression on a folder? | Using P/Invoke is, in my experience, usually easier than WMI. I believe the following should work:
```
private const int FSCTL_SET_COMPRESSION = 0x9C040;
private const short COMPRESSION_FORMAT_DEFAULT = 1;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int DeviceIoControl(
SafeFileHandle hDevice,
int dwIoControlCode,
ref short lpInBuffer,
int nInBufferSize,
IntPtr lpOutBuffer,
int nOutBufferSize,
ref int lpBytesReturned,
IntPtr lpOverlapped);
public static bool EnableCompression(SafeFileHandle handle)
{
int lpBytesReturned = 0;
short lpInBuffer = COMPRESSION_FORMAT_DEFAULT;
return DeviceIoControl(handle, FSCTL_SET_COMPRESSION,
ref lpInBuffer, sizeof(short), IntPtr.Zero, 0,
ref lpBytesReturned, IntPtr.Zero) != 0;
}
```
Since you're trying to set this on a directory, you will probably need to use P/Invoke to call [CreateFile](http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx) using `FILE_FLAG_BACKUP_SEMANTICS` to get the SafeFileHandle on the directory.
Also, note that setting compression on a directory in NTFS does not compress all the contents, it only makes new files show up as compressed (the same is true for encryption). If you want to compress the entire directory, you'll need to walk the entire directory and call DeviceIoControl on each file/folder. | I have tested the code and it [](https://i.stack.imgur.com/RzGkI.png)
(source: [typepad.com](https://codinghorror.typepad.com/.a/6a0120a85dcdae970b0128776ff992970c-pi))
!
* Make sure it works for you with the gui. Maybe the allocation unit size is too big for compression. Or you don't have sufficient permissions.
* For your destination use format like so: "c:/temp/testcomp" with forward slashes.
Full code:
```
using System.IO;
using System.Management;
class Program
{
static void Main(string[] args)
{
string destinationDir = "c:/temp/testcomp";
DirectoryInfo directoryInfo = new DirectoryInfo(destinationDir);
if ((directoryInfo.Attributes & FileAttributes.Compressed) != FileAttributes.Compressed)
{
string objPath = "Win32_Directory.Name=" + "'" + directoryInfo.FullName.Replace("\\", @"\\").TrimEnd('\\') + "'";
using (ManagementObject dir = new ManagementObject(objPath))
{
ManagementBaseObject outParams = dir.InvokeMethod("Compress", null, null);
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
}
}
}
}
``` | Compress a folder using NTFS compression in .NET | [
"",
"c#",
".net",
"windows",
"ntfs",
""
] |
Across various SQL dialects, what string representation for a Date and/or DateTime would be most likely to be interpreted correctly? Is there an SQL Standard? Are the two answers identical or similar?
EDIT:
For suggestions, can we all please comment with any known SQL dialects that don't comply? | I would bet the ISO 8601 date time standard would most likely be the one.
'YYYY-MM-DDThh:mm:ssTZD'
Or maybe a slight variation:
'YYYY-MM-DD hh:mm:ss'
<http://www.w3.org/TR/NOTE-datetime> | If you want to be portable across databases, maybe you should consider abstracting everything away using something like ADO or OTL. Pretty much all databases support ODBC connections, and you could just use something like OTL's datetime container to write and read dates. | Most portable SQL date string format | [
"",
"sql",
"datetime",
"date",
""
] |
Is there a shortcut of some kind in C# (VS 2008) to automatically implement the virtual and abstract base class methods in a derived class? | For virtual methods, you can type `override` and then a space. Intellisense should offer you a list of options.
For abstract methods and properties, you can use the smart tag on the base class or interface (also, `Ctrl`+`.` or `Shift`+`Alt`+`F10` will show the smart tag menu) to generate the concrete items.
For example, in the following code snippet, you could place the caret at the end of `INotifyPropertyChanged` and press `Ctrl`+`.` to then select Implement Interface, and the `PropertyChanged` event would be added to `MyClass`:
```
class MyClass : INotifyPropertyChanged
{
}
``` | Just type the Interface that you want to implement, and then click on the Smart Tag, a context menu will popup, and then you can select either Implement Interface or Implement Interface Explicitly:
> [](https://i.stack.imgur.com/MdCcY.png)
All the members to be overridden will be contained within a code region that is named to reflect its purpose.
All the members will have a line that throws a `NotImplementedException`. | Automatically generate implementations of base class methods | [
"",
"c#",
"visual-studio",
""
] |
My degree was in audio engineering, but I'm fairly new to programming. I'd like to learn how to work with audio in a programming environment, partly so I can learn C++ better through interesting projects.
First off, is C++ the right language for this? Is there any reason I shouldn't be using it? I've heard of Soundfile and some other libraries - what would you recommend?
Finally, does anyone know of any good tutorials in this subject? I've learnt the basics of DSP - I just want to program it!
EDIT: I use Windows. I'd like to play about with real-time stuff, a bit like Max/MSP but with more control. | It really depends on what kind of audio work you want to do, If you want to implement audio for a game, C++ is sure the right language. There are many libraries around, OpenAL is great, free and multiplatform. I also used DirectSound and Fmod with great sucess. Check them out, it all depends on your needs. | If you do decide to use C++, then [The Synthesis Toolkit](http://ccrma.stanford.edu/software/stk/) is worth noting. I use it for a schoolproject and it is very usable, developed at stanford university, crossplatform (win, mac and linux), free and opensource. An extract from the [wikipedia page](http://en.wikipedia.org/wiki/Synthesis_Toolkit) on it:
> Versions of the STK instrument classes
> have been integrated into ChucK,
> Csound, Real-Time Cmix, Max/MSP (as
> part of PeRColate) and SuperCollider
They have a lot of testcode included + on the site are some tutorials to get started with their library. (But you do have to know some C++ of course)
STK has some classed to read/write audio files (and matlab files), realtime audio/midi io, some basic algorithms (usage based on similar functions out of matlab), ...
---
Another *obvious* option and probably THE most used environment to learn/test dsp stuff is [Matlab](http://www.mathworks.com/) (or free [octave](http://www.gnu.org/software/octave/), but i havent used it before). I sometimes test stuff out in Matlab before implementing it in C++.
---
EDIT: In the past year I've been using [JUCE](http://www.juce.com/) which is a pretty cool C++ library centered around C++ audio programming, though its more leaning towards something like QT. One of their developers (Timur Doumler) has a nice talk about real time audio with C++ and JUCE on CppCon 2015, definitely worth checking out, even if you don't end up using JUCE: <https://youtu.be/boPEO2auJj4>
Another resource that might be interesting is the [audio section of the awesome cpp github readme](https://github.com/fffaraz/awesome-cpp#audio) which contains a number of libraries related to audio | Learning to work with audio in C++ | [
"",
"c++",
"audio",
""
] |
```
internal class Foo
{
public void Fee()
{
Debug.WriteLine("Fee");
}
internal void Fi()
{
Debug.WriteLine("Fi");
}
}
```
I'm thinking that Fee() and Fi() are equally accessible since the entire class is already internal. Am I overlooking something? Is there any reason to choose public or internal for the methods in a case like this? | The `internal class Foo` declaration will override the accessibility of the `public void Fee()` method, effectively making it internal.
In this case, using internal vs. public on the methods will have the same effect. The only reason I would choose public methods vs. internal methods in a case like this would be to ease transitioning to a public class in a future version, should you choose to do so. | The only thing missing here in the answer is why would you do this?
Some libraries have a lot of classes that are not meant for the consumer of the library to touch but they must inherit interfaces marked as public. For instance I have a library with a class that inherits the IComparer interface but it is only used internally and I don't want to clutter the public aspect of my library. If I mark the implemented Compare function as internal the compiler complains that I am not implmenting the interface IComparer.
So how do I successfully implement the interface and at the same time prevent it from being accessible in the public aspect of my library? Mark the class as internal but the implemented function as public. | public vs. internal methods on an internal class | [
"",
"c#",
"public-method",
""
] |
I have just written a program for importing data from an xml file to a database using dom4j. It endend up as a series of xpath statements wrapped in java, - and it works, but I strongly feel that there is a better way of doing this.
What is the preferred way to import data from xml into a db? | Depending on what kind of XML you have, [JAXB](http://java.sun.com/developer/technicalArticles/WebServices/jaxb/) (which is a standard part of Java SE since 1.6) might be the most straightforward way to deal with it. Just make a class similar to your XML structure, put in the setters and getters for the fields and a @XmlRootElement annotation to the top of the class. Then something like
```
Unmarshaller um = JAXBContext.newInstance(YourClass.class).createUnmarshaller();
YourClass input = (YourClass) um.unmarshal(new FileReader("file.xml"));
```
magically converts your XML file to a Java object. Then it should be easy to write to the DB of your choice. | I have found [Simple](http://simple.sourceforge.net/home.php) very easy to use for creating Java objects from XML. We use this to setup default configuration that we can then store using Hibernate. | What is the best way to import xml to a database (using java) | [
"",
"java",
"xml",
"database",
""
] |
Normally I have one controller and one model. Is there a disgn-pattern to have 1 View with multiple Controllers and multiple Models. Where very controller can have multiple models, too?
Some links to related patterns would be nice. | Generally a controller has only one model. However, you *could* create a composite model that itself has multiple models.
```
class CompositeModel
{
private ModelA modela;
private ModelB modelb;
}
```
And then have your Controller typed to that.
But if you don't know what you're doing ultimately that's a plan that'll only end in tears.
But if you can manage to avoid the God Model pattern it can be very powerful. | I would recommend studying MVC more in general. | MVC in C#: Model - Controller relationship | [
"",
"c#",
"model-view-controller",
"design-patterns",
""
] |
I have to do a demo of an application, the application has a server.jar and client.jar. Both have command line arguments and are executable. I need to launch two instances of server.jar and two instances of client.jar.
I thought that using a batch file was the way to go, but, the batch file executes the first command (i.e. >server.bat [argument1] [argument2]) and does not do anything else unless I close the first instance, in which case it then runs the 2nd command. And also the I do not want a blank console window to open (or be minimized)
What I really need is a batch script that will just launch these apps without any console windows and launch all instances that I need.
Thanks in Advance!
EDIT:
**javaw**:
> works if I type the command
> into the console window individually.
> If I put the same in the batch file,
> it will behave as before. Console
> window opens, one instance starts
> (whichever was first) and it does not
> proceed further unless I close the
> application in which case it runs the 2nd command. I want it to run all commands silently | Found the solution, below is the contents of my batch file
```
@echo off
start /B server.jar [arg1] [arg2]
start /B server.jar [arg3] [arg4]
start /B client.jar [arg5]
start /B client.jar [arg6]
@echo on
```
this opens, runs all the commands and closes the window, does not wait for the command to finish.
I am still not sure how to prevent the window from opening completely. | Try:
```
javaw <args>
``` | Launch .jar files with command line arguments (but with no console window) | [
"",
"java",
"batch-file",
""
] |
GWT is the main reason I'm moving into java for web development. Which java framework will work best with it, while also maximizing code reuse for mundane tasks like form validation, database access, pagination, etc?
Thanks. | I'm assuming you don't mean web framework since GWT is itself a framework. I would use JSF to handle the application/business logic side. It makes it easy to store and scope beans, and access the DB. For reading the DB, any JPA flavor you like. I've had good expierence with Eclipselink, but now they all implement the same interfaces. Also you might want to look at EJBs in order to throw everything together and inject the JPA you'll need. | Spring is the obvious one you should be using. GWT has its own RPC controller framework so I can't really think what you would need a Web application framework (like JSF) for.
JPA is a reasonable choice on several fronts but it has problems too.
For one thing, its potentially an issue sending JPA objects to the client. GWT (up to 1.5 at least) enforces a pretty strict directory structure so you'd have to put your entities under the GWT source tree. That aside, serializing (JSON usually) JPA entities to and from the client is potentially problematic.
JPA entities are fairly rigid objects that map almost one-to-one to your tables. That doesn't tend to be how you use data in a presentation layer however. Direct SQL will allow you to pick and choose which data you do and don't want, tailored specifically for that page. So JPA entities will typically have lots of fields you're not interested in and shouldn't serialize (particularly collections of one-to-many relationships).
Now that aspect of SQL--tailoring it to the page--is often cited as an advantage of entities: your code doesn't end up littered with one-use value objects. Thing is, you still end up with the same thing in gWT+JPA but instead of being in the persistence layer or the business layer you end up with them in the presentation layer. Now you might call that an advantage. I call it six of one, half a dozen of the other.
I actually think Ibatis is a far better fit to the GWT application model than JPA for the reason that you are using direct SQL, objects tailored for your purpose and those objects can be used all the way from the database to the client. Now this concept may horrify the layering zealots that are quite common in Java land but remember layering is a means to an end not an end in itself. Use it if it helps you. Don't if it doesn't.
But Spring is the absolute must in this stack.
I'll also refer you to [Why isn’t Google Web Toolkit more popular?](https://stackoverflow.com/questions/523728/why-isnt-google-web-toolkit-more-popular/523759#523759) and [Using an ORM or plain SQL?](https://stackoverflow.com/questions/494816/using-an-orm-or-plain-sql/494853#494853). | Which Java framework works best with Google Web Toolkit? | [
"",
"java",
"gwt",
"servlets",
""
] |
Alan Kay [points out](http://craphound.com/kayetcon2003) that "Unlike Java, [Squeak] runs bit-identical on every machine -- we invented this 20 years ago". The [wikipedia page](http://en.wikipedia.org/wiki/Squeak) mentions this also:
> Squeak is available for many
> platforms, and programs produced on
> one platform run bit-identical on all
> other platforms.
Since machines with different instruction sets obviously can't run bit-identical programs natively, what does it mean when one says that Squeak runs bit-identical programs on different machines, in a way that Java doesn't?
I'm under the impression that compiled Java classes runs identically on any machine on any JVM, is that not so? | The obvious interpretation is that executing the same image on different machines with the same inputs will result in the image evolving through the same bit patterns. [This post about Squeak's floating point math](http://www.nabble.com/FloatMathPlugin-for-Croquet-td3603085.html) implies that the floating point has identical representation on different platforms. Java requires that semantics are the same between platforms, but permits denormalised representations. The library Squeak uses to ensure bit-identical floating point across platform is Sun's one, which the Sun JVM also uses, though they mention further restricting it with compiler settings. | The term bit-identical can not only refer to no native code, but also refer to how data operations are handled. From platform to platform there are subtile difference, for example in the least significant digits of floating point numbers due to diffrent hardware implementations of the floating point unit.
So bit-identical could also mean that such diffrences are removed and every single instruction returns bit by bit the same result on every hardware. Ad hoc this prohibts the usage of some hardware and would require emulation. I am not sure if thi is feasible at acceptable costs or if there is a good trick to achiev this. | What does it mean that Squeak runs "bit-identically" across platforms, in a way Java doesn't? | [
"",
"java",
"jvm",
"smalltalk",
"vm-implementation",
""
] |
OK, please disregard what has gone before. I'm not getting the errors anymore, so it seems my problem is with getting a Chart to update when I change the values to which the Chart is data bound.
//Disregard below here
Hi all. I have a WinForms application that has a panel, `panel1`. A background thread creates some other controls that then get added to `panel1` like so
```
panel1.Controls.AddRange(myArrayOfControls);
```
This works great and I can see my controls get added. But, when new data comes in on another thread, I update values in the controls' parent objects and then need to `Refresh()` to get the display to update with the new values. Calling `Refresh()` in either context, the thread where the data comes in or the objects that receive the updated data causes an InvalidOperation exception because Invoke is required. I've tried using Invoke in my model objects and also the thread where the data is incoming and can't seem to shake the error.
If anyone has some guidance I'd greatly appreciate it.
UPDATE: Here's a little more info. I didn't think it would require it, but I was wrong. :)
I have an object class MyObject. This MyObject class gets created in a thread called topologyThread. Data comes in on dataThread. Instances of MyObject have a Panel instance variable and the Panel has child Controls including two Charts from the System.Windows.Forms.DataVisualization.Charting namespace. So, as data comes in on dataThread, I update the respective data values in the MyObject objects and then need to refresh the Charts to show the updated data.
I do know the data is processing fine. In my MyObject class, I'm logging the new values to Console in the setter for the property and see the new values show up. | You must do both operations (refresh and updating of control's parent object) from the main UI thread. If you are modifying a control from a background thread and not getting an exception that is bad luck because it is definitely an error.
The best way to do this is to use
```
theControl.Invoke(new MethodInvoker(MyUpdateMethod));
```
If you have a sample of how the update is done, we can give a better sample on how to properly call it from the background thread. | JaredPar is a pretty good answer. I would like to add to it a bit as to the reason your code sort of works.
With windows forms you can talk to the UI thread from other threads. This is really bad practice in all cases.
The catch is that when you do it, it is hard to catch because sometimes the UI will work as if nothing is wrong. item will get added or changed and the UI will reflect the changes. However other times running the same exact code, it will not work.
That is the catch with touching the UI from any thread other then the UI thread. The out come is inconsistent and that is why is very bad practice.
God I wish I could comment. :) | Control.Refresh() Across Threads | [
"",
"c#",
".net",
"multithreading",
"controls",
""
] |
I'm trying to parse a [GPX file](http://en.wikipedia.org/wiki/GPS_eXchange_Format). I tried it with JDOM, but it does not work very well.
```
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(filename);
Element root = document.getRootElement();
System.out.println("Root:\t" + root.getName());
List<Element> listTrks = root.getChildren("trk");
System.out.println("Count trk:\t" + listTrks.size());
for (Element tmpTrk : listTrks) {
List<Element> listTrkpts = tmpTrk.getChildren("trkpt");
System.out.println("Count pts:\t" + listTrkpts.size());
for (Element tmpTrkpt : listTrkpts) {
System.out.println(tmpTrkpt.getAttributeValue("lat") + ":" + tmpTrkpt.getAttributeValue("lat"));
}
}
```
I opened the [example file](http://openstreetmap.org/trace/339421/data) (CC-BY-SA [OpenStreetMap)](http://www.openstreetmap.org) and the output is just:
> Root: gpx
> Count trk: 0
What can I do? Should I us a SAXParserFactory (`javax.xml.parsers.SAXParserFactory`) and implement a Handler class? | Here is my gpx reader. It ignores some of the tags but I hope it will help.
```
package ch.perry.rando.geocode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author perrym
*/
public class GpxReader extends DefaultHandler {
private static final DateFormat TIME_FORMAT
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private List<Trackpoint> track = new ArrayList<Trackpoint>();
private StringBuffer buf = new StringBuffer();
private double lat;
private double lon;
private double ele;
private Date time;
public static Trackpoint[] readTrack(InputStream in) throws IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
GpxReader reader = new GpxReader();
parser.parse(in, reader);
return reader.getTrack();
} catch (ParserConfigurationException e) {
throw new IOException(e.getMessage());
} catch (SAXException e) {
throw new IOException(e.getMessage());
}
}
public static Trackpoint[] readTrack(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
return readTrack(in);
} finally {
in.close();
}
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
buf.setLength(0);
if (qName.equals("trkpt")) {
lat = Double.parseDouble(attributes.getValue("lat"));
lon = Double.parseDouble(attributes.getValue("lon"));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("trkpt")) {
track.add(Trackpoint.fromWGS84(lat, lon, ele, time));
} else if (qName.equals("ele")) {
ele = Double.parseDouble(buf.toString());
} else if (qName.equals("")) {
try {
time = TIME_FORMAT.parse(buf.toString());
} catch (ParseException e) {
throw new SAXException("Invalid time " + buf.toString());
}
}
}
@Override
public void characters(char[] chars, int start, int length)
throws SAXException {
buf.append(chars, start, length);
}
private Trackpoint[] getTrack() {
return track.toArray(new Trackpoint[track.size()]);
}
}
``` | To read GPX files easily in Java see: <http://sourceforge.net/p/gpsanalysis/wiki/Home/>
example:
//gets points from a GPX file
final List points= GpxFileDataAccess.getPoints(new File("/path/toGpxFile.gpx")); | How to parse GPX files with SAXReader? | [
"",
"java",
"xml",
"gpx",
""
] |
*Links to articles would also be appreciated--I don't know the terminology to search for.*
I'm looking to learn how a web application can allow for server-to-client communications. I know the web was not designed for this and that it has been something of a hurdle, and am just wondering what the state of this is, and what the best practices are.
An alternative is constant or occasional polling via ajax, but is it possible for web servers to maintain stateful connections to a web client?
**Edit:** Another way to ask this question is how does StackOverflow tell a page that new posts are available for it to display that little bar at the top? | StackOverflow polls the server to check if there is more data.
What you're looking for is [Comet](http://en.wikipedia.org/wiki/Comet_(programming)). | To get true two way communications from a browser you need to use a plugin technology like Silverlight, Flash, et al. Those plugins can create TCP connections that can establish a two way persistent connection with a server socket. Note that you can't really establish the TCP connection with the HTTP server so you'd have to create an additional server agent to do the communicating back to the browser.
Basically it's a completely differnet deployment model to what AJAX sites like Stackoverflow, Gmail etc. use. They all rely on the browser polling the server at set intervals. | What's the best way for the server to send messages to a web client? | [
"",
"asp.net",
"javascript",
"asp.net-mvc",
"ajax",
"web-applications",
""
] |
I want to be able to show a dialog on outbound calls.
The dialog is used to ask the user if he wants
1. dial the phone number directly
2. Dial through the PBX.
If option two is chosen, i want to dial a specific number and send the dialed number as DTMF.
1. How do I catch and stop outgoing calls?
2. How do I get the dialed number? | It can be done through TAPI. I'm hiring a person through elance.com to do it. | Firstly (and possibly a little off topic) there is actually a built-in WM6 feature for allowing calls to be routed either over the cell network or over SIP using the built-in dialer. If SIP calling (or "Internet Calling" as the UI has it) is enabled and there is a WiFi connection the call will be routed over SIP, if not it will route over GSM in the normal way. There is actually also a registry setting that enables the calls to routed over SIP if there is a 3G/HSDPA connection available too.
Most manufacturers do not ship the part of the WM6 OS that enables this functionality on their device ROMs (presumably mindful of their call revenue), however it can easily be installed on most WM6 devices.
Secondly if this is not what you are after (if you don't want to use SIP but use a calling card or need to have the choice after you place the call) I can tell you it must be possible to do what you want to do because this app does it - [magicall](http://www.mobiion.com/magicall-screenshots.html). One way I can think of doing this is to get notification of the call, immedialety end it, wipe it from the log, put up your PBX or Cell dialog, and then place the call again in the way the user requested. This has the disadvantage that if the original call was started programmatically the app that did so will think the call was ended prematurely. It may also be possible using another technique, but that is where my knowledge runs out... | Show dialog on outbound calls | [
"",
"c#",
"windows-mobile",
""
] |
I've been working on getting this program complete where it saves multiple structs to a file, can read them back and edit them, then save them all back to a file. I've been working on the logic of this not to mention lots of help from others and a ton of googling hours... now I am getting a compile error. Any help would be very appreciated.
**Code:**
```
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
struct InventoryItem {
string Item;
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
int dateAdded;
} ;
int main(void)
{
vector<InventoryItem> structList;
ofstream out("data.dat");
writeVector( out, structList );
return 0;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i; // error C2679
}
}
```
**Compiler error:**
```
1>.\Project 5.cpp(128) : error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const InventoryItem' (or there is no acceptable conversion)
// listed overload variants skipped
1> while trying to match the argument list '(std::ofstream, const InventoryItem)'
1> .\Project 5.cpp(46) : see reference to function template instantiation 'void writeVector<InventoryItem>(std::ofstream &,const std::vector<_Ty> &)' being compiled
1> with
1> [
1> _Ty=InventoryItem
1> ]
``` | You have no `operator<<` defined that would specify how your `InventoryItem` should be printed to an output stream. You try to print it and the compiler doesn't know how. You need to define a function like this one:
```
std::ostream& operator<<(std::ostream &strm, const InventoryItem &i) {
return strm << i.Item << " (" << i.Description << ")";
}
``` | You're trying to use the `<<` operator for your struct, but that operator isn't defined for that type. Try outputting specific data members instead. | Compiler error with `<<` | [
"",
"c++",
"serialization",
"struct",
"compiler-errors",
""
] |
Suppose I want something of this sort, in one `.cpp` source file:
```
class A {
public:
void doSomething(B *b) {};
};
class B {
public:
void doSomething(A *a) {};
};
```
Is there anyway of doing this without splitting it into two separate files, and without receiving a compiler error (syntax error on `doSomething(B *b)`) | put at the first line:
```
class B;
``` | If I remember well, you can 'pre-declare' your class B.
```
class B; // predeclaration of class B
class A
{
public:
void doSomething(B* b);
}
class B
{
public
void doSomething(A* a) {}
}
public void A::doSomething(B* b) {}
```
Then, your class 'A' knows that a class 'B' will exists, although it hasn't been really defined yet.
Forward declaration is indeed the correct term, as mentionned by Evan Teran in the comments. | C++ - 2 classes 1 file | [
"",
"c++",
""
] |
how can i command to run file.exe file from another computer in my domain with C#
I know System.Diagnostic.Process.Start but its starting in my computer.
How can i use it for "192.168.100.2" ip addressed computer for running an exe file from my comp with a command? I know TCP/Socket programming but else ? | [PsExec](http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx), a part of [PsTools](http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx), can do this for you. | If you don't need a UI for the .exe you can use WMI to start a process remotely. I haven't got code to do it here but [this codeproject article](http://www.codeproject.com/KB/cs/Remote_Process_using_WMI_.aspx) looks like it would work. | How to run some exe file from another computer in a domain C# | [
"",
"c#",
""
] |
I know that this question has been asked before, but I'm looking for a way to:
1. streamline the creation of safe cross-threaded code.
2. reuse this code in any situation (no Windows Forms references).
Here's what I have so far, but I want to remove the Windows Forms references. Any ideas?
```
public delegate void SafeInvokeDelegate(System.Action action);
public class SafeInvoke
{
private readonly System.Windows.Forms.Control _threadControl;
public SafeInvoke()
{
_threadControl = new System.Windows.Forms.Control();
}
public void Invoke(System.Action action)
{
if (_threadControl.InvokeRequired)
_threadControl.Invoke(new SafeInvokeDelegate(Invoke), new object[] {action});
else if (action != null) action();
}
}
```
The above class might be used this way:
```
SafeInvoke _safeInvoker = new SafeInvoke();
void SafeClearItems()
{
_safeInvoker.Invoke(delegate
{
listView1.Items.Clear();
});
}
```
How would I remove the System.Windows.Forms.Control in the SafeInvoke class but keep the same functionality? | You also could use an extension method and lambdas to make your code much cleaner.
```
using System.ComponentModel;
public static class ISynchronizeInvokeExtensions
{
public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
{
if (@this.InvokeRequired)
{
@this.Invoke(action, new object[] { @this });
}
else
{
action(@this);
}
}
}
```
So now you can use `InvokeEx` on any ISynchronizeInvoke and be able to access the properties and fields of implementing class.
```
this.InvokeEx(f => f.listView1.Items.Clear());
``` | Use [`ISynchronizeInvoke`](http://msdn.microsoft.com/en-us/library/system.componentmodel.isynchronizeinvoke.aspx) instead of `Control`. That's the interface that `Control` implements with `Invoke/BeginInvoke/EndInvoke/InvokeRequired`.
An alternative is to use [`SynchronizationContext.Current`](http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.current.aspx) - which is what `BackgroundWorker` uses, I believe. | Best Way to Invoke Any Cross-Threaded Code? | [
"",
"c#",
".net",
"invoke",
""
] |
I have a Java app that runs on linux that has a lots of events and business logic that revolve around times and dates.
For testing, is it possible to tweak something into time going faster. Let's say, make a whole computer-year finish in one hour wall time? | You can write a wrapper interface for your time/date calls. Have one real implementation that does real system calls, and a test implementation that can do whatever you want (run faster, slower, fake dates, etc). | One approach that works best for unit testing is to abstract the way the current time is accessed in your code.
Instead of calling System.currentTimeMillis() directly you can provide your own implementation.
Something like this (pseudo-code):
```
class MyTime {
private static TimeInterface CurrentTimeInterface = new DefaultTimeImpl();
public setTimeInterface(TimeInterface timeInterface) {
CurrentTimeInterface = timeInterface;
}
public int getTime() { CurrentTimeInterface.getTime(); }
}
class DefaultTimeImpl implements TimeInterface {
public int getTime() { return System.currentTimeMillis(); }
}
class TestTimeImpl implements TimeInterface {
private int CurrentTimeMillis = 0;
public int getTime() { return CurrentTimeMillis; }
public void setTime(int timeMillis) { CurrentTimeMillis = timeMillis}
public void sleep(int millis) { CurrentTimeMillis += millis; }
}
```
Then, everywhere you would have called System.getTimeMillis() instead call MyTime.getTime(). When you're testing your code simply create a TestTimeImpl and call MyTime.setTimeInterface(testTimeImpl). Then when you want time to advance call testTimeImpl.sleep() or testTimeImpl.setTime().
This allows you to simulate any time down to the millisecond. | Simulating "faster time" in linux | [
"",
"java",
"linux",
"testing",
"date",
"time",
""
] |
Is there a way to create a second console to output to in .NET when writing a console application? | Well, you could start a new cmd.exe process and use stdio and stdout to send and recieve data.
```
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe")
{
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false
};
Process p = Process.Start(psi);
StreamWriter sw = p.StandardInput;
StreamReader sr = p.StandardOutput;
sw.WriteLine("Hello world!");
sr.Close();
```
More info on [MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardinput(vs.71).aspx). | The following fires off an application-dependent number of console windows and stores the amount and parameters for the console inside a String Dictionary that is then looped to generate the required amount of spawned console apps. You would only need the process stuff if only spawning one of course.
```
//Start looping dic recs and firing console
foreach (DictionaryEntry tests in steps)
{
try
{
Process runCmd = new Process();
runCmd.StartInfo.FileName = CONSOLE_NAME;
runCmd.StartInfo.UseShellExecute = true;
runCmd.StartInfo.RedirectStandardOutput = false;
runCmd.StartInfo.Arguments = tests.Value.ToString();
if (cbShowConsole.Checked)
{
runCmd.StartInfo.CreateNoWindow = true;
runCmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
}
else
{
runCmd.StartInfo.CreateNoWindow = false;
runCmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
runCmd.Start();
}
catch (Exception ex)
{
string t1 = ex.Message;
}
}
```
Note this is intended either to run hidden (CreateNoWindow) or visible. | Is there a way to create a second console to output to in .NET when writing a console application? | [
"",
"c#",
".net",
"console",
""
] |
I have a page with a dropdown. The `onchange` event calls a Javascript function (below) that includes an Ajax block that retrieves data and populates a `TEXTAREA`. On the surface, everything works.
I can select any item in the list with no problems. However, if I select an item that has previously been selected, the Ajax call appears to hang. It looks like maybe some weird caching issue or something. If I close the browser and reload the page, all items work again until I re-select.
I've tested for the `readyState` and `status` properties when it's hanging, but I get nothing. Am I missing something?
The page is a client project behind authentication so I can't post a URL, but here's the Ajax code. This is in a PHP page, but there's no PHP script related to this.
```
function getText( id ) {
var txt = document.getElementById( "MyText" );
txt.disabled = "disabled";
txt.innerText = "";
txt.className = "busy";
var oRequest = zXmlHttp.createRequest();
oRequest.open( "get", "get_text.php?id=" + id, true );
oRequest.send( null );
oRequest.onreadystatechange = function() {
if( oRequest.readyState == 4 ) {
if( oRequest.status == 200 ) {
txt.innerText = oRequest.responseText;
} else {
txt.innerText = oRequest.status + ": " + oRequest.statusText;
}
txt.disabled = "";
txt.className = "";
oRequest = null;
}
}}
```
*Edit:* The code block seems a little quirky; it won't let me include the final `}` unless it's on the same line as the previous. | You're setting the `onreadystatechange` function *after* you're sending the request. If it takes a long time (ie if it goes to the server), this will probably work, since there will be a delay before it tries to call the callback.
If the page is cached, though, the browser is probably trying to call `onreadystatechange` immediately in the `send` method. Move your assignment to `onreadystatechange` to before the `open/send` code. | HI,
The caching is due to the same url thats being called repeatedly. If you change the URl dynamically then this issue can be rsolved. Something like by adding a querystring with the current time with the request ( or any random renerated number ) you can change the url without affecting the result | Ajax call not responding on repeated request | [
"",
"javascript",
"ajax",
""
] |
When I first typed this question, I did so in order to find the duplicate questions, feeling sure that someone must have already asked this question. My plan was to follow those dupe links instead of posting this question. But this question has not been asked before as far as I can see ... it did not turn up in the "Related Questions" list.
**What are some of the best resources you've found (articles, books, blog posts, etc.) for gaining an in-depth understanding of Expression Trees in C#?** I keep getting surprised by their capabilities, and now I'm at the point where I'm saying, "OK, enough surprise. I want to stop right now and get a PhD in these things." I'm looking for material that systematically, methodically covers the capabilities and then walks through detailed examples of what you can do with them.
Note: I'm not talking about lambda expressions. I'm talking about Expression< T > and all the things that go with it and arise from it.
Thanks. | Chapter 11 (Inside Expression Trees) and chapter 12 (Extending Linq) of Programming Microsoft Linq (ISBN 13: 978-0-7356-2400-9 or ISBN 10: 0-7356-2400-3) has been invaluable for me. I haven't read Jons book, but he is a quality guy and explains things well, so I assume that his coverage would also be good.
Another great resource is [Bart De Smet's blog](http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx)
Also, keep your eye on MSDN, the sample code for building a [Simple Linq to Database](http://code.msdn.microsoft.com/SimpleLingToDatabase/Release/ProjectReleases.aspx?ReleaseId=1471) (by Pedram Rezaei) is about to get about 40 pages of Doco explaining it.
A really, really useful resource for Expression Tree's in fact I would regard it as a *must have* is the [Expression Tree Visualiser](http://msdn.microsoft.com/en-us/library/bb397975.aspx) debugging tool.
You should also learn as much as you can about Expression Tree Visitors, there is a pretty good base class inplementation [here](http://msdn.microsoft.com/en-us/library/bb882521.aspx).
Here is some sample code derived from that Visitor class to do some debugging (I based this on some sample code in the book I mentioned) the prependIndent method call is just an extension method on a string to put a "--" at each indent level.
```
internal class DebugDisplayTree : ExpressionVisitor
{
private int indentLevel = 0;
protected override System.Linq.Expressions.Expression Visit(Expression exp)
{
if (exp != null)
{
Trace.WriteLine(string.Format("{0} : {1} ", exp.NodeType, exp.GetType().ToString()).PrependIndent(indentLevel));
}
indentLevel++;
Expression result = base.Visit(exp);
indentLevel--;
return result;
}
...
``` | I don't claim them to be comprehensive, but I have a number of `Expression` posts [on my blog](http://marcgravell.blogspot.com/search/label/expression). If you are UK based, I will also be presenting a session on `Expression` at [DDD South West](http://dddsouthwest.com/) in May (and [last night](http://www.gl-net.org.uk/Events/GLnet_March.aspx), but too late ;-p). I could post the slide deck and some of the links from related articles, if you want... unfortunately, a pptx intended to be *spoken* rarely makes sensible standalone reading.
Some other reading (not from the blog):
* Jason Bock: [genetic programming](http://www.jasonbock.net/JB/Default.aspx?blog=entry.b2ff6b7e47ae41929e38beec4093518e) with `Expression`
* (me again): [generic operators](http://www.yoda.arachsys.com/csharp/genericoperators.html) with `Expression`
* (and again, on InfoQ) [`Expression` as a Compiler](http://www.infoq.com/articles/expression-compiler)
(and a whole load of posts here and on microsoft.public.dotnet.languages.csharp
- try searching for: +expression -regex -"regular expression" | What is the best resource for learning C# expression trees in depth? | [
"",
"c#",
"c#-3.0",
"lambda",
"expression-trees",
""
] |
I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.
I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.
I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.
I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.
One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?
Any clearly laid out information would be very helpful! | Three suggestions:
1. **Use one dictionary.**
It's easier, it's more straightforward, and someone else has already optimized this problem for you. Until you've actually measured your code and traced a performance problem to this part of it, you have no reason not to do the simple, straightforward thing.
2. **Optimize later.**
If you are *really* worried about performance, then abstract the problem make a class to wrap whatever lookup mechanism you end up using and write your code to use this class. You can change the implementation later if you find you need some other data structure for greater performance.
3. **Read up on hash tables.**
Dictionaries are [hash tables](http://en.wikipedia.org/wiki/Hash_table), and if you are worried about their time or space overhead, you should read up on how they're implemented. This is basic computer science. The short of it is that hash tables are:
* average case **O(1)** lookup time
* **O(n)** space (Expect about **2n**, depending on various parameters)
I do not know where you read that they were **O(n^2)** space, but if they were, then they would not be in widespread, practical use as they are in most languages today. There are two advantages to these nice properties of hash tables:
1. **O(1)** lookup time implies that you will not pay a cost in lookup time for having a larger dictionary, as lookup time doesn't depend on size.
2. **O(n)** space implies that you don't gain much of anything from breaking your dictionary up into smaller pieces. Space scales linearly with number of elements, so lots of small dictionaries will not take up significantly less space than one large one or vice versa. This would not be true if they were **O(n^2)** space, but lucky for you, they're not.
Here are some more resources that might help:
* The [Wikipedia article on Hash Tables](http://en.wikipedia.org/wiki/Hash_table) gives a great listing of the various lookup and allocation schemes used in hashtables.
* The [GNU Scheme documentation](http://www.gnu.org/software/mit-scheme/documentation/mit-scheme-ref/Resizing-of-Hash-Tables.html) has a nice discussion of how much space you can expect hashtables to take up, including a formal discussion of why *"the amount of space used by the hash table is proportional to the number of associations in the table"*. This might interest you.
Here are some things you might consider if you find you actually need to optimize your dictionary implementation:
* Here is the C source code for Python's dictionaries, in case you want ALL the details. There's copious documentation in here:
+ [dictobject.h](http://svn.python.org/view/python/trunk/Include/dictobject.h?revision=59564&view=markup)
+ [dictobject.c](http://svn.python.org/view/python/trunk/Objects/dictobject.c?revision=68128&view=markup)
* Here is a [python implementation](http://pybites.blogspot.com/2008/10/pure-python-dictionary-implementation.html) of that, in case you don't like reading C.
(Thanks to [Ben Peterson](https://stackoverflow.com/users/33795/benjamin-peterson))
* The [Java Hashtable class docs](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Hashtable.html) talk a bit about how load factors work, and how they affect the space your hash takes up. Note there's a tradeoff between your load factor and how frequently you need to *rehash*. Rehashes can be costly. | If you're using Python, you really shouldn't be worrying about this sort of thing in the first place. Just build your data structure the way it best suits *your* needs, not the computer's.
This smacks of premature optimization, not performance improvement. Profile your code if something is actually bottlenecking, but until then, just let Python do what it does and focus on the actual programming task, and not the underlying mechanics. | Memory efficiency: One large dictionary or a dictionary of smaller dictionaries? | [
"",
"python",
"memory",
"dictionary",
"performance",
""
] |
I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it?
Edit: I think I've found the problem. My character data contains "<" and ">" characters, presumably from html tags. After being parsed, these are converted to "<" and ">" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening? | Does the sax parser not give you details about *where* it thinks it's not well-formed?
Have you tried loading the file into an XML editor and checking it there? Do other XML parsers accept it?
The schema shouldn't change whether or not the XML is well-formed or not; it may well change whether it's *valid* or not. See the [wikipedia entry for XML well-formedness](http://en.wikipedia.org/wiki/Well-formed_XML_document) for a little bit more, or the [XML specs](http://www.w3.org/XML/Core/#Publications) for a lot more detail :)
EDIT: To represent "&" in text, you should escape it as `&`
So:
```
<
```
should be
```
&lt
```
(assuming you really want ampersand, l, t). | I would suggest putting those tags back in and making sure it still works. Then, if you want to take them out, do it one at a time until it breaks.
However, I question the wisdom of taking them out. If it's your XML file, you should understand it better. If it's a third-party XML file, you really shouldn't be fiddling with it (until you understand it better :-). | Python SAX parser says XML file is not well-formed | [
"",
"python",
"xml",
"sax",
""
] |
i feel like im trying to do something super simple, but just being stupid about it.
all i want to do is see if a variable has been set previously, and if it has NOT, set it with a default value....here is a sample:
```
if(!embed_BackgroundColor) {
var embed_BackgroundColor;
embed_BackgroundColor = "#F4F4F4";
}
```
so, once you stop laughing at my code....WHY is it overwriting the variable no matter what?
please save my nerves;) | ```
if (typeof variable === 'undefined') {
// variable is undefined
// eg:
// var variable = "someValue";
}
``` | Pro style:
```
var SomeVar = SomeVar || 'Default Value';
``` | javascript: define a variable if it doesn't exist | [
"",
"javascript",
"variables",
""
] |
So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like `vector.insert(pos, first, last)` is the function I want... except I only have first and last as ints. Is there any nice way I can get an iterator to these values? | Try this:
```
vector<Type>::iterator nth = v.begin() + index;
``` | way mentioned by @dirkgently `( v.begin() + index )` nice and fast for vectors
but [`std::advance`](http://en.cppreference.com/w/cpp/iterator/advance)`( v.begin(), index )` most generic way and for random access iterators works constant time too.
**EDIT**
differences in usage:
```
std::vector<>::iterator it = ( v.begin() + index );
```
or
```
std::vector<>::iterator it = v.begin();
std::advance( it, index );
```
added after @litb notes. | C++ STL Vectors: Get iterator from index? | [
"",
"c++",
"stl",
"vector",
"iterator",
""
] |
I am trying to implement GZip compression for my asp.net page (including my CSS and JS files). I tried the following code, but it only compresses my .aspx page (found it from [YSlow](http://developer.yahoo.com/yslow/))
```
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
```
The above code is only compressing my .aspx page code (markup) not the CSS and JS files which is included as external files.
Please tell me how can I implement GZip compression in ASP.NET using code (because I am on shared hosting server where I don't have access to IIS Server configurations). And also in the above code I am not getting the last two lines, why they are used and what's the purpose of these lines. Please explain! | For compressing JS & CSS files you actually have to handle that at the IIS level, since these files are rendered directly without the ASP.NET runtime.
You could make a JSX & CSSX extension mapping in IIS to the aspnet\_isapi.dll and then take advantage of your zip code, but IIS is likely to do a better job of this for you.
The content-encoding header tells the browser that it needs to unzip the content before rendering. Some browsers are smart enough to figure this out anyway, based on the shape of the content, but it's better to just tell it.
The Accept-encoding cache setting is there so that a cached version of the gzipped content won't be sent to a browser that requested only text/html. | Here is the solution for css and javascript files. Add the following code to <system.webServer> inside your web.config file:
```
<configuration>
...
<system.webserver>
...
<httpCompression>
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
...
</system.webserver>
...
<configuration>
```
Credit: [How to GZip on ASP.NET and GoDaddy](http://web.archive.org/web/20121224102802/http://jeeshenlee.wordpress.com/2010/08/01/how-to-gzip-on-asp-net-and-godaddy) | How to implement GZip compression in ASP.NET? | [
"",
"c#",
"asp.net",
"compression",
"gzip",
""
] |
ok...in php how do i do this? given the following scenario:
```
// array of letters
var $letters = array('a', 'b', 'c');
// loop through array and create empty arrays with names like $a, $b, $c
foreach($letters as $letter) {
var $$letter = array();
}
``` | Your code was almost correct. You just need to remove 'var' on the 2nd and fifth lines.
```
// array of letters
$letters = array('a', 'b', 'c');
// loop through array and create empty arrays with names like $a, $b, $c
foreach($letters as $letter) {
$$letter = array();
}
```
This works correctly (as you described). I tested it.
More [information on variable variables here](http://au.php.net/language.variables.variable).
*As an aside, I would recommend against using eval() in your PHP.* | You probably don't want to do this. Wanting to use variable variables is usually a sign of a failure to understand data structures and/or excessive cleverness. If you really want to do this, you could say something like...
```
extract(array_fill_keys($letters, array()));
```
...but it would be best if you didn't. Using nested arrays is probably a much better idea - especially since you can just say `$nested['a'][] = 5` and PHP will append the value to the array, creating one if nothing is there. Alternately, you could just say `$varname['key'] = 123` and, again, PHP will auto-create the array for you. | how do i create a variable from another variable name? | [
"",
"php",
"variables",
"loops",
""
] |
I have an *unmanaged class* that I'm trying to dllexport from a *managed* DLL file. I'm trying to use the unmanaged class in another *managed* DLL file. However, when I try to do this I get *link* errors.
I've done this lots of times with unmanaged DLL files, so I know how that works. I know how to use "public ref", etc. in managed classes.
Is there some flag somewhere I need to set? Or do I have to do some DllImport magic?
This is on .NET 2.0 and [Visual Studio 2005](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005). | You need to use an interop assembly for unmanaged libraries or COM components. Here is [a link](http://www32.brinkster.com/srisamp/netArticles/article_16.htm) with good information regarding this. | If you want to use an unmanaged class from managed code, you can:
1. Use some nasty [P/Invoke](http://en.wikipedia.org/wiki/Platform_Invocation_Services) to load the class member functions (constructor, destructor, etc.) and make a nastier managed wrapper class to call the "real" member functions. This gets even worse when there are virtual methods involved.
2. The second option (which in my opinion is better) is to write a [C++/CLI](http://en.wikipedia.org/wiki/C++/CLI) wrapper class (you mentioned that you're familiar with this) that is a simple proxy to the unmanaged class. For every member function you have in the unmanaged class you'll have a similar one in your proxy class. Then it's a simple case of adding a reference to that DLL from your managed project, and you'll be able to use your class as any other .NET class. Take into consideration that you'll run into more work if your class exposes other unmanaged stuff (those that can't be marshalled).
If you need more information on the second option, I could look up some old links that explained this technique more. | How do I use an unmanaged class from a managed DLL in .NET? | [
"",
"c++",
"dll",
"unmanaged",
"dllimport",
""
] |
I'm trying to design a Form class in PHP. So far, I have the `<input>` buttons pretty well working. But the `<select>` boxes have me stymied. I'm trying to figure out a "generic" way of adding the `<option>` tags, and am lacking the creativity.
I'm not asking for teh codez, but implementation ideas are welcome. | This is my implementation of it from my bare-bones framework that I use in super simple projects:
```
function select($name, $options = array(), $attrs = array(), $showEmpty = false) {
$attrs['name'] = $name;
$attrs['class'] = isset($attrs['class']) ? $attrs['class'] . ' input' : 'input';
if(isset($this->validation->invalid[$name])) {
$attrs['class'] .= ' errorinput';
}
$opts = array();
foreach($attrs as $key => $value) {
$opts[] = $key . '="' . $value . '"';
}
$htmloptions = array();
$hasSelected = false;
foreach($options as $option => $value) {
if(isset($this->validation->post[$name]) && $this->validation->post[$name] == $option) {
$hasSelected = true;
$htmloptions[] = '<option value="' . $option . '" selected>' . $value;
} else {
$htmloptions[] = '<option value="' . $option . '">' . $value;
}
}
if($showEmpty) {
$emptyoption = '<option value=""' . (($hasSelected) ? '' : ' selected') . '>';
$htmloptions = array_merge($emptyoption, $htmloptions);
}
return '<select ' . implode(' ', $opts) . '>' . implode("\n", $htmloptions) . '</select>';
}
``` | Heres some function I made some while ago.
```
function formLabel($id, $text, $attr = array(), $escape = true) {
$attr['for'] = $id;
return htmlElement('label', $text, $attr, true, $escape);
}
function formSelect($name, $selected, $options, $attr = array(), $escape = true) {
$attr['name'] = $name;
if (!isset($attr['id'])) {
$attr['id'] = $name;
}
$options = formSelectOptions($selected, $options, $escape);
return htmlElement('select', $options, $attr, true, false);
}
function formSelectOptions($selected = null, $options, $escape = true) {
if ($escape) {
$options = escape($options);
}
array_walk($options, 'formSelectOption', $selected);
return implode('', $options);
}
function formSelectOption(&$value, $key, $selected) {
if (is_array($value)) {
$attr['label'] = $key;
array_walk($value, 'formSelectOption', $selected);
$value = htmlElement('optgroup', implode('', $value), $attr, true, false);
} else {
$attr['value'] = $key;
if (($selected == $key) &&
(0 === strcmp($selected, $key)) &&
($selected !== null)) {
$attr['selected'] = 'selected';
}
$value = htmlElement('option', $value, $attr, true, false);
}
}
function escape($val) {
if (is_array($val)) {
return array_map('escape', $val);
}
return htmlspecialchars($val, ENT_QUOTES);
}
function htmlElement($tag, $value, $attr = null, $end = true, $escape = true) {
if (!is_array($attr)) {
$attr = array();
}
if ($escape) {
$value = htmlspecialchars($value);
}
return "<$tag" . (!empty($attr) ? ' ' : '') . arrayToAttributes($attr) . ($end ? '' : '/') . '>' . $value . ($end ? "</$tag>" : '');
}
function arrayToAttributes($attr) {
array_walk($attr, '_arrayToAttributes');
return implode(' ', $attr);
}
function _arrayToAttributes(&$v, $k) {
$k = escape($k);
$t = escape($v);
$v = "$k=\"$t\"";
}
```
Some tests
```
<html><header><title>Test</title></header>
<body>
<p>
<?php
$arr = array('hoi', 'wee', 'hai', 'Sub' => array('Hi' => 'Hi', 'Lo' => 'Lo'));
echo '<p>', formSelect('aaaa', null, $arr), "</p>\n";
echo '<p>', formSelect('ccc', 'Hi', $arr), "</p>\n";
echo '<p>', formLabel('hello', 'Hello'), ': ', formSelect('hello', 1, $arr), "</p>\n";
?></p>
<p>
<?php
$months = array (1 => 'Januar',
'Februar', 'Mars', 'April', 'Mai',
'Juni', 'Juli', 'August', 'September',
'Oktober', 'November', 'Desember');
echo formLabel('month', 'Month'), ': ', formSelect('month', null, $months), "\n";
echo formLabel('month2', 'Month'), ': ', formSelect('month2', 4, $months), "\n";
?></p>
</body><html>
``` | HTML Class with <select> | [
"",
"php",
"forms",
"class",
"select",
""
] |
I tried to use java.io.FileReader to read some text files and convert them into a string, but I found the result is wrongly encoded and not readable at all.
Here's my environment:
* Windows 2003, OS encoding: CP1252
* Java 5.0
My files are UTF-8 encoded or CP1252 encoded, and some of them (UTF-8 encoded files) may contain Chinese (non-Latin) characters.
I use the following code to do my work:
```
private static String readFileAsString(String filePath)
throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
FileReader reader = new FileReader(filePath);
//System.out.println(reader.getEncoding());
BufferedReader reader = new BufferedReader(reader);
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
```
The above code doesn't work. I found the FileReader's encoding is CP1252 even if the text is UTF-8 encoded. But the JavaDoc of java.io.FileReader says that:
> The constructors of this class assume
> that the default character encoding
> and the default byte-buffer size are
> appropriate.
Does this mean that I am not required to set character encoding by myself if I am using FileReader? But I did get wrongly encoded data currently, what's the correct way to deal with my situtaion? Thanks. | Yes, you *need to specify the encoding* of the file you want to read.
Yes, this means that you have to *know* the encoding of the file you want to read.
No, there is no general way to *guess* the encoding of any given "plain text" file.
[The one-arguments constructors of `FileReader`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileReader.html) always use the platform default encoding which is generally *a bad idea*.
Since Java 11 `FileReader` has also gained constructors that accept an encoding: [`new FileReader(file, charset)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileReader.html#%3Cinit%3E(java.io.File,java.nio.charset.Charset)) and [`new FileReader(fileName, charset)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileReader.html#%3Cinit%3E(java.lang.String,java.nio.charset.Charset)).
In earlier versions of java, you need to use [`new InputStreamReader(`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStreamReader.html)[`new FileInputStream(pathToFile)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileInputStream.html)`, <encoding>)`. | `FileReader` uses Java's platform default encoding, which depends on the system settings of the computer it's running on and is generally the most popular encoding among users in that locale.
If this "best guess" is not correct then you have to specify the encoding explicitly. Unfortunately, `FileReader` does not allow this (major oversight in the API). Instead, you have to use `new InputStreamReader(new FileInputStream(filePath), encoding)` and ideally get the encoding from metadata about the file. | Java FileReader encoding issue | [
"",
"java",
"file",
"unicode",
"encoding",
""
] |
I am trying to improve my embedded C/C++ development on ARM architecture. I have recently moved from 68K development to ARM and wanted to use some of my spare time to dig into the platform and learn the best practices especially on developing for mobile platforms.
Preferably 32bit architecture will be helpful with supporting development tools. A bit of fun during the learning process may enhance my understanding of the platform | [ST Micro](http://www.st.com/) has a very attractively priced (and packaged too) kit for their ARM Cortex-M3 based STM32 line. MSRP runs about US$35 for the [STM32-PRIMER](http://www.stm32circle.com/hom/index.php) with 128x128 color LCD, MEMS accelerometer, push button, LEDs, USB, and some spare GPIOs all in a package that includes a battery and USB to JTAG debug connection. A GCC toolchain and a commercial debugger are supposed to come with it as well. I have one on order, and will try to remember to edit this answer to include a quick review after it arrives next week sometime.
They have a new model based on an STM32 with more FLASH and RAM on chip that also has a micro-SD card connector, and a larger LCD that includes a resistive touchscreen that runs just over $100 if you can find it in stock.
[Luminary Micro](http://www.luminarymicro.com/) has a number of inexpensive demo/eval board kits as well. The people behind the [eLua project](http://www.eluaproject.net/) (a complete Lua programming environment running in SoC and MCU scale devices) seem to like the Luminary Micro product line, but I have no personal experience with them. | It seems like there's an awful lot of fun stuff being done with the [Arduino](http://blog.makezine.com/archive/arduino/) platform.
The basic answer is really "anything you can afford that will let you build fun stuff" and Arduino seems to fit the bill. | What is the best Evaluation Kit for Learning Embedded C/C++ Development? | [
"",
"c++",
"c",
"embedded",
"arm",
""
] |
I'm making a list of recent news. So, it will show something like this:
```
- Take a look at the new Volks...
- John Doe is looking for a jo...
- Microsoft is launching the n...
```
So, the list above only shows me the title of the news and the length of each news is limited in 25 characters. But, this is not working well... for example, if you type 25 M's, it will explode my div.
I've been told that there is a way to calculate the length of the string and make it fit in a div automatically.
Does anyone know how to do it?
thanks!! | I think you talking about is using the `System.Drawing.Gaphics` class's `MeasureString()` method.
However, this requires making a Graphics object which matches the font characteristics of your web page. *But*, your server process shouldn't know anything about the style elements of the web page, which should be handled by the CSS sheet. | "text-overflow: ellipsis" is what you want but not everybody supports it. [More info here...](http://www.blakems.com/archives/000077.html) | C# - How can I cut a string at its end to fit in a div? | [
"",
"c#",
".net",
"asp.net",
"c#-3.0",
""
] |
In my table, I have a nullable bit column (legacy system...) and another developer recently made a change to a stored procedure to only show values where the bit column was not true (1). Because this is a nullable column, we noticed that if the column was NULL, the record was not being picked up. WHY is this?
Both the other developer and I agree that NULL <> 1... Is this a bug in SQL or was this designed this way? Seems like a design flaw.
**Current Code:**
```
(VoidedIndicator <> 1)
```
**Proposed Fix:**
```
(VoidedIndicator <> 1 OR VoidedIndicator IS NULL)
```
**Clarification (By Jon Erickson)**
VoidedIndicator is a nullable bit field so it can have the following values: NULL, 0, or 1
When a SQL statement is created with a where clause such as (VoidedIndicator <> 1) we only get records returned that have VoidedIndicator == 0, but we were expecting both VoidedIndicator == 0 and VoidedIndicator IS NULL. Why is this? | From the [Wikipedia entry on NULL](http://en.wikipedia.org/wiki/Null_(SQL)#Common_mistakes):
> For example, a WHERE clause or
> conditional statement might compare a
> column's value with a constant. It is
> often incorrectly assumed that a
> missing value would be "less than" or
> "not equal to" a constant if that
> field contains Null, but, in fact,
> such expressions return Unknown. An
> example is below:
>
> ```
> -- Rows where num is NULL will not be returned,
> -- contrary to many users' expectations.
> SELECT * FROM sometable WHERE num <> 1;
> ```
Basically, *any* comparison between NULL and something else, whether it's with = or <> will not be true.
As another reference, the [MSDN T-SQL page on `<>`](http://msdn.microsoft.com/en-us/library/ms176020(SQL.90).aspx) states:
> Compares two expressions (a comparison
> operator). When you compare nonnull
> expressions, the result is TRUE if the
> left operand is not equal to the right
> operand; otherwise, the result is
> FALSE. If either or both operands are
> NULL, see SET ANSI\_NULLS
> (Transact-SQL).
The [SET ANSI\_NULLS](http://msdn.microsoft.com/en-us/library/ms188048(SQL.90).aspx) page then states:
> When SET ANSI\_NULLS is ON, a SELECT
> statement that uses WHERE column\_name
> = NULL returns zero rows even if there are null values in column\_name. A
> SELECT statement that uses WHERE
> column\_name <> NULL returns zero rows
> even if there are nonnull values in
> column\_name.
>
> ...
>
> When SET ANSI\_NULLS is ON, all
> comparisons against a null value
> evaluate to UNKNOWN. When SET
> ANSI\_NULLS is OFF, comparisons of all
> data against a null value evaluate to
> TRUE if the data value is NULL. | Lots of good answers, but let me give you a really concise version.
To SQL, Null does NOT mean "No value" it means "Unknown Value"
With that in mind, consider the answer to the question you are asking SQL in plain English.
```
Q: Is this unknown value not equal to 1?
A: I don't know, there is no way to tell without knowing the value.
Hence Null<>1 = Null
``` | SQL: Why are NULL values filtered out within this where clause? | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I wrote a program that allow two classes to "fight". For whatever reason C# always wins. What's wrong with VB.NET ?
```
static void Main(string[] args)
{
Player a = new A();
Player b = new B();
if (a.Power > b.Power)
Console.WriteLine("C# won");
else if (a.Power < b.Power)
Console.WriteLine("VB won");
else
Console.WriteLine("Tie");
}
```
Here are the players:
Player A in C#:
```
public class A : Player
{
private int desiredPower = 100;
public override int GetPower
{
get { return desiredPower; }
}
}
```
Player B in VB.NET:
```
Public Class B
Inherits Player
Dim desiredPower As Integer = 100
Public Overrides ReadOnly Property GetPower() As Integer
Get
Return desiredPower
End Get
End Property
End Class
```
And here is a base class.
```
public abstract class Player
{
public int Power { get; private set; }
public abstract int GetPower { get; }
protected Player()
{
Power = GetPower;
}
}
``` | The issue here is that VB is calling the base constructor before setting its field value. So the base Player class stores zero.
```
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 15 (0xf)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [base]Player::.ctor()
IL_0006: ldarg.0
IL_0007: ldc.i4.s 100
IL_0009: stfld int32 B::desiredPower
IL_000e: ret
} // end of method B::.ctor
``` | Promoting my comments to an answer:
Me:
> Try writing each "power" to the console as well
Prankster:
> C#: 100 VB.NET: 0
Me:
> As I suspected. Looks like VB.Net is calling the Base constructor before the inherited constructor, and therefore VB's desiredPower variable is still 0, whereas C# does it in reverse (remember, literal initialization happens at the end of the constructor).
**Update:**
I wanted to find some [documentation](http://msdn.microsoft.com/en-us/library/ms228387.aspx) on the behavior (otherwise you're looking at behavior that might change out from under you with any new .Net release). From the link:
> The constructor of the derived class implicitly calls the constructor for the base class
and
> Base class objects are always constructed before any deriving class. Thus the constructor for the base class is executed before the constructor of the derived class.
Those are on the same page and would seem to be mutually exclusive, but I take it to mean the derived class constructor is invoked first, but it is assumed to itself invoke the base constructor before doing any other work. Therefore it's not constructor order that important, but the manner in which literals are initialized.
I also found [this reference](http://www.csharp411.com/c-object-initialization/), which clearly says that the order is derived instance fields, then base constructor, then derived constructor. | I wrote a program that allow two classes to "fight". For whatever reason C# always wins. What's wrong with VB.NET? | [
"",
"c#",
"vb.net",
"compiler-construction",
"initialization",
""
] |
I'm trying to read binary data to load structs back into memory so I can edit them and save them back to the .dat file.
readVector() attempts to read the file, and return the vectors that were serialized. But i'm getting this compile error when I try and run it. What am I doing wrong with my templates?
\*\*\*\*\*\*\*\*\* EDIT \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
Code:
```
// Project 5.cpp : main project file.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace System;
using namespace std;
#pragma hdrstop
int checkCommand (string line);
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
template<typename T>
vector<T> readVector(ifstream &in);
struct InventoryItem {
string Item;
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
int dateAdded;
} ;
int main(void)
{
cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
ifstream in("data.dat");
vector<InventoryItem> structList;
readVector<InventoryItem>( in );
while (1)
{
string line = "";
cout << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-4: ";
getline(cin , line);
int rValue = checkCommand(line);
if (rValue == 1)
{
cout << "You've entered a invalid command! Try Again." << endl;
} else if (rValue == 2){
cout << "Error calling command!" << endl;
} else if (!rValue) {
break;
}
}
system("pause");
return 0;
}
int checkCommand (string line)
{
int intReturn = atoi(line.c_str());
int status = 3;
switch (intReturn)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
status = 0;
break;
default:
status = 1;
break;
}
return status;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i;
}
}
ostream& operator<<(std::ostream &strm, const InventoryItem &i) {
return strm << i.Item << " (" << i.Description << ")";
}
template<typename T>
vector<T> readVector(ifstream &in)
{
size_t size;
in >> size;
vector<T> vec;
vec.reserve(size);
for(int i = 0; i < size; i++)
{
T tmp;
in >> tmp;
vec.push_back(tmp);
}
return vec;
}
```
Compiler errors:
```
1>------ Build started: Project: Project 5, Configuration: Debug Win32 ------
1>Compiling...
1>Project 5.cpp
1>.\Project 5.cpp(124) : warning C4018: '<' : signed/unsigned mismatch
1> .\Project 5.cpp(40) : see reference to function template instantiation 'std::vector<_Ty> readVector<InventoryItem>(std::ifstream &)' being compiled
1> with
1> [
1> _Ty=InventoryItem
1> ]
1>.\Project 5.cpp(127) : error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'InventoryItem' (or there is no acceptable conversion)
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1144): could be 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,signed char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1146): or 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,signed char &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1148): or 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,unsigned char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1150): or 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,unsigned char &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(155): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::basic_istream<_Elem,_Traits> &(__cdecl *)(std::basic_istream<_Elem,_Traits> &))'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(161): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::basic_ios<_Elem,_Traits> &(__cdecl *)(std::basic_ios<_Elem,_Traits> &))'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(168): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::ios_base &(__cdecl *)(std::ios_base &))'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(175): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::_Bool &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(194): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(short &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(228): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(unsigned short &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(247): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(int &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(273): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(unsigned int &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(291): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(long &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(309): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(__w64 unsigned long &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(329): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(__int64 &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(348): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(unsigned __int64 &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(367): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(float &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(386): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(double &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(404): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(long double &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(422): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(void *&)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(441): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::basic_streambuf<_Elem,_Traits> *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> while trying to match the argument list '(std::ifstream, InventoryItem)'
1>Build log was saved at "file://c:\Users\Owner\Documents\Visual Studio 2008\Projects\Project 5\Project 5\Debug\BuildLog.htm"
1>Project 5 - 1 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
```
Oh my god...I fixed that error I think and now I got another one. Will you PLEASE just help me on this one too! What the heck does this mean ?? | ```
readVector( in ); // error C2783
```
This should be:
```
readVector<InventoryItem>( in );
```
Argument dependent lookup does not help deduce the templates, hence explicit specification is required.
```
in >> tmp;
```
This line requires you have a function like:
```
istream& operator>>(ostream& is, InventoryItem& item) {
// parse and read in the data to item
return is;
}
```
Put in the definition (I think strager provided this in your other question). | When you call readVector, it would normally try to deduce the template arguments from the parameter.
In your example, the only templated part is the return value, so it has no way to figure it out implicitly.
Change your call
```
readVector(in)
```
to
```
vector<InventoryItem> structList = readVector<InventoryItem>(in);
``` | Compile error C++: could not deduce template argument for 'T' | [
"",
"c++",
"templates",
"serialization",
"compiler-errors",
""
] |
I'm trying to create some functionality that keeps an audit trail of how data in a given user form has been changed over time, with a dated audit at the foot of that page. For example:
02/04/09 21:49 Name changed from "Tom" to "Chris".
I'm doing this by storing the data in it's present format in the session and then on save checking whether there are any differences in the data being stored. If there are, I'm storing the data how it was before the latest edit in a table called history, and storing the new values in the current user table.
Is this the best approach to be taking? | One suggestion; this would be relatively easy to do in a database trigger. In that case, you would never have to worry about whether the code running the update remembers to add a history record. | I'm not sure there is one "best approach", there are so many variables to take into consideration, including how far down the development path you are.
Having been through both code-based and db-trigger auditing solutions, I've listed some comments below; I hope you can see where you are now at (in terms of development) could affect these issues:
* If you need to map the user who changed the data (which you normally do) then db triggers will need to get this information somehow. Not impossible, but more work and several ways to approach this (db user executing query, common user column in each table, etc.)
* If you use db triggers and you rely on affected rows count returned from queries, then your audit triggers need to have this turned off, or your existing code modified to account for them.
* IMHO db triggers offer more security, and offer an easier path to audit automation, however they are not foolproof, as anyone with appropriate access can disable the triggers, modify data and then enable them again. In other words, ensure your db security access rights are tight.
* Having a single table for history is not a bad way to go, although you will have more work to do (and data to store) if you are auditing history for multiple tables, especially when it comes to reconstructing the audit trail. You also have to consider locking issues if there are many tables trying to write to one audit table.
* Having an audit history table for each table is another option. You just need each column in the audit table to be nullable, as well as storing date and time of action (insert/update/delete) and the user associated with the action.
* If you go with the single table option, unless you have a lot of time to spend on this, don't get too fancy trying to audit only on updates or deletes, although it may be tempting to avoid inserts (since most apps do this more often than updates or deletes), reconstructing the audit history takes a fair bit of work.
* If your servers or data span multiple time-zones, then consider using an appropriate datetime type to be able to store and reconstruct the timeline, i.e. store audit event date in UTC as well as including the timezone offset.
* These audit tables can get huge, so have a strategy if they start affecting performance. Options include table partitioning onto different discs, archiving, etc. basically think about this now and not when it becomes a problem :) | Is this the best approach to creating an audit trail? | [
"",
"php",
"mysql",
"audit",
""
] |
In one of our applications I've used some of the MFC classes to allow docking a sidebar window, approximately like so:
```
CDialogBar* bar = new CDialogBar;
bar->Create(this, IDD, WS_CHILD | WS_VISIBLE | CBRS_RIGHT | CBRS_TOOLTIPS, IDD));
bar->EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_RIGHT | CBRS_ALIGN_LEFT);
DockControlBar(bar, AFX_IDW_DOCKBAR_RIGHT);
```
This all works fine.
I want to do a similar thing now in another application. Unfortunately it has been changed to use some classes from the MFC "feature pack", which are very pretty but this approach no longer works (it asserts, which I can fix with some minor modification but then the sidebar doesn't appear). The documentation for these new classes is woeful, so I'm having quite a bit of trouble figuring out what I'm supposed to do. I've tried what seems to be the "new" approach:
```
CPaneDialog* pane = new CPaneDialog;
pane->Create("pane", this, TRUE, IDD, WS_VISIBLE | WS_CHILD, IDD);
EnableDocking(CBRS_ALIGN_RIGHT | CBRS_ALIGN_LEFT);
AddPane(pane);
DockPane(pane);
```
This works in that a sidebar window appears, but it doesn't seem to be movable and isn't getting drawn properly.
I feel like I'm shooting in the dark with all this. Does anybody know what the right approach to it is? | If we both shoot in the dark, we double our chances of hitting something.
Looking at the documentation for [CDockablePane](http://msdn.microsoft.com/en-us/library/bb984433.aspx) (the parent class of CPaneDialog), I notice a method called [EnableGripper](http://msdn.microsoft.com/en-us/library/bb984118.aspx). Try that. | This is what I do as part of my `CMainFrame::OnCreate`:
```
if (!m_projectsPane.Create(L"Projects", this, CRect(0,0,0,0), true, IDD_PROJECTSPANE, WS_CHILD|WS_VISIBLE))
return -1;
AddDockSite();
EnableDocking(CBRS_ALIGN_ANY);
EnableAutoHidePanes(CBRS_ALIGN_ANY);
m_projectsPane.EnableDocking(CBRS_ALIGN_LEFT|CBRS_ALIGN_RIGHT);
DockPane(&m_projectsPane, AFX_IDW_DOCKBAR_RIGHT);
```
My `m_projectsPane` is a class that then catches `ON_WM_GETMINMAXINFO` to fill `ptMinTrackSize` (to make sure the user can't resize the dialog below a certain minimum). I don't see anything else in my code and the resizing of the docked pane works fine. | Docking control bars/panes to CMDIFrameWndEx? | [
"",
"c++",
"mfc",
"mfc-feature-pack",
""
] |
I'm doing some image processing, and I'd like to individually read each pixel value in a JPEG and PNG images.
In my deployment scenario, it would be awkward for me to use a 3rd party library (as I have restricted access on the target computer), but I'm assuming that there's no standard C or C++ library for reading JPEG/PNG...
So, if you know of a way of *not* using a library then great, if not then answers are still welcome! | There is no standard library in the C-standard to read the file-formats.
However, most programs, especially on the linux platform use the same library to decode the image-formats:
For jpeg it's libjpeg, for png it's libpng.
The chances that the libs are already installed is *very* high.
<http://www.libpng.org>
<http://www.ijg.org> | This is a small routine I digged from 10 year old source code (using libjpeg):
```
#include <jpeglib.h>
int loadJpg(const char* Name) {
unsigned char a, r, g, b;
int width, height;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE * infile; /* source file */
JSAMPARRAY pJpegBuffer; /* Output row buffer */
int row_stride; /* physical row width in output buffer */
if ((infile = fopen(Name, "rb")) == NULL) {
fprintf(stderr, "can't open %s\n", Name);
return 0;
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
(void) jpeg_read_header(&cinfo, TRUE);
(void) jpeg_start_decompress(&cinfo);
width = cinfo.output_width;
height = cinfo.output_height;
unsigned char * pDummy = new unsigned char [width*height*4];
unsigned char * pTest = pDummy;
if (!pDummy) {
printf("NO MEM FOR JPEG CONVERT!\n");
return 0;
}
row_stride = width * cinfo.output_components;
pJpegBuffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
while (cinfo.output_scanline < cinfo.output_height) {
(void) jpeg_read_scanlines(&cinfo, pJpegBuffer, 1);
for (int x = 0; x < width; x++) {
a = 0; // alpha value is not supported on jpg
r = pJpegBuffer[0][cinfo.output_components * x];
if (cinfo.output_components > 2) {
g = pJpegBuffer[0][cinfo.output_components * x + 1];
b = pJpegBuffer[0][cinfo.output_components * x + 2];
} else {
g = r;
b = r;
}
*(pDummy++) = b;
*(pDummy++) = g;
*(pDummy++) = r;
*(pDummy++) = a;
}
}
fclose(infile);
(void) jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
BMap = (int*)pTest;
Height = height;
Width = width;
Depth = 32;
}
``` | How do I read JPEG and PNG pixels in C++ on Linux? | [
"",
"c++",
"c",
"linux",
"png",
"jpeg",
""
] |
Normally using a variable in a .cpp file results in the variable being globally available, like this:
```
.h file:
extern int myGlobal;
void work();
.cpp file:
int myGlobal = 42;
void work(){ myGlobal++; }
```
When the .cpp file is put in a static library and more than one shared library (DLL) or executable links against the static library, each one has its own copy of `myGlobal`. work() would modify its own version of the variable.
My question now: is there a way to get a process-wide unique variable or pointer to that variable? Similar what thread-local storage would be for thread-wide variables. It doesn't have to be platform independent. Bonus points if it works in Win32 :) | Simple: make all the DLLs in the process link to a single DLL that exposes the variable. | Either don't statically link to it (stick myGlobal in a DLL), or only link against the static library once (potentially more of a pain in the neck to achieve). | How to implement process-global variable in C++? | [
"",
"c++",
""
] |
I need to remove white spaces between xml tags, e.g. if the original xml looks like:
```
<node1>
<node2>
<node3>foo</node3>
</node2>
</node1>
```
I'd like the end-result to be *crunched* down to single line:
```
<node1><node2><node3>foo</node3></node2></node1>
```
Please note that I will not have control over the xml structure, so the solution should be generic enough to be able to handle any valid xml. Also the xml might contain CDATA blocks, which I'd need to exclude from this *crunching* and leave them as-is.
I have couple of ideas so far: (1) parse the xml as text and look for start and end of tags < and > (2) another approach is to load the xml document and go node-by-node and print out a *new* document by concatenating the tags.
I think either method would work, but I'd rather not reinvent the wheel here, so may be there is a python library that already does something like this? If not, then any issues/pitfalls to be aware of when rolling out my own *cruncher*? Any recommendations?
**EDIT**
Thank you all for answers/suggestions, both Triptych's and Van Gale's solutions work for me and do exactly what I want. Wish I could accept both answers. | **Pretty straightforward with BeautifulSoup.**
This solution assumes it is ok to strip whitespace from the tail ends of character data.
Example: `<foo> bar </foo>` becomes `<foo>bar</foo>`
It will correctly ignore comments and CDATA.
```
import BeautifulSoup
s = """
<node1>
<node2>
<node3>foo</node3>
</node2>
<node3>
<!-- I'm a comment! Leave me be! -->
</node3>
<node4>
<![CDATA[
I'm CDATA! Changing me would be bad!
]]>
</node4>
</node1>
"""
soup = BeautifulSoup.BeautifulStoneSoup(s)
for t in soup.findAll(text=True):
if type(t) is BeautifulSoup.NavigableString: # Ignores comments and CDATA
t.replaceWith(t.strip())
print soup
``` | This is pretty easily handled with lxml (note: this particular feature isn't in ElementTree):
```
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
foo = """<node1>
<node2>
<node3>foo </node3>
</node2>
</node1>"""
bar = etree.XML(foo, parser)
print etree.tostring(bar,pretty_print=False,with_tail=True)
```
Results in:
```
<node1><node2><node3>foo </node3></node2></node1>
```
**Edit:** The answer by Triptych reminded me about the CDATA requirements, so the line creating the parser object should actually look like this:
```
parser = etree.XMLParser(remove_blank_text=True, strip_cdata=False)
``` | Crunching xml with python | [
"",
"python",
"xml",
""
] |
I need a collection that can lookup a value based on the key and vice versa. For every value there is one key and for every key there is one value. Is there a ready to use data structure out there that does this? | The [BiMap](https://guava.dev/releases/28.0-jre/api/docs/com/google/common/collect/BiMap.html) from [Google Guava](https://github.com/google/guava) looks like it will suit you.
> A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.
Or the [BidiMap](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/BidiMap.html) from [Apache Commons Collections](https://commons.apache.org/proper/commons-collections/):
> Defines a map that allows bidirectional lookup between key and values.
>
> This extended `Map` represents a mapping where a key may lookup a value and a value may lookup a key with equal ease. This interface extends `Map` and so may be used anywhere a map is required. The interface provides an inverse map view, enabling full access to both directions of the `BidiMap`. | You can use [BiMap](http://www.eclipse.org/collections/javadoc/8.0.0/org/eclipse/collections/api/bimap/BiMap.html) from [Eclipse Collections](http://www.eclipse.org/collections/) (formerly GS Collections).
`BiMap` is a map that allows users to perform lookups from both directions. Both the keys and the values in a BiMap are unique.
The main implementation is `HashBiMap`.
**`inverse()`**
`BiMap.inverse()` returns a view where the position of the key type and value type are swapped.
```
MutableBiMap<Integer, String> biMap =
HashBiMap.newWithKeysValues(1, "1", 2, "2", 3, "3");
MutableBiMap<String, Integer> inverse = biMap.inverse();
Assert.assertEquals("1", biMap.get(1));
Assert.assertEquals(1, inverse.get("1"));
Assert.assertTrue(inverse.containsKey("3"));
Assert.assertEquals(2, inverse.put("2", 4));
```
**`put()`**
`MutableBiMap.put()` behaves like `Map.put()` on a regular map, except it throws when a duplicate value is added.
```
MutableBiMap<Integer, String> biMap = HashBiMap.newMap();
biMap.put(1, "1"); // behaves like a regular put()
biMap.put(1, "1"); // no effect
biMap.put(2, "1"); // throws IllegalArgumentException
```
**`forcePut()`**
This behaves like `MutableBiMap.put()`, but it silently removes the map entry with the same value before putting the key-value pair in the map.
```
MutableBiMap<Integer, String> biMap = HashBiMap.newMap();
biMap.forcePut(1, "1"); // behaves like a regular put()
biMap.forcePut(1, "1"); // no effect
biMap.put(1, "2"); // replaces the [1,"1"] pair with [1, "2"]
biMap.forcePut(2, "2"); // removes the [1, "2"] pair before putting
Assert.assertFalse(biMap.containsKey(1));
Assert.assertEquals(HashBiMap.newWithKeysValues(2, "2"), biMap);
```
**Note:** I am a committer for Eclipse Collections. | Java Collection - Unique Key and Unique Value | [
"",
"java",
"collections",
""
] |
Anyone know how can I disable backspace and delete key with Javascript in IE? This is my code below, but seems it's not work for IE but fine for Mozilla.
```
onkeydown="return isNumberKey(event,this)"
function isNumberKey(evt, obj)
{
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode == 8 || charCode == 46) return false;
return true;
}
``` | This event handler works in all the major browsers.
```
function onkeyup(e) {
var code;
if (!e) var e = window.event; // some browsers don't pass e, so get it from the window
if (e.keyCode) code = e.keyCode; // some browsers use e.keyCode
else if (e.which) code = e.which; // others use e.which
if (code == 8 || code == 46)
return false;
}
```
You can attach the event to this function like:
```
<input onkeyup="return onkeyup()" />
``` | **update** based on [@JoeCoder](https://stackoverflow.com/users/187523/joecoder)s comment and the 'outdatedness' of my answer, I revised it.
```
document.querySelector([text input element]).onkeydown = checkKey;
function checkKey(e) {
e = e || event;
return !([8, 46].indexOf(e.which || e.keyCode || e.charCode) > -1);
}
```
See also [**this jsFiddle**](http://jsfiddle.net/KooiInc/9r6bvaLd/) | Disable backspace and delete key with javascript in IE | [
"",
"javascript",
""
] |
I was wondering if anyone knows how the C# compiler handles the following assignment:
```
int? myInt = null;
```
My assumption is that there is an implicit conversion performed, but I cannot figure out how the null literal assignment is handled. I dissasembled the System.Nullable object and found the implicit operator is overriden to this:
```
public static implicit operator T?(T value) {
return new T?(value);
}
```
Once called this would try to fire the secondary constructor:
```
public Nullable(T value) {
this.value = value;
this.hasValue = true;
}
```
Which is where my confusion comes into play... this.value is of some value type and cannot be null.
So, does anyone know how this "magic" takes place... or am I wrong in assuming that the secondary constructor is called? Does the default constructor get called because the compiler knows that it cannot match the second contructor's signature with the null literal (resulting in myInt being assigned to a new "null" Nullable)? | The statement:
```
int? myInt = null;
```
Gets compiled as:
```
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
```
Which, [according to the MSDN](http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.initobj(VS.85).aspx), means «Initialize each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type.»
So there's no constructor or conversion here. HasValue will return false, and trying to get its Value will throw an InvalidOperationException. Unless you use GetValueOrDefault of course. | What really happens is that when you assign `null` to the nullable type instance, the compiler simply creates a new instance of `T?`, using the default constructor (the initobj IL instruction on [Jb answer](https://stackoverflow.com/questions/711635/how-does-the-assignment-of-the-null-literal-to-a-system-nullablet-type-get-handle/711678#711678)), so the following two lines are equivalent:
```
int? a = null;
Nullable<int> b = new Nullable<int>();
object.Equals(a,b); // true
```
Therefore you cannot do this:
```
Nullable<int> c = new Nullable<int>(null);
```
Something similar happens then you compare a nullable type to null:
```
if (a == null)
{
// ...
}
```
Behind the scenes it just does a call to the a.HasValue property. | How does the assignment of the null literal to a System.Nullable<T> type get handled by .Net (C#)? | [
"",
"c#",
"nullable",
""
] |
E.g. eng, spa, ita, ger
I could iterate all locales and compare the codes, but I wonder whether there is a more elegant & performant way to achieve this....
Thanks a lot for any hints :) | I don't know if there's an easy way to convert the 3-letter to the 2-letter versions, but in a worse case scenario, you could create a Map of them, like so:
```
String[] languages = Locale.getISOLanguages();
Map<String, Locale> localeMap = new HashMap<String, Locale>(languages.length);
for (String language : languages) {
Locale locale = new Locale(language);
localeMap.put(locale.getISO3Language(), locale);
}
```
Now you can look up locales using things like `localeMap.get("eng")`;
Edit: Modified the way the map is created. Now there should be one object per language.
Edit 2: It's been a while, but changed the code to use the actual length of the languages array when initializing the Map. | You can use constructor `Locale(String language)`, where language is the 2 letter ISO-639-1 code. I think the easiest way to convert ISO-639-2 to ISO-639-1 would be to create `HashMap<String,String>` constant. | Is there an elegant way to convert ISO 639-2 (3 letter) language codes to Java Locales? | [
"",
"java",
"localization",
"locale",
""
] |
I am seeing in some domain object models that an abstract base class is created(that implement Equals and GetHashCode) for all domain Entity objects to inherit from to gain their identity.
I am not clear why this base class is needed and when and why it should be used. Can you provide me some insight on this or refer me a link that talks on this
Thanks
Now I understand the advantages of overriding Equality (this link helped <http://en.csharp-online.net/CSharp_Canonical_Forms>—Identity\_Equality)
Going back to domain driven design I would like to expand my question a bit;
I have a customer entity which I use guid as identity.
If I create 2 instances of customer with exactly the same details, since I am using guid as the identity they will be two different objects. But as they have all attributes the same they should be the same object(or is it a better ddd practice to keep them unique and seperate??)
Trying to understand if I should handle the equality of two objects by their full attribute value match. If I go toward that direction then I am looking at either overriding the Equality of the base class on the level of sub class and implement these conditions or have the identity of the entity a string or hash code(?) representation of the values of all these attributes and use the Equality of the base class.
I could be little off here so thanks in advance for the patience. | The use of the term **equality** is overloaded here:
1) Equality for *Identity*
If you have 2 instances of the same Customer, they should both have the same GUID value – it’s the only way to ensure that you're working with the same Entity. In reality, there will always be different instances of the same Entity (e.g. multi-user apps running on different machines).
2) Equality for *sameness*
This is where you're checking that 2 instances have all the same values. For instance, if 2 staff members are looking at the same Customer, and the first person modifies & saves it, both people will see different data. They’re both interested in the same Customer, but the data becomes stale.
For (2), you definitely need a mechanism to do the checking. You could compare each property (expensive), or you could use a ‘version’ property to detect changes (see [NHibernate’s optimistic locking mechanism](https://stackoverflow.com/questions/118526/how-do-you-deal-with-concurrency-in-nhibernate)).
I think your example is a bit contrived, and might be drawing you away from the more important aspects of DDD. If you’re interested, [I sell a tool](http://www.evolving-software.co.uk) that can help grasp DDD concepts easier. | You should compare the IDs of the objects if they are entities and their attributes in case they are value objects. That means that you don't have to inherit your value objects from a base entity, but for entities it's better to create one.
How to understand if a class is an entity or a value object? You should answer a question: are objects of such class equal if they have the same attribute set? If yes, they are values objects. For example, two persons are not equal even if they have the same names and birth dates - you should treat them as different entities anyway. But if you have 25 cent coin, you probably don't care what **exact** piece of metal do you have, they all just 25 cent coins.
There's a great article describing the details: [domain object base class](http://enterprisecraftsmanship.com/2014/11/08/domain-object-base-class/) | Abstract Base class for All Domain Entity Objects | [
"",
"c#",
"domain-driven-design",
""
] |
A beginner question:
I have a stored proc (just a procedure, without any packages) in the Oracle Database:
```
CREATE OR REPLACE procedure FII_DBO.CLEAR_UNIT_TEST_PRODUCT
IS
BEGIN
...
END CLEAR_UNIT_TEST_PRODUCT;
```
and it works fine in TOAD. However, when I try to run it from C# it complains:
```
System.Data.OracleClient.OracleException: ORA-06550: line 1, column 7:
PLS-00201: identifier 'CLEAR_UNIT_TEST_PRODUCT' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
```
relevant C# code:
```
Command = new OracleCommand();
Command.CommandText = procedureName;
Command.CommandType = CommandType.StoredProcedure;
Command.Connection = connection;
Command.ExecuteNonQuery();
``` | Check that the Oracle user that your .NET application is connecting with has permissions to execute the stored procedure. | Found it, the error message was a bit misleading. I was executing it as a different user, who didn't have the proper access rights. This did the trick:
```
grant execute on FII_DBO.CLEAR_UNIT_TEST_PRODUCT to FII_USER;
``` | Running Oracle stored procs from C# | [
"",
"c#",
".net",
"oracle",
"ora-06550",
""
] |
I'm familiar with the the date and time classes in the JDK and their associated formatting methods. I may be blind, but I cannot find an equivalent set of classes for processing time intervals. For example, I would like to display the number of days for a given long value of milliseconds. I realize that the method to do these conversions is quite simple, however when you factor in internationalization and localization support this becomes less trivial.
I'm surprised that the JDK is missing support for interval processing. However, databases such as [Postgresql](http://www.postgresql.org/docs/8.1/interactive/functions-datetime.html) support it.
Basically what I'm looking for in the JDK (if I'm too blind to see it) or in a third party library is the following functionality:
* Time calculation methods. Such as milliseconds to weeks or seconds to nanoseconds. Although the math is simple for these operations, having an API to go through seems more self-documenting to me.
* Time interval formatting functions that format according to the passed Locale like DateFormat works. For example, in EN\_US I would assume that 10 days is well "10 days" and in Japanese I would want "10日" returned.
Is there anything out there or is this a canidate for a new open-source project? | Have you tried [Joda Time](http://joda-time.sourceforge.net/)? | have a look at <http://commons.apache.org/> and the DateUtils class there | Is there an easy way to Calculate and format time/date intervals in java? | [
"",
"java",
"datetime",
"date",
"time",
"intervals",
""
] |
Is there any way to access the backing field for a property in order to do validation, change tracking etc.?
Is something like the following possible? If not is there any plans to have it in .NET 4 / C# 4?
```
public string Name
{
get;
set
{
if (value != <Keyword>)
{
RaiseEvent();
}
<Keyword> = value;
}
}
```
The main issue I have is that using auto properties doesn't allow for the same flexibility in validation etc. that a property with a explicit backing field does. However an explicit backing field has the disadvantage in some situations of allowing the class it is contained in to access the backing field when it should be accessing and reusing the validation, change tracking etc. of the property just like any other class that may be accessing the property externally.
In the example above access to the backing field would be scoped to the property thus preventing circumvention of the property validation, change tracking etc.
**Edit:** I've changed < Backing Field > to < Keyword >. I would propose a new keyword similar to value. **field** would do nicely although I'm sure it's being used in a lot of existing code. | Having read your comments in Mehrdad's answer, I think I understand your problem a bit better.
It appears that you are concerned about the ability of the developer to access private state in the class they are writing, bypassing your validation logic, etc. This suggests that the state should not be contained in the class at all.
I would suggest the following strategy. Write a generic class that represents a ValidatedValue. This class holds only the backing value and only allows access/mutation via get and set methods. A delegate is passed to the ValidatedValue to represent the validation logic:
```
public class ValidatedValue< T >
{
private T m_val;
public ValidationFn m_validationFn;
public delegate bool ValidationFn( T fn );
public ValidatedValue( ValidationFn validationFn )
{
m_validationFn = validationFn;
}
public T get()
{
return m_val;
}
public void set(T v)
{
if (m_validationFn(v))
{
m_val = v;
}
}
}
```
You could, of course, add more delegates as required (eg, to support pre/post change notification).
Your class would now use the ValidatedValue in place of a backing store for your property.
The example below shows a class, MyClass, with an integer that is validated to be less than 100. Note that the logic to throw an exception is in MyClass, not the ValidatedValue. This allows you to do complex validation rules that depend on other state contained in MyClass. Lambda notation was used to construct the validation delegate - you could have bound to a member function instead.
```
public partial class MyClass
{
private ValidatedValue<int> m_foo;
public MyClass()
{
m_foo = new ValidatedValue<int>(
v =>
{
if (v >= 100) RaiseError();
return true;
}
);
}
private void RaiseError()
{
// Put your logic here....
throw new NotImplementedException();
}
public int Foo
{
get { return m_foo.get(); }
set { m_foo.set(value); }
}
}
```
Hope that helps - somewhat off the original topic, but I think it's more inline with your actual concerns. What we have done is taken the validation logic away from the property and put it on the data, which is exactly where you wanted it. | No there isn't. If you want to access the backing field, then don't use auto properties and roll your own.
I agree that it would be great to have a field that was only accessible by the property and not by the rest of the class. I would use that all the time. | Acessing the backing field in an auto property | [
"",
"c#",
".net-3.5",
"c#-3.0",
"properties",
"encapsulation",
""
] |
Does anyone know of a simple "Hello World" example for using the Webkit library in Python? I have a GTK window, and inside I want to put Webkit.
With Python/mozembed (Mozilla/Gecko), this is simple:
```
mozembed = gtkmozembed.MozEmbed()
mozembed.load_url('http://google.com/')
```
..and I have already created my browser, how do I do this with WebKit? | Did you check the [Python bindings for the WebKit GTK+ port](http://code.google.com/p/pywebkitgtk/). In one of the directory there are demos on how to use it, including a browser: python demos/tabbed\_browser.py
You could check also the slides of a FOSDEM by Alp Toker on [WebKit GTK+](http://www.atoker.com/webkit/webkitgtk-fosdem08.pdf) (pdf) Developing hybrid Web/GTK+ rich internet applications.
```
import gtk
import webkit
view = webkit.WebView()
sw = gtk.ScrolledWindow()
sw.add(view)
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.add(sw)
win.show_all()
view.open("http://w3.org/")
gtk.main()
```
That should give you good hints for starting. | Now with WebKitGtk2
```
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk, WebKit2
window = Gtk.Window()
window.set_default_size(800, 600)
window.connect("destroy", Gtk.main_quit)
scrolled_window = Gtk.ScrolledWindow()
webview = WebKit2.WebView()
webview.load_uri("https://google.cl")
scrolled_window.add(webview)
window.add(scrolled_window)
window.show_all()
Gtk.main()
``` | Need a simple "Hello World" example using the Webkit library in Python | [
"",
"python",
"webkit",
""
] |
I have two tables:
> **Application**
> applicationid (int)
> applicationname (varchar)
> isavailable (bit)
and
> **Holidays**
> applicationid (int)
> holidaydate (datetime)
I need to get the *isavailable* flag for any given applicationname but it should only return if the day if is not a holiday. The *isavailable* flag is independent of holidays - it is only set if there are system-wide problems, not on a set schedule.
I initially had something like:
```
select top 1 apps.isavailable
from dbo.Applications apps, dbo.Holidays hol
where apps.applicationid = hol.applicationid and
apps.applicationname = @appname and
((datediff(dd,getdate(),hol.holidaydate)) != 0)
```
but that was returning records even if today was a holiday because the other holiday dates don't equal today.
I tried
```
and (CONVERT(VARCHAR,getdate(),101)) not in (CONVERT(VARCHAR,hol.holidaydate,101))
```
(it is on SQL Server 2005, so there is no Date type so I have to convert it)
but again, it was returning records even if today was a holiday. How can I structure this query using a "not in" or "except" clause (or something else) to only return a record if today isn't a holiday?
**Update**
I don't need a list of all applicationnames that don't have a holiday - I need a record for the specified apps.applicationname. The answers below only return the application names that don't have a holiday on today. The query should return the isavailable flag if it is not a holiday, or else return no records if it is a holiday. I don't care about the other applications.
Also, what if I added a table like:
> **HoursOfOperations**
> applicationid (int)
> mondayopen (datetime)
> mondayclose (datetime)
> tuesdayopen (datetime)
> tuesdayclose (datetime)
> //open and close for all seven days of the week
Could I join on all three of these tables to only return a record if it is within the hours for the given day and is not a holiday? Do I have to do this in separate queries? | THe following query should get you a list of applications that DO NOT have a holiday defined for the CURRENT date.
```
SELECT apps.ApplicationName, apps.isavailable
FROM dbo.Applications apps
WHERE apps.ApplicationName = @AppName
AND NOT EXISTS
( SELECT *
FROM Holidays
WHERE ApplicationId = apps.ApplicationId
AND CONVERT(VARCHAR,getdate(),101) = CONVERT(VARCHAR,holidaydate,101)
)
```
Basically what we do is select everything where it does not have a match. | OK, just to be different, how about something like this:
```
select apps.isavailable
from dbo.Application apps left outer join dbo.Holidays hol
on apps.applicationid = hol.applicationid
and convert(varchar(10),getdate(),101) = convert(varchar(10),hol.holidaydate,101)
where apps.applicationname = @appname
and hol.applicationid is null
```
Basically, you're joining the tables based on applicationid and the current date. Since it's a left join, you'll always get all the applications that match @appname, then you just filter out any results that get a match based on the holiday date being the current date. Assuming that applicationname is unique, you'll always get a single row where the right half of the join is null, unless the current date matches a holiday, in which case the query will return no results.
I don't know how it stacks up with the other solutions performance-wise; I believe joins are generally supposed to be faster than sub-queries, but that probably depends on a variety of factors, so YMMV. | SQL query to exclude records if it matches an entry in another table (such as holiday dates) | [
"",
"sql",
"join",
"sql-server-2005",
""
] |
How can I derive a class from `cout` so that, for example, writing to it
`new_cout << "message";`
would be equivalent to
`cout << __FUNCTION__ << "message" << "end of message" << endl;` | ```
class Log
{
public:
Log(const std::string &funcName)
{
std::cout << funcName << ": ";
}
template <class T>
Log &operator<<(const T &v)
{
std::cout << v;
return *this;
}
~Log()
{
std::cout << " [end of message]" << std::endl;
}
};
#define MAGIC_LOG Log(__FUNCTION__)
```
Hence:
```
MAGIC_LOG << "here's a message";
MAGIC_LOG << "here's one with a number: " << 5;
``` | ```
#define debug_print(message) (std::cout << __FUNCTION__ << (message) << std::endl)
```
This has the advantage that you can disable all debug messages at once when you're done
```
#define debug_print(message) ()
``` | customize cout | [
"",
"c++",
"stl",
"iostream",
""
] |
I use `SQL_CALC_FOUND_ROWS` in Mysql SELECT statement, to get the number of lines my SELECT would return without a LIMIT clause.
```
$sql = new mysqli('localhost', 'root', '');
$sql->select_db('mysql');
$s1 = $sql->query('select SQL_CALC_FOUND_ROWS * from db limit 0, 3');
$s2 = $sql->query('select FOUND_ROWS()');
if($row = $s2->fetch_row()) printf('%d/%d', $s1->num_rows, $row[0]);
```
On my WinXP dev station it return 3/0 everytime for several weeks. When I use another MySQL server from my station it return 3/0 too.
On anothers PC the same code runs fine, and return the correct number (3/17 for example, if I have 17 records in mysql.db table). Every XP PC have the same PHP/Mysql version, and it ran fine in the past on my PC
Using Mysql Query Browser with the same SQL queries I get the right number.
Could anyone give me an idea of solution, without re-install all?
Sorry, my previous request was awfully unclear. | Thank you.
When I ran something analogous to your example on the mysql command line, it would work; but running it from php, it failed. The second query has to "know about" the first one, so I figure somehow that persistence/memory linking the two queries was getting messed up by the php.
(It turns out that Wordpress uses this type of query to do its pagination - so our larger problem was that the pagination in a wordpress install suddenly stopped working when we moved to php 5.2.6 ... eventually tracked it down to the FOUND\_ROWS()).
Just for the sake of posting for people who may run into this in the future... for me it was the php setting "mysql.trace\_mode" - this defaulted "on" in 5.2.6 instead of "off" like previously, and for some reason prevents the FOUND\_ROWS() from working.
As a "fix", we could either put this in every php page (actually, in a common "include"):
```
ini_set("mysql.trace_mode", "0");
```
or add this to the .htaccess:
```
php_value mysql.trace_mode "0"
```
Thanks again,
Jerry | Are you using a MySQL query method that allows for multiple queries.
From MySQL documentation.
> To obtain this row count, include a `SQL_CALC_FOUND_ROWS` option in the SELECT statement, and then invoke `FOUND_ROWS()` afterward
Example:
```
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
```
Also just for fun, there's a great discussion about the race condition of `FOUND_ROWS()`'s usage [here.](http://is.php.net/manual/en/function.mysql-num-rows.php#85654) | SQL_CALC_FOUND_ROWS / FOUND_ROWS() does not work in PHP | [
"",
"php",
"mysql",
""
] |
I have an order which has a status (which in code is an Enum). The question is how to persist this. I could:
1. Persist the string in a field and then map back to enum on data retrieval.
2. Persist this as an integer and then map back to enum on data retrieval.
3. Create separate table for enum value and do a join on data retrieval.
Thoughts? | If this is a fixed list (which it seems it is, or else you shouldn't store it as an enum), I wouldn't use #1.
The main reason to use #3 over #2 is for ease of use with self-service querying utilities. However, I'd actually go with a variant of #2: Store the value as an integer and map to an enum on data retrieval. However, also create a table representing the enum type, with the value as the PK and the name as another column. That way it's simple, quick, and efficient to use with your code, but also easy to get the logical value with self-service querying and other uses that don't use your data access code. | #3 is the most "proper" from a database/normalization standpoint. Your status is, in effect, a domain entity that's linked to the order entity. | Persisting Enums in database tables | [
"",
"c#",
"database-design",
"enums",
""
] |
I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs.
My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback propagate to stderr (i.e. the log file).
If I do something like this:
```
def updateResults(self):
try:
#code that updates the results
except:
#display error message box
```
This will catch the exception and not propogate to the error log.
Is there some way to show the user the message and then continue to propogate the error?
Would this work?
```
except, e:
#display error message box
raise e
```
Is there a better way to accomplish my goal? | I think you are thinking about this in the wrong way. You shouldn't be re-raising the error simply to log it further down the line. The cannonical way of doing this in Python is to use the logging module. Adapted from the docs:
```
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
...
try:
# code
except:
logging.debug('Something bad happened', exc_info=True)
# display message box
# raise (if necessary)
```
This gives a far more flexible logging system than relying on errors produced on sys.stdout. You may not need to re-raise the exception if you can recover from the exception in some way. | Exactly, but you can just
```
raise
```
which will re-raise the currently handled exception. | How to display errors to the user while still logging it? | [
"",
"python",
"exception",
"error-handling",
"pyqt4",
"error-logging",
""
] |
The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?
Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.
[xml.etree.elementtree](http://docs.python.org/library/xml.etree.elementtree.html) | If you're using `xml.etree.ElementTree.parse` to parse from a file, then you can use `xml.etree.ElementTree.fromstring` to get the root `Element` of the document. Often you don't actually need an `ElementTree`.
See [xml.etree.ElementTree](http://docs.python.org/library/xml.etree.elementtree.html) | You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.
```
import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))
```
I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the [`parse()`](https://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.parse) and [`fromstring()`](https://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.fromstring) methods. | Python xml ElementTree from a string source? | [
"",
"python",
"xml",
""
] |
What is the easiest way to make Linux C++ GUI apps? I'm using GNOME and ubuntu 8.10. | I personally prefer QT as I prefer working with the signal/slots mechanism and just find it easy to develop applications quickly with it. Some of your other options would be wxWidgets and GTK+. | The easiest way is to use an GUI GUI builder.
[Glade](http://glade.gnome.org/) for GTK.
[QT Designer](https://doc.qt.io/qt-6/qtdesigner-manual.html) for QT.
[wxDesigner](http://www.roebling.de/) and [wxFormBuilder](http://www.wxformbuilder.org/) for [wxWidgets](http://www.wxwidgets.org/).
Update: I should mention that these output C++ among many others? | How to make Linux C++ GUI apps | [
"",
"c++",
"user-interface",
"ubuntu",
"gnome",
""
] |
I have a set of bytes I want to apply an sha1 hash to. One hash will be in .net, the other in PHP. Then I'll test to see if they match.
In .net, you can create a byte array and use sha.ComputeHash().
```
byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA1 sha = new SHA1CryptoServiceProvider();
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);
```
In PHP, you call sha1($string).
I can't do anything about the .net side of the code, but how can I get the same hash out of PHP that .net will generate?
Please note: I am ONLY able to work on the PHP side of this. The .net stuff is fixed and can't be modified. Thanks! | Since SHA1 is a common, standard algorithm, it is implemented the same way in PHP as it is in .NET. The only part that is different is how you invoke the two functions.
Technically, SHA1 is defined on bytes rather than strings, but (correct me if I'm wrong) PHP strings work with single-byte characters, so bytes and characters should be interchangable from the SHA1 algorithm's point of you.
You'll have to make sure that your string's value in binary is the same as .NET's byte array, in the same order. I'm not a PHP guy, so you'll have to get someone else's answer for how to do that. | It looks like the sha1 function takes a byte array which is in hexidecimal notation. So if you had two bytes, FA and A1, your string would be "FAA1".
Then, you would parse the result string back into bytes and compare with the .NET output.
Note that you could create this string in .NET with the same format rather easily (use the "x2" format on the call to ToString on each byte and append all together). | If .net sha1 hash expects a byte array, and php sha1() wants a string, can I match the results? | [
"",
".net",
"php",
"sha1",
""
] |
I'm working on a project fuzzing a media player. I wrote the file generator in Java and converted the CRC generator from the original compression code written in C. I can write data fine with DataOutputStream, but I can't figure out how to send the data as an unsigned character array in java. In C this is a very straightforward process. I have searched for a solution pretty thoroughly, and the best solution I've found is to just send the data to C and let C return a CRC. I may just not be searching correctly as I'm pretty unfamiliar with this stuff. Thank you very much for any help. | You definitely want a byte[]. A 'byte' is equivalent to a signed char in C. Java's "char" is a 16-bit unicode value and not really equivalent at all.
If it's for fuzzing, unless there's something special about the CRC function you're using, I imagine you could simply use:
```
import java.util.Random;
Random randgen = new Random();
byte[] fuzzbytes = new byte[numbytes];
randgen.nextBytes(fuzzbytes);
outstream.write(fuzzbytes, 0, numbytes);
``` | I doubt that you want to do anything with characters. I can't see anything in your description which suggests *text* manipulation, which is what you'd do with characters.
You want to use a byte array. It's a bit of a pain that bytes are signed in Java, but a byte array is what you've got - just work with the bit patterns rather than thinking of them as actual numbers, and check each operation carefully. | Java Unsigned Char Array | [
"",
"java",
"crc",
""
] |
OK, I understand what the messages *means*, but I'm really not sure what's causing it. I'm using Safari and the Web Inspector on Mac OS X, by the way.
I've got the following in my document head:
```
<script src="http://local.url/a/js/jquery.js" type="text/javascript"></script>
<script src="http://local.url/a/js/jquery.inplace.js" type="text/javascript"></script>
```
`jquery.js` is handled fine, but the other file causes the warning. It also seems that the javascript in this file never gets executed.
The file is being served via `mod_deflate`, so it is gzip encoded, but so is the other file.
Has anybody got any ideas what's causing this, or how to resolve it?
Cheers all,
Gaz. | seems to be a bug in safari / webkit. maybe [this one](https://bugs.webkit.org/show_bug.cgi?id=22994), or [any of these](https://bugs.webkit.org/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__open__&product=WebKit&content=Resource+interpreted+as+other). try upgrading your safari. if there is no more recent stable version, try the 4 beta. | An image with an empty "src" attribute generates this error under Windows-Chrome:
```
<img src="">
```
... whereas ...
```
<img>
```
... does not.
I arrived here because my ajax resultset was returning "src" data which was empty yet the img was still being inserted into the page. | Debug message "Resource interpreted as other but transferred with MIME type application/javascript" | [
"",
"javascript",
"apache",
"safari",
"mime-types",
""
] |
I have an object(A) which has a list composed of objects (B). The objects in the list(B) are pointers, but should the list itself be a pointer? I'm migrating from Java to C++ and still haven't gotten fully accustomed to the stack/heap. The list will not be passed outside of class A, only the elements in the list. Is it good practice to allocate the list itself on the heap just in case?
Also, should the class that contains the list(A) also be on the heap itself? Like the list, it will not be passed around. | Bear in mind that
1. The list would only be on the stack if Object-A was also on the stack
2. Even if the list itself is not on the heap, it may allocate its storage from the heap. This is how std::list, std::vector and most C++ lists work – the reason is that stack-based elements cannot grow.
3. These days most stacks are around 1mb, so you'd need a pretty big list of pretty big objects before you need to worry about it. Even if your stack was only about 32kb you could store close to eight thousand pointers before it would be an issue.
IMO people new to the explicit memory management in C/C++ can have a tendency to overthink these things.
Unless you're writing something that you know will have thousands of sizable objects just put the list on the stack. Unless you're using giant C-style arrays in a function the chances are the memory used by the list will end up in the heap anyway due to #1 and #2 above. | You're better off storing a list, if it can grow, on the heap. Since you never know what the runtime stack will be, overflow is a real danger, and the consequences are fatal.
If you absolutely know the upper bound of the list, and it's small compared to the size of your stack, you can probably get away with stack allocating the list. | Should a list of objects be stored on the heap or stack? | [
"",
"c++",
"object",
"memory-management",
"stack",
"heap-memory",
""
] |
I know there are different methods in the System.Web namespace for decoding html entities (such as "%20" for space). I'm building a Winforms application however, but needs to deal with html encoded strings. Basically I have the iTunes Library XML file and need to decode the URLs in there to check the files.
Is this possible without the System.Web namespace? | > Developers who need to use System.Web.HttpUtility in their client apps and had to reference System.Web.dll and therefore target NET4
> full (System.Web.dll is in Full) , can now target the NET4 Client
> Profile by using the new System.Net.WebUtility class which is in
> System.dll (System.dll is in NET4 Client Profile).
> System.Net.WebUtility includes HtmlEncode and HtmlDecode. Url encoding
> can be accomplished using the System.Uri class (also in System.dll).
From <http://blogs.msdn.com/b/jgoldb/archive/2010/04/12/what-s-new-in-net-framework-4-client-profile-rtm.aspx> | You can use [`System.Net.WebUtility.HtmlDecode`](http://msdn.microsoft.com/en-us/library/system.net.webutility.htmldecode.aspx):
> Converts a string that has been HTML-encoded for HTTP transmission into a decoded string. | C# HTMLDecode without System.Web possible? | [
"",
"c#",
"html-encode",
""
] |
I have a string of email recipients in the format like this:
```
DECLARE @recipients VARCHAR(MAX);
....
PRINT @recipients;
/* the result
person1@yahoo.com;person2@hotmail.com;person1@yahoo.com;...
*/
```
"SELECT DISTIECT ..." is a simple and powerful SQL statement, but it works against a table. Is there a simple way to select **distinct** recipient from the recipient list variable like FOR loop in C# or Ruby?
```
FOR @recipient IN @recipients
BEGIN
-- send email to @recipient
END
```
By the way, I am using TSQL in SQL server 2005. | Here's a solution for you that uses a temporary table.
```
declare @emails varchar(2000)
set @emails = 'person1@yahoo.com;person2@hotmail.com;person1@yahoo.com;'
declare @results table (row int identity(1,1), email varchar(500))
while ((select charindex(';',@emails)) > 0)
begin
insert into @results select substring(@emails,1,charindex(';',@emails))
select @emails = substring(@emails,charindex(';',@emails)+1,len(@emails))
end
select distinct email from @results
```
The idea is to continously parse the email from the string, insert it into a temporary table, and remove the parsed email from the remaining string.
You can use loop through the temporary table afterward to send your individual emails. | e.g.
```
CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
GO
``` | Select item from a string of items | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
What is stack alignment?
Why is it used?
Can it be controlled by compiler settings?
The details of this question are taken from a problem faced when trying to use ffmpeg libraries with msvc, however what I'm really interested in is an explanation of what is "stack alignment".
The Details:
* When runnig my msvc complied program which links to avcodec I get the
following error: "Compiler did not align stack variables. Libavcodec has
been miscompiled", followed by a crash in avcodec.dll.
* avcodec.dll was not compiled with msvc, so I'm unable to see what is going on inside.
* When running ffmpeg.exe and using the same avcodec.dll everything works well.
* ffmpeg.exe was not compiled with msvc, it was complied with gcc / mingw (same as avcodec.dll)
Thanks,
Dan | Alignment of variables in memory (a short history).
In the past computers had an 8 bits databus. This means, that each clock cycle 8 bits of information could be processed. Which was fine then.
Then came 16 bit computers. Due to downward compatibility and other issues, the 8 bit byte was kept and the 16 bit word was introduced. Each word was 2 bytes. And each clock cycle 16 bits of information could be processed. But this posed a small problem.
Let's look at a memory map:
```
+----+
|0000|
|0001|
+----+
|0002|
|0003|
+----+
|0004|
|0005|
+----+
| .. |
```
At each address there is a byte which can be accessed individually.
But words can only be fetched at even addresses. So if we read a word at 0000, we read the bytes at 0000 and 0001. But if we want to read the word at position 0001, we need two read accesses. First 0000,0001 and then 0002,0003 and we only keep 0001,0002.
Of course this took some extra time and that was not appreciated. So that's why they invented alignment. So we store word variables at word boundaries and byte variables at byte boundaries.
For example, if we have a structure with a byte field (B) and a word field (W) (and a very naive compiler), we get the following:
```
+----+
|0000| B
|0001| W
+----+
|0002| W
|0003|
+----+
```
Which is not fun. But when using word alignment we find:
```
+----+
|0000| B
|0001| -
+----+
|0002| W
|0003| W
+----+
```
Here memory is sacrificed for access speed.
You can imagine that when using double word (4 bytes) or quad word (8 bytes) this is even more important. That's why with most modern compilers you can chose which alignment you are using while compiling the program. | Some CPU architectures require specific alignment of various datatypes, and will throw exceptions if you don't honor this rule. In standard mode, x86 doesn't require this for the basic data types, but can suffer performance penalties (check www.agner.org for low-level optimization tips).
However, the [SSE](http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions "SSE") instruction set (often used for high-performance) audio/video procesing has strict alignment requirements, and will throw exceptions if you attempt to use it on unaligned data (unless you use the, on some processors, much slower unaligned versions).
Your issue is **probably** that one compiler expects the *caller* to keep the stack aligned, while the other expects *callee* to align the stack when necessary.
**EDIT**: as for why the exception happens, a routine in the DLL probably wants to use SSE instructions on some temporary stack data, and fails because the two different compilers don't agree on calling conventions. | what is "stack alignment"? | [
"",
"c++",
"data-structures",
"mingw",
"visual-c++",
"compiler-construction",
""
] |
I am working on a MCQ module and I need to fetch random questions from my database. The problem is that I seem to get duplicates. | If you're fetching them from database, use SQL to do your job. e.g. fetching 20 random questions (without repeating):
```
SELECT * FROM questions ORDER BY RAND() LIMIT 20
``` | Sounds like you want to shuffle the questions, not randomize access to them. So your algorithm would be something like this.
1. Get the all question (or question keys) you want to display.
2. Shuffle them
3. Retrieve/ display in them in the shuffled order
for shuffling check out: [Fisher-Yates shuffle algorithm](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle) | How can I generate unique random numbers in PHP? | [
"",
"php",
"prng",
""
] |
It seems to me, from both personal experience and SO questions and answers, that SQL implementations vary substantially. One of the first issues for SQL questions is: What dbms are you using?
In most cases with SQL there are several ways to structure a given query, even using the same dialect. But I find it interesting that the relative portability of various approaches is frequently not discussed, nor valued very highly when it is.
But even disregarding the likelihood that any given application may or not be subject to conversion, I'd think that we would prefer that our skills, habits, and patterns be as portable as possible.
In your work with SQL, how strongly do you prefer standard SQL syntax? How actively do you eschew propriety variations? Please answer without reference to proprietary preferences for the purpose of perceived better performance, which most would concede is usually a sufficiently legitimate defense. | We take it very seriously at our shop. We do not allow non-standard SQL or extensions unless they're supported on ALL of the major platforms. Even then, they're flagged within the code as non-standard and justifications are necessary.
It is not up to the application developer to make their queries run fast, we have a clear separation of duties. The query is to be optimized only by the DBMS itself or the DBAs tuning of the DBMS.
Real databases, like DB2/z :-), process standard SQL plenty fast.
The reason we enforce this is to give the customer choice. They don't like the idea of being locked into a specific vendor any more than we do. | I vote against standard/vendor independent sql
* Only seldom the database is actually switched.
* There is no single database that fully conforms to the current sql standard. So even when you are standard conform, you are not vendor independent.
* vendor differences go beyond sql syntax. Locking behaviour is different. Isolation levels are different.
* database testing is pretty tough and under developed. No need to make it even harder by throwing multiple vendors in the game, if you don't absolutly need it.
* there is a lot of power in the vendor specific tweaks. (think 'limit', or 'analytic functions', or 'hints' )
So the quintessence:
* If there is no requirement for vendor independence, get specialised for the vendor you are actually using.
* If there is a requirement for vendor independence make sure that who ever pays the bill understands, that this will cost money. Make sure you have every single RDBMS available for testing. And use it too.
* Put every piece of sql in a special layer, which is pluggable, so you can use the power of the database AND work with different vendors
* Only where the difference is a pure question of syntax go with the standard, e.g. using the oracle notation for (outer) joins vs the ANSI standard syntax. | How Important is SQL Portability? | [
"",
"sql",
"portability",
""
] |
I'm working on a php project, and I want to run code that's fetched from a MySQL database. There's no chance of unsafe code being injected, so the only thing I'm worried about is performace. Should I use eval() so I can directly run the code, or parse it so that call\_user\_func() runs it instead?
For example, if the code I fetched was "myfunc(1,2,3); anotherFunc(3,2,1);"
I can eval() it directly to run the code.
But for call\_user\_func(), I'd have to parse the string so that it can be ran. So which is the better function to use in this case? | As a general rule, i always try to stay as far away from eval() as possible.
This case, however, looks like a good candidate for it.
You say *"There's no chance of unsafe code being injected"*, so the big question is: is there a chance of unworking code being in the database?
If not, eval() is the solution, but if there is then proper parsing and error logging/etc might be a safer bet. (i believe using call\_user\_func\_array() is faster in theory, so any parsing overhead might become negligible) | Storing PHP in the database is a bad design smell in itself; even though in this case you are pretty sure it can never contain unsafe code, it is always good to minimize the number of assumptions or defenses like that you have to make. If you store PHP code in the database, then an attack in which an attacker gains access to your database quickly becomes a lot more serious, turning into an attack in which an attacker can run arbitrary code! I know that having your database compromised like this is highly unlikely, but nonetheless it is good security practice not to let even an unlikely situation compromise your system more than it needs to.
[Many people agree](https://stackoverflow.com/questions/233030/worst-php-practice-found-in-your-experience/234021#234021) that eval() should always, without exception, be avoided in PHP code. There's always an alternative.
In this case, however, I think that I would have to say that using eval() would be the best solution for you, because you are already storing PHP code in the DB, so using eval() is not going to increase your risk any further than that.
I would, however, recommend that
1. You try to validate the code before you eval() it, by being conservative in what you allow. Assume that somehow an attacker got into your database even thought that is unlikely.
2. You at least give some serious thought to rewriting your application so that PHP code is not stored in a database. If you are storing complex data structures, think about something like JSON or even XML instead. Safe parsers exist for these.
I'm sorry if this answer seems a bit reactionary; I just happen to feel this sort of thing is very important. | Should I use eval() or call_user_func()? | [
"",
"php",
"eval",
""
] |
In a software development class at my university, the teacher kept mentioning that on a quiz we needed to make sure that a field returned by a getter needed to be "protected." I guess she meant that nothing outside the class should be able to change it. She didn't give much more of an explanation than that.
For instance:
```
class Foo {
string[] bar = <some array contents>;
public string[] getBar() {
return bar;
}
}
```
Any code calling getBar would be able to modify the elements in that array. How do you prevent that from happening? I'm assuming that the object itself should be able to modify the array, just not anything outside the object.
This isn't homework help since the quiz is a couple of weeks old. I simply want to understand Java better since my teacher didn't explain very well.
Update: The teacher wouldn't merely allow us to use protected as the access modifier on the field. | You either use a collection and wrap it in Collections.unmodifiable\*() or you defensively copy your array, collection or object if its **mutable** (which arrays always are).
For example:
```
class Foo {
private String[] bar = <some array contents>;
public String[] getBar() {
return bar == null ? bar : Arrays.copyOf(bar);
}
}
```
What you have to watch out for is that this is a shallow copy (so is clone). Not sure what your teacher's problem with clone was. | Just to add to one of the previous answers, you want to make sure that with a collection you aren't using the clone() method to achieve what you are trying to achieve here. This creates a shallow copy of the collection only, all object references contained in the collection copy still point to the same objects as in the original, e.g. the objects in the collection copy can still be modified, even though the original collection cannot. Be sure you are making a deep copy of a returned collection if this is what you are trying to do. | In Java, Prevent a field from being changed after being returned by instance method | [
"",
"java",
""
] |
In PHP, will these always return the same values?
```
//example 1
$array = array();
if ($array) {
echo 'the array has items';
}
// example 2
$array = array();
if (count($array)) {
echo 'the array has items';
}
```
Thank you! | From <http://www.php.net/manual/en/language.types.boolean.php>, it says that an empty array is considered FALSE.
---
(Quoted):
When converting to boolean, the following values are considered FALSE:
* the boolean FALSE itself
* the integer 0 (zero)
* the float 0.0 (zero)
* the empty string, and the string "0"
* **an array with zero elements**
* an object with zero member variables (PHP 4 only)
* the special type NULL (including unset variables)
* SimpleXML objects created from empty tags
---
Since
* a count() of > 0 IS NOT FALSE
* a filled array IS NOT FALSE
then both cases illustrated in the question will always work as expected. | Those will always return the same value, but I find
```
$array = array();
if (empty($array)) {
echo 'the array is empty';
}
```
to be a lot more readable. | PHP Does if (count($array)) and if ($array) mean the same thing? | [
"",
"php",
"arrays",
""
] |
In JavaScript, it is possible to declare multiple variables like this:
```
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
```
...or like this:
```
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
```
Is one method better/faster than the other? | The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.
With the second way, it is annoying to remove the first or last declaration because they start from the `var` keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma. | Besides maintainability, the first way eliminates possibility of accident global variables creation:
```
(function () {
var variable1 = "Hello, World!" // Semicolon is missed out accidentally
var variable2 = "Testing..."; // Still a local variable
var variable3 = 42;
}());
```
While the second way is less forgiving:
```
(function () {
var variable1 = "Hello, World!" // Comma is missed out accidentally
variable2 = "Testing...", // Becomes a global variable
variable3 = 42; // A global variable as well
}());
``` | Declaring multiple variables in JavaScript | [
"",
"javascript",
"performance",
"variables",
"declaration",
""
] |
I'm getting an error in Visual C++ that is giving me a really hard time.
The error is error c2143 reading: syntax error: missing ')' before 'constant'
My code line is:
```
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth);
```
I have #include at the beginning of the file which should define the floor(double) function.
a bit more explanation of the variables.
double depth is a member variable of the class which this line can be found in.
int i is an incrementing index value.
double t is an incrementing value.
What they do is really unimportant, but I wanted to clarify that all three are already defined as variables of basic types.
I've gone through and verified that all the parentheses match up. I'm kind of at a loss as to what 'constant' the compiler is referring to. Any ideas? | I'm not quite sure if this is the same error that the compiler is giving you, but you have to put a '\*' sign in front of the second '2' so that this:
```
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth);
```
Becomes this:
```
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) * 2 * depth);
``` | Other posters have shown you the actual error in the statement, but please, split that up into multiple sub-statements that more clearly show what you are trying to do mathematically, because that function is going to cause you headaches in the future if you don't! | Visual C++ error C2143: syntax error: missing ')' before 'constant' | [
"",
"c++",
"visual-studio",
"syntax-error",
""
] |
I need to send out an email with multiple image attachments from PHP. I currently have a test set up that uses two hard coded images. I compile the email with al the necessary headers and send it out. However, when I receive it, it only shows the first image as an attachment. The second image seems to be ignored (tested with both Groupwise and Gmail).
When I view the source of my email the following is what I see after the by the server generated headers. Apparently both attachments (images) are in there but only the first one is showing up as an attachment.
Any help would be greatly appreciated.
```
This is a multi-part message in MIME format.
--==Multipart_Boundary_x38e1b83d34375e183a2fdcd6a9c001f8x
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
my message text
--==Multipart_Boundary_x38e1b83d34375e183a2fdcd6a9c001f8x
Content-Type: image/gif;
name="image1.gif"
Content-Disposition: attachment;
filename="image1.gif"
Content-Transfer-Encoding: base64
iVBORw0KGgoAAAANSUhEUgAAABEAAAAMCAIAAAALR8HoAAABgElEQVQoFZWQzSuEURTG7z3n3Pt+
*[-- snip --]*
SaHPETExQ6HQ0BB4Z8FwTr/KHVc/AJ98jIf2BGdKAAAAAElFTkSuQmCC
--==Multipart_Boundary_x38e1b83d34375e183a2fdcd6a9c001f8x--
--==Multipart_Boundary_x38e1b83d34375e183a2fdcd6a9c001f8x
Content-Type: image/gif;
name="image2.gif"
Content-Disposition: attachment;
filename="image2.gif"
Content-Transfer-Encoding: base64
iVBORw0KGgoAAAANSUhEUgAAAKMAAAAyCAIAAAC/NPwxAAAAA3NCSVQICAjb4U/gAAAACXBIWXMA
*[-- snip --]*
yh4+kv39P/vticlfC0Muodov+5posktKGGb7/2pscsAoKykp2W8fTH4Exv1tEEbD3NNGwbi/y8do
mNnbKPwf2Oju7uv54J4AAAAASUVORK5CYII=
--==Multipart_Boundary_x38e1b83d34375e183a2fdcd6a9c001f8x--
``` | Going from memory:
```
SaHPETExQ6HQ0BB4Z8FwTr/KHVc/AJ98jIf2BGdKAAAAAElFTkSuQmCC
--==Multipart_Boundary_x38e1b83d34375e183a2fdcd6a9c001f8x--
^^^ DELETE THIS LINE ^^^
--==Multipart_Boundary_x38e1b83d34375e183a2fdcd6a9c001f8x
```
You shouldn't have two boundaries next to each other, and the "--" at the end is only for the end of the **last** part. | If it is okay for your purpose you could try to use [PHPMailer](http://phpmailer.codeworxtech.com/) (licensed under [LGPL](http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License)). It is very very easy to use and handles all the complicated mail stuff for you. | Compiling email with multiple attachments in PHP | [
"",
"php",
"email",
"attachment",
""
] |
In Tomcat (and some other servlet containers) I can store information about my JDBC DataSource in `META-INF/context.xml`. This is very useful.
However, the settings for my JDBC DataSource can be different in my development and production environments. I'd like to know how other people deal with these differences in an elegant way, specifically how can I set up a `context.xml` for my development environment and one for my production environment in the most hassle-free manner. | You can create different files for specific builds. For example, create:
development.context.xml
production.context.xml
Then, you can control which context file is used in your build.xml file. Basically, setup a prompt for which type of build you would like to use. When you select development, it uses the development context file. When you select production, it uses the production context file. | I would do the same as Kevin mentioned. If you're using Maven you would use "profiles". | How to Use Different META-INF/context.xml Files For Development and Production Environments | [
"",
"java",
"tomcat",
"jdbc",
"jndi",
""
] |
I have a simple View and I wish to add a [JQuery DatePicker JavaScript](http://jqueryui.com/demos/datepicker/) to this view (and not *every* view, via a masterpage).
I'm not sure what is the best way to do this.
Second, I'm conscious of where/when my JavaScript loads. I'm a fan of YSlow and it recommends that I add any scripts to the bottom of the page, which I do.
So, how could I do both?
Here's the view:
```
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<% using (Html.BeginForm()) {%>
<p>
<label for="StartDate">Start Date:</label>
<!-- JQuery DatePicker to be added, here. -->
</p>
<% } %>
</asp:Content>
``` | One way is put a content placeholder at the bottom of your master page, then the specific slave page that needs the javascript can specify the placeholders contents as the required javascript. Other pages that don't need the javascript simply don't specify any content for the placeholder. | In ASP.NET MVC3, you can now use a RenderSection to achieve this, at least for simpler scenarios. Just add a RenderSection to the bottom of the layout page, and from your view fill in the appliation code
RenderSections: <http://www.dotnetcurry.com/ShowArticle.aspx?ID=636> | How do I add JavaScript to an ASP.NET MVC View? | [
"",
"javascript",
"jquery",
"asp.net-mvc",
"view",
""
] |
Is there a penalty for calling newInstance() or is it the same mechanism underneath?
How much overhead if any does newInstance() have over the new keyword\* ?
\*: Discounting the fact that newInstance() implies using reflection. | In a real world test, creating 18129 instances of a class via "Constuctor.newInstance" passing in 10 arguments -vs- creating the instances via "new" the program took no measurable difference in time.
This wasn't any sort of micro benchmark.
This is with JDK 1.6.0\_12 on Windows 7 x86 beta.
Given that Constructor.newInstance is going to be very simlilar to Class.forName.newInstance I would say that the overhead is hardly anything given the functionality that you can get using newInstance over new.
As always you should test it yourself to see. | Be wary of microbenchmarks, but I found [this blog entry](http://www.thoughtsabout.net/blog/archives/000036.html) where someone found that `new` was about twice as fast as `newInstance` with JDK 1.4. It sounds like there is a difference, and as expected, reflection is slower. However, it sounds like the difference may not be a dealbreaker, depending on the frequency of new object instances vs how much computation is being done. | newInstance() vs new | [
"",
"java",
"performance",
"reflection",
""
] |
Does anyone know of a free decompiler that can decompile an entire Jar file instead of a single class? I have a problem with sub classes like name$1.class name$2.class name.class | 2023: [splashout](https://stackoverflow.com/users/1048376/splashout) suggests in [the comments](https://stackoverflow.com/questions/647116/how-to-decompile-a-whole-jar-file/647140?noredirect=1#comment135449931_647140) the [`Vineflower/vineflower`](https://github.com/Vineflower/vineflower) decompiler ([releases](https://github.com/Vineflower/vineflower/releases)), renaming from Quiltflower to Vineflower.
```
java -jar vineflower.jar -dgs=1 c:\Temp\binary\library.jar c:\Temp\souce
```
---
2022 update: [**QuiltMC/quiltflower**](https://github.com/QuiltMC/quiltflower) is the latest [most advanced Java decompiler](https://www.reddit.com/r/java/comments/ue8u59/new_open_source_java_decompiler/):
Quiltflower is a modern, general purpose decompiler focused on improving code quality, speed, and usability.
Quiltflower is a fork of [Fernflower](https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine) and Forgeflower.
> Changes include:
>
> * New language features (Try with resources, switch expressions, pattern matching, and more)
> * Better control flow generation (loops, try-catch, and switch, etc.)
> * More configurability
> * Better error messages
> * Javadoc application
> * Multithreading
> * Optimization
> * Many other miscellaneous features and fixes
>
> Originally intended just for use with the QuiltMC toolchain with Minecraft, Quiltflower quickly expanded to be a general purpose java decompiler aiming to create code that is as accurate and clean as possible.
>
> If the name sounds familiar it's because Quiltflower is a fork of [Fernflower](https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine), the (in)famous decompiler that was developed by Stiver, maintained by Jetbrains, and became the default decompiler in Intellij IDEA.
> Fernflower also quickly found its way into many other tools.
>
> Over the past year, Quiltflower has added support for features such as modern string concatenation, a code formatter, sealed classes, pattern matching, switch expressions, try-with-resources, and more. Quiltflower also focuses on the code quality of the decompiled output, and takes readability very seriously.
See [output examples](https://gist.github.com/SuperCoder7979/c7171b0e34b6eccf0b9f1c37030867dc).
> Runs nice with [jbang](https://www.jbang.dev/)
>
> ```
> https://github.com/QuiltMC/quiltflower/releases/download/1.8.1/quiltflower-1.8.1.jar
> ```
Or:
> ```
> java -jar quiltflower.jar -dgs=1 c:\Temp\binary\library.jar c:\Temp\binary\Boot.class c:\Temp\source\
> ```
---
2009: [JavaDecompiler](https://java-decompiler.github.io/) can do a good job with a jar: since 0.2.5, All files, in JAR files, are displayed.

See also [the question "How do I “decompile” Java class files?"](https://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files/272595#272595).
The JD-Eclipse doesn't seem to have changed since late 2009 though (see [Changes](http://java.decompiler.free.fr/?q=changes/jdeclipse)).
So its integration with latest Eclipse (3.8, 4.2+) might be problematic.
JD-Core is actively maintained.
Both are the result of the fantastic work of (SO user) [**Emmanuel Dupuy**](https://stackoverflow.com/users/37785/emmanuel-dupuy).
---
2018: A more modern option, mentioned [in the comments](https://stackoverflow.com/questions/647116/how-to-decompile-a-whole-jar-file/647140?noredirect=1#comment89196907_647140) by [David Kennedy Araujo](https://stackoverflow.com/users/1697026/david-kennedy-araujo):
[**JetBrains/intellij-community/plugins/java-decompiler/engine**](https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine)
> Fernflower is the first actually working analytical decompiler for Java and probably for a high-level programming language in general.
>
> ```
> java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>
>
> java -jar fernflower.jar -hes=0 -hdc=0 c:\Temp\binary\ -e=c:\Java\rt.jar c:\Temp\source\
> ```
See also [How to decompile to java files intellij idea](https://stackoverflow.com/questions/28389006/how-to-decompile-to-java-files-intellij-idea) for a command working with recent IntelliJ IDEA.
---
2022 update: [Florian Wendelborn](https://stackoverflow.com/users/2857873/florian-wendelborn) suggests in [the comments](https://stackoverflow.com/questions/647116/how-to-decompile-a-whole-jar-file?noredirect=1#comment126287968_647116)
> this one works well: [jdec.app](https://jdec.app/) from [Leonardo Santos](https://github.com/leonardosnt). | First of all, it's worth remembering that all Java archive files (`.jar`/`.war`/etc...) are **all basically just fancy`.zip` files**, with a few added manifests and metadata.
Second, to tackle this problem I personally use several tools which handle this problem on all levels:
* [**Jad**](https://varaneckas.com/jad/) + [**Jadclipse**](http://jadclipse.sourceforge.net/wiki/index.php/Main_Page) while working in IDE for decompiling `.class` files
* [**WinRAR**](http://www.rarlab.com/), my favorite compression tool natively supports Java archives (again, see first paragraph).
* [**Beyond Compare**](http://www.scootersoftware.com/), my favorite diff tool, when configured correctly can do on-the-fly comparisons between any archive file, including `jar`s. Well worth a try.
The advantage of all the aforementioned, is that I do not need to hold any other external tool which clutters my work environment. Everything I will ever need from one of those files can be handled inside my IDE or diffed with other files natively. | How to decompile a whole Jar file? | [
"",
"java",
"jar",
"decompiler",
""
] |
```
const int MIN_NUMBER = 4;
class Temp
{
public:
Temp(int x) : X(x)
{
}
bool getX() const
{
try
{
if( X < MIN_NUMBER)
{
//By mistake throwing any specific exception was missed out
//Program terminated here
throw ;
}
}
catch (bool bTemp)
{
cout<<"catch(bool) exception";
}
catch(...)
{
cout<<"catch... exception";
}
return X;
}
private:
int X;
};
int main(int argc, char* argv[])
{
Temp *pTemp = NULL;
try
{
pTemp = new Temp(3);
int nX = pTemp->getX();
delete pTemp;
}
catch(...)
{
cout<<"cought exception";
}
cout<<"success";
return 0;
}
```
In above code, **throw false** was intended in getX() method but due to a human error(!) **false** was missed out. The innocent looking code crashed the application.
My question is why does program gets terminated when we throw "nothing”?
I have little understanding that `throw;` is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation? | This is expected behaviour. From the C++ standard:
> If no exception is presently being
> handled, executing a throw-expression
> with no operand calls
> terminate()(15.5.1).
As to why the compiler can't diagnose this, it would take some pretty sophisticated flow analysis to do so and I guess the compiler writers would not judge it as cost-effective. C++ (and other languages) are full of possible errors that *could* in theory be caught by the compiler but in practice are not. | To elaborate on Neil's answer:
`throw;` by itself will attempt to re-raise the current exception being unwind -- if multiple are being unwound, it attempts to rethrow the most recent one. If none are being unwound, then terminate() is called to signal your program did something bogus.
As to your next question, why the compiler doesn't warn with `throw;` outside a catch block, is that the compiler can't tell at compile-time whether the `throw;` line may be executing in the context of a catch block. Consider:
```
// you can try executing this code on [http://codepad.org/pZv9VgiX][1]
#include <iostream>
using namespace std;
void f() {
throw 1;
}
void g() {
// will look at int and char exceptions
try {
throw;
} catch (int xyz){
cout << "caught int " << xyz << "\n";
} catch (char xyz){
cout << "caught char " << xyz << "\n";
}
}
void h() {
try {
f();
} catch (...) {
// use g as a common exception filter
g();
}
}
int main(){
try {
h();
} catch (...) {
cout << "some other exception.\n";
}
}
```
In this program, `g()` operates as an exception filter, and can be used from `h()` and any other function that could use this exception handling behavior. You can even imagine more complicated cases:
```
void attempt_recovery() {
try{
// do stuff
return;
} catch (...) {}
// throw original exception cause
throw;
}
void do_something() {
for(;;) {
try {
// do stuff
} catch (...) {
attempt_recovery();
}
}
}
```
Here, if an exception occurs in do\_something, the recovery code will be invoked. If that recovery code succeeds, the original exception is forgotten and the task is re-attempted. If the recovery code fails, that failure is ignored and the previous failure is re-throw. This works because the `throw;` in `attempt_recovery` is invoked in the context of `do_something`'s catch block. | why does throw "nothing" causes program termination? | [
"",
"c++",
"exception",
""
] |
```
InetAddress serverAddr = InetAddress.getByName(serverAddress);
String hostname = serverAddr.getCanonicalHostName();
Socket socket = new Socket(serverAddr, portNumber);
// Freezes before this line if the server is unavailable
socket.setSoTimeout(3000);
```
Does anyone know how to implement the check of server availability or prevent the freezing? | By using the [two-argument constructor](http://java.sun.com/javase/6/docs/api/java/net/Socket.html#Socket(java.net.InetAddress,%20int)), you tell Java to connect immediately. What you are looking for is likely
```
Socket socket = new Socket();
// Configure socket here
socket.connect(new InetSocketAddress(serverAddr, portNumber), 3000);
if (! socket.isConnected()) {
// Error handling
} else {
// Use socket
}
```
This will still block for 3s though. If you want to prevent that, use a thread for the connection. | I'm going to advise the obvious: Use a seperate thread to do this in. The thread can freeze without freezing the application. | How to prevent application freeze if server unavailable? | [
"",
"java",
"sockets",
"networking",
""
] |
After one hour of trying to find a bug in my code I've finally found the reason. I was trying to add a very small float to 1f, but nothing was happening. While trying to figure out why I found that adding that small float to 0f worked perfectly.
Why is this happening?
Does this have to do with 'orders of magnitude'?
Is there any workaround to this problem?
Thanks in advance.
Edit:
Changing to double precision or decimal is not an option at the moment. | Because precision for a single-precision (32 bit) floating-point value is around 7 digits after the decimal point. Which means the value you are adding is essentially zero, at least when added to `1`. The value itself, however, can effortlessly stored in a float since the exponent is small in that case. But to successfully add it to `1` you have to use the exponent of the larger number ... and then the digits after the zeroes disappear in rounding.
You can use `double` if you need more precision. Performance-wise this shouldn't make a difference on today's hardware and memory is often also not as constrained that you have to think about every single variable.
**EDIT:** As you stated that using `double` is not an option you could use [Kahan summation](http://en.wikipedia.org/wiki/Kahan_summation), as [akuhn](https://stackoverflow.com/users/24468/akuhn) pointed out in a comment.
Another option may be to perform intermediary calculations in double-precision and afterwards cast to `float` again. This will only help, however, when there are a few more operations than just adding a very small number to a larger one. | [Floating-point arithmetic](http://en.wikipedia.org/wiki/Floating_point#Floating-point_arithmetic_operations) | Why 1.0f + 0.0000000171785715f returns 1f? | [
"",
"c#",
".net",
"floating-point",
"precision",
""
] |
In IE 6 select control(combo box) is displaying on top of menus. I checked some Javascript menus, [mmmenu](http://www.leigeber.com/2008/11/drop-down-menu/), but all are getting under select control. It's not fixable by assigning Z-Index. Is there any other solution. | This is a well-known bug with IE6 with trying to absolutely position divs on top of select controls.
There are workarounds involving iframe shims, but there is no good answer. The iframe shim answer is to place an iframe underneath whatever div you're trying to place above a select, with the iframe being the same size. Unfortunately, this is a huge pain in the ass.
I suggest using a javascript menu system which already uses iframe shims, such as [YUI menus](http://developer.yahoo.com/yui/menu/ "yui menus") (and I assume jQuery). | Most of the major javascript libraries have easy to implement solutions to this problem. We use jQuery, and the [bgiframe plugin](http://plugins.jquery.com/project/bgiframe) is very easy-to-use and solves the problem. | IE 6 select controls(Combo Box) over menu | [
"",
"javascript",
"xhtml",
"internet-explorer-6",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.