Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
If you have a Bitmap object that needs to be passed to numerous methods (about 10), and finally to an event where it shall finally be disposed of after it's used, would it be (performance wise) beneficial to pass it to every one of those methods by reference instead of value?
Passing by value, the object is copied, passing by reference its not.
(Performance is critical in this situation. The application needs to run as fast as possible.) | Bitmap is a reference type. Passing a reference type by value does not copy the object, merely the reference to the object. There would be no performance benefit to passing the Bitmap by reference instead of by value. | Since Bitmap is a reference type, there is no practical difference for performance in this scenario as it is already being passed by reference to the method.
I'd recommend [Jon Skeet's article on the subject](http://www.jonskeet.uk/csharp/parameters.html) for a thorough explanation of how "by reference" and "by value" work in C#. | C# 'ref' keyword, performance | [
"",
"c#",
"performance",
"ref",
""
] |
Just looking at Python generators, real impressed with them, but are there any things not to use them for? I was thinking of past C coding where reading from a file, or user actions would be areas. For example, could the generator be used to prompt the user for input (base data entry?) and the calling function process that input? are there any performance or cleanup issues to be concerned with? | One problem with generators is that they get "consumed." This means that if you need to iterate over the sequence again, you need to create the generator again.
If lazy evaluation is an issue, then you probably don't want a generator expression. For example, if you want to perform all your calculations up front (e.g. so that you can release a resource), then a list comprehension or for loop is probably best.
If you use [psyco](http://psyco.sourceforge.net/), you'll get a significant speed increase for list expressions and for loops, but not for generators.
Also rather obviously, if you need to get the length of your sequence up front, then you don't want a generator. | Generators don't persist well.
Generally, you get an error trying to persist a generator object.
```
>>> def generatorForEvenKeys( aDictionary ):
for k in aDictionary:
if k % 2 == 0: yield aDictionary[k]
>>> x = generatorForEvenKeys( someDictionary )
>>> pickle.dump(x,file('temp.dat','wb'))
```
Gets you the following error:
```
TypeError: can't pickle generator objects
``` | Python Generator - what not to use it for | [
"",
"python",
""
] |
Over the months I've written some nice generic enough functionality that I want to build as a library and link dynamically against rather than importing 50-odd header/source files.
The project is maintained in Xcode and Dev-C++ (I do understand that I might have to go command line to do what I want) and have to link against OpenGL and SDL (dynamically in SDL's case). Target platforms are Windows and OS X.
What am I looking at at all?
* What will be the entry point of my
library if it needs one?
* What do I have to change in my code?
(calling conventions?)
* How do I release it? My understanding
is that headers and the compiled
library (.dll, .dylib(, .framework),
whatever it'll be) need to be
available for the project -
especially as template functionality
can not be included in the library by
nature.
* What else I need to be aware of? | I'd recommend building as a statc library rather than a DLL. A lot of the issues of exporting C++ functions and classes go away if you do this, provided you only intend to link with code produced by the same compiler you built the library with.
Building a static library is very easy as it is just an collection of .o/.obj files - a bit like a ZIP file but without compression. There is no need to export anything - just include the library in the list of files that your application links with. To access specific functions or classes, just include the relevant header file. Note you can't get rid of header files - the C++ compilation model, particularly for templates, depends on them. | It can be problematic to export a C++ class library from a dynamic library, but it is possible.
You need to mark each function to be exported from the DLL (syntax depends on the compiler). I'm poking around to see if I can find how to do this from xcode. In VC it's \_\_declspec(dllexport) and in CodeWarrior it's #pragma export on/#pragma export off.
This is perfectly reasonable if you are only using your binary in-house. However, one issue is that C++ methods are named differently by different compilers. This means that nobody who uses a different compiler will be able to use your DLL, unless you are only exporting C functions.
Also, you need to make sure the calling conventions match in the DLL and the DLL's client. This either means you should have the same *default* calling convention flag passed to the compiler for both the DLL or the client, or better, explicitly set the calling convention on each exported function in the DLL, so that it won't matter what the default is for the client.
This article explains the naming issue:
<http://en.wikipedia.org/wiki/Name_decoration> | Building C++ source code as a library - where to start? | [
"",
"c++",
"entity-framework",
"dynamic-linking",
""
] |
Can anyone comment with their opinion on the best way to resolve the following issue? I've tried init blocks and initializing the field in the constructor, but neither get called before the overridden method tries to clear it.
```
class TestRunner {
public static void main(String[] args) {
ftw ftw = new ftw();
ftw.dontPanic();
}
}
class wtf {
wtf(){
this.dontPanic();
}
void dontPanic() {
System.out.println("super don't panic");
}
}
class ftw extends wtf {
final HashSet variableOfDoom = new HashSet();
ftw(){
super();
}
void dontPanic() {
super.dontPanic();
System.out.println("sub don't panic");
variableOfDoom.clear(); //This line prints a null pointer exception, because the field hasn't been intialized yet.
}
}
``` | This is why they recommend you don't call non-`final` methods from inside a constructor. `private` methods are also safe, since they can't be overriden.
Assuming that you can't follow that sound advice, for some reason, here are some other observations that might help:
* I'm assuming you simplified for the sake of the example, but the call to `.clear()` doesn't really accomplish anything in the example; you may be able to just delete it.
* It's tough to say without seeing the actual program in total, but you may be able to skate by with assigning the variable a new `HashSet` instead of invoking `.clear()`. | Here's the problem: Your execution flow looks like this:
```
main
->ftw()
->wtf()
->wtf.dontPanic()
```
But since method invocations are determined at runtime in Java, `ftw.dontPanic()` is the method that's really being called. And `variableOfDoom` won't be set until the constructor completes, but the constructor will never complete because of the exception.
The solution is not to do work in your constructor (at least not with non-`private` non-`final` methods). | NullPointerException with an override method | [
"",
"java",
""
] |
What is it and how to use?
I need that as I have a timer that inserts into DB every second, and I have a shared resource between timer handler and the main thread.
I want to gurantee that if the timer handler takes more than one second in the insertion the waited threads should be executed in order.
This is a sample code for my timer handler:
```
private void InsertBasicVaraibles(object param)
{
try
{
DataTablesMutex.WaitOne();//mutex for my shared resources
//insert into DB
}
catch (Exception ex)
{
//Handle
}
finally
{
DataTablesMutex.ReleaseMutex();
}
}
```
But currently the mutex does not guarantee any order. | You'll need to write your own class to do this, I found this example (pasted because it looks as though the site's domain has lapsed):
```
using System.Threading;
public sealed class QueuedLock
{
private object innerLock;
private volatile int ticketsCount = 0;
private volatile int ticketToRide = 1;
public QueuedLock()
{
innerLock = new Object();
}
public void Enter()
{
int myTicket = Interlocked.Increment(ref ticketsCount);
Monitor.Enter(innerLock);
while (true)
{
if (myTicket == ticketToRide)
{
return;
}
else
{
Monitor.Wait(innerLock);
}
}
}
public void Exit()
{
Interlocked.Increment(ref ticketToRide);
Monitor.PulseAll(innerLock);
Monitor.Exit(innerLock);
}
}
```
Example of usage:
```
QueuedLock queuedLock = new QueuedLock();
try
{
queuedLock.Enter();
// here code which needs to be synchronized
// in correct order
}
finally
{
queuedLock.Exit();
}
```
[Source via archive.org](https://web.archive.org/web/20081220235523/http://www.jakubsloup.cz/Blog/z%C3%A1%C5%99%C3%AD-2008/Monitor/lock-which-remember-order-in-C--to-simulate-FIFO.aspx) | Just reading Joe Duffy's "Concurrent Programming on Windows" it sounds like you'll *usually* get FIFO behaviour from .NET monitors, but there are some situations where that won't occur.
Page 273 of the book says: "Because monitors use kernel objects internally, they exhibit the same roughly-FIFO behavior that the OS synchronization mechanisms also exhibit (described in the previous chapter). Monitors are unfair, so if another thread sneaks in and acquires the lock before an awakened waiting thread tries to acquire the lock, the sneaky thread is permitted to acquire the lock."
I can't immediately find the section referenced "in the previous chapter" but it *does* note that locks have been made deliberately unfair in recent editions of Windows to improve scalability and reduce *lock convoys*.
Do you definitely need your lock to be FIFO? Maybe there's a different way to approach the problem. I don't know of any locks in .NET which are guaranteed to be FIFO. | Is there a synchronization class that guarantee FIFO order in C#? | [
"",
"c#",
"synchronization",
""
] |
I have three sets of numbers, a measurement (which is in the range 0-1 inclusive) two errors (positive and negative. These numbers should be displayed consistently to the number of significant figures, rounded up, which corresponds to the first non-zero entry in either of the number.
This requirement is skipped on the measurement if it is one (i.e. only the figures in the errors need be considered). For example:
```
0.95637 (+0.00123, -0.02935) --> 0.96 +0.00 -0.03
1.00000 (+0.0, -0.0979) --> 1.0 +0.0 -0.1 (note had to truncate due to -ve error rounding up at first significant digit)
```
Now, getting at the first non-zero digit is easy by taking log10(num), but I'm having an idiotic moment trying to get stripping and rounding working in a clean fashion.
All data types are doubles, and language of choice is C++. All and any ideas welcome! | My C++ is rusty, but wouldn't the following do it:
```
std::string FormatNum(double measurement, double poserror, double negerror)
{
int precision = 1; // Precision to use if all numbers are zero
if (poserror > 0)
precision = ceil(-1 * log10(poserror));
if (negerror < 0)
precision = min(precision, ceil(-1 * log10(abs(negerror))));
// If you meant the first non-zero in any of the 3 numbers, uncomment this:
//if( measurement < 1 )
// precision = min(precision, ceil(-1 * log10(measurement)));
stringstream ss;
ss.setf(ios::fixed, ios::floatfield);
ss.precision( precision );
ss << measurement << " +" << poserror << " " << negerror ;
return ss.str();
}
``` | Using
```
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
```
before you output the numbers should do what you are looking for.
Edit: as an example
```
double a = 0.95637;
double b = 0.00123;
double c = -0.02935;
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout << a << endl;
cout << b << endl;
cout << c << endl;
```
will output:
```
0.96
0.00
-0.03
```
Further edit: you'll obviously have to adjust the precision to match your significant figures. | Correct formatting of numbers with errors (C++) | [
"",
"c++",
"formatting",
"numbers",
"rounding",
""
] |
How do I find out the user's "preferred web browser", if they're using Gnome desktop environment? (I want to open a webpage, I don't need to know which browser the user prefers.)
Some background:
I'm trying to open a browser window (my homepage) with my Java app.
1. if Java version is 1.6+, use Desktop.browse(url);
2. otherwise, use [BareBonesBrowserLaunch.openURL(url)](http://www.centerkey.com/java/browser/) - that means checking the environment and starting a browser with Runtime.getRuntime().exec()
Method 2 works on Windows just fine; and opens a browser on Linux. However, it's the first browser that it finds (in my case, looks for Firefox first). In Gnome desktop environment (e.g. Ubuntu Linux has that by default), you could set your "Preferred Applications" for e-mail, www browsing etc; I believe this information is accesible *somewhere*. How can I find out which is the user's preferred browser?
In other words: **where does Gnome store the "Preferred Browser" setting**? | The most portable way to open a file or URL in Linux desktop is `xdg-open`.
<http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html> | The "default browser" setting is in `~/.gconf/desktop/gnome/url-handlers/http/%gconf.xml` Here's mine:
```
<?xml version="1.0"?>
<gconf>
<entry name="command" mtime="1243616896" type="string">
<stringvalue>opera %s</stringvalue>
</entry>
</gconf>
```
The `<stringvalue/>` is the command I was looking for.
(Found this out after a while - and forgot to post the question.) | Respecting/reading the "Preferred Applications" settings in Gnome (Linux) | [
"",
"java",
"gnome",
""
] |
I'm trying to build the following block of code in a 1-file .cpp file:
```
#include <iostream>
#include <algorithm>
using namespace std;
class test
{
public:
int a[10];
int index;
test();
~test();
bool equals(int p);
void search();
};
test::test()
{
int temp[10] = {4, 9, 5, 6, 9, 10, 9, 255, 60, 0};
memcpy(a, temp, sizeof(temp));
index = -1;
}
bool test::equals(int p)
{
return p == 9;
}
void test::search()
{
int* p = std::find_if(a, a+10, &test::equals);
while (p != a+10)
{
cout<< *p;
index = p - a;
p = std::find_if(p+1, a+10, &test::equals);
}
}
int main(int argc, char *argv[])
{
test object;
object.search();
return 0;
}
```
I am getting an error as shown below, and I'm not sure exactly what's happening when I use the find\_if function in a member method of a class, and I'm getting this error whenever I am doing so.
```
1>c:\program files\microsoft visual studio 8\vc\include\algorithm(87) : error C2064: term does not evaluate to a function taking 1 arguments
1> c:\program files\microsoft visual studio 8\vc\include\algorithm(96) : see reference to function template instantiation '_InIt std::_Find_if(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=int *,
1> _Pr=bool (__thiscall test::* )(int)
1> ]
1> c:\testprogram\nomfc\main.cpp(32) : see reference to function template instantiation '_InIt std::find_if(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=int *,
1> _Pr=bool (__thiscall test::* )(int)
1> ]
``` | The `find_if` function expects an object which is callable as a function with no parameters. This is something like a free function, a function object or a static class function. You passed in the address of the `equals` member function which is none of these. You could resolve this by making the `equals` function a free function or a static function, since it does not require any members of the `test` instance.
```
// static
class test
{
public:
static bool equals(int p); // etc
};
int* p = std::find_if(a, a+10, &test::equals);
// free
bool equals(int p)
{
return p == 9;
}
int* p = std::find_if(a, a+10, equals);
```
If your real code example requires that it be a member function, then you need to pass in a function object that acts as a closure over the class instance. I favour using the Boost bind method for this, but there are other methods as well.
```
int* p = std::find_if(a, a+10, boost::bind(&test::equals, this, _1));
``` | `test::equals` is a member function, which has different pointer syntax from an ordinary function pointer. In particular, to call it, `find_if` would need an object of type `test`, which it doesn't have (it won't, for example, automatically call it on `this`, which I'm guessing is what you have in mind).
You can move the function `equals` outside the class `test`, and it should work. | find_if function build problems | [
"",
"c++",
"stl",
""
] |
how can i access the summary of a file like music file (any format) and edit it and especially the artwork of this file(the photo that are included in the file) and edit it too?
thanks. | You'll probably need to read up on the specification for whatever music file format you're using. Each music format has a different metadata format and compression/encoding scheme. Some formats might have libraries available for maniuplating the files, and some might have to be manipulated by hand.
For example, try searching google for "mp3 spec" or "mp3 file format" | May I recommend [TagLib Sharp](http://developer.novell.com/wiki/index.php/TagLib_Sharp) for mp3 tag editing. Very powerful and easy to use with clear documentation. | Edit music metadata with c# | [
"",
"c#",
".net",
"file-io",
"metadata",
""
] |
I am making most of my basic types in my app, immutable. But should the collections be immutable too? To me, this seems like a huge overhead unless I am missing something.
I am talking about collections to hold Point3 values, etc which can be added as it goes at different times. So if there are 1M values in a collection, and you needed to delete 1 of them, you would have to create the same collection all over again, right? | Eric Lippert has a series on Immutability in C#, and if you read it all the way through he implements a couple different immutable collections:
1. [Immutability in C# Part One: Kinds of Immutability](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability)
2. [Immutability in C# Part Two: A Simple Immutable Stack](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-two-a-simple-immutable-stack)
3. [Immutability in C# Part Three: A Covariant Immutable Stack](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-three-a-covariant-immutable-stack)
4. [Immutability in C# Part Four: An Immutable Queue](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-four-an-immutable-queue)
5. [Immutability in C# Part Five: LOLZ!](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-five-lolz)
6. [Immutability in C# Part Six: A Simple Binary Tree](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-six-a-simple-binary-tree)
7. [Immutability in C# Part Seven: More on Binary Trees](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-seven-more-on-binary-trees)
8. [Immutability in C# Part Eight: Even More On Binary Trees](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-eight-even-more-on-binary-trees)
9. [Immutability in C# Part Nine: Academic? Plus my AVL tree implementation](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-nine-academic-plus-my-avl-tree-implementation)
10. [Immutability in C# Part Ten: A double-ended queue](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-10-a-double-ended-queue)
11. [Immutability in C# Part Eleven: A working double-ended queue](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-eleven-a-working-double-ended-queue) | Immutable collections are great, especially if your app already leverages immutable types or semantics.
.NET just shipped their first [immutable collections](http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx), which I suggest you try out. | Immutable collections? | [
"",
"c#",
".net",
"immutability",
""
] |
I have a rich text editor that passes HTML to the server. That HTML is then displayed to other users. I want to make sure there is no JavaScript in that HTML. Is there any way to do this?
Also, I'm using ASP.NET if that helps. | The simplest thing to do would be to either strip out tags with a regex. Trouble is that you could do plenty of nasty things without script tags (e.g. imbed dodgy images, have links to other sites that have nasty Javascript) . Disabling HTML completely by convert the less than/greater than characters into their HTML entities forms (e.g. <) could also be an option.
If you want a more powerful solution, in the past I have used [AntiSamy](http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project_.NET) to sanitize incoming text so that it's safe for viewing. | The only way to *ensure* that some HTML markup does not contain any JavaScript is to filter it of all unsafe HTML tags and attributes, in order to prevent [Cross-Site Scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) (XSS).
However, there is in general no reliable way of *explicitly removing* all unsafe elements and attributes by their names, since certain browsers may interpret ones of which you weren't even aware at the time of design, and thus open up a security hole for malicious users. This is why you're much better off taking a **whitelisting** approach rather than a **blacklisting** one. That is to say, only allow HTML tags that you are *sure* are safe, and stripping all others by default. Indeed, only one accidentally permitted tag can make your website vulnerable to XSS.
---
## Whitelisting (good approach)
See this article on [HTML sanitisation](http://www.feedparser.org/docs/html-sanitization.html), which offers some specific examples of why you should whitelist rather than blacklist. Quote from that page:
> Here is an incomplete list of potentially dangerous HTML tags and attributes:
>
> * `script`, which can contain malicious script
> * `applet`, `embed`, and `object`, which can automatically download and execute malicious code
> * `meta`, which can contain malicious redirects
> * `onload`, `onunload`, and all other `on*` attributes, which can contain malicious script
> * `style`, `link`, and the `style` attribute, which can contain malicious script
[Here](http://software.open-xchange.com/OX6/doc/Html-Whitelist/ch01.html) is another helpful page that suggests a set of HTML tags & attributes as well as CSS attributes that are typically safe to allow, as well as recommended practices.
## Blacklisting (generally bad approach)
Although many website have in the past (and currently) use the blacklisting approach, there is almost never any true need for it. (The security risks invariably outweight the potential limitations whitelisting enforces with the formatting capabilities that are granted to the user.) You need to be very aware of its flaws.
For example, [this page](http://forums.tizag.com/showthread.php?t=3459) gives a list of what are supposedly "all" the HTML tags you might want to strip out. Just from observing it briefly, you should notice that it contains a very limited number of element names; a browser could easily include a proprietary tag that unwittingly allowed scripts to run on your page, which is essentially the main problem with blacklisting.
---
Finally, I would strongly recommend that you utilise an **HTML DOM library** (such as the well-known [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack)) for .NET, as opposed to RegEx to perform the cleaning/whitelisting, since it would be significantly more reliable. (It is quite possible to create some pretty crazy obfuscated HTML that can fool regexes! A proper HTML reader/writer makes the coding of the system much easier, anyway.)
Hopefully that should given you a decent overview of what you need to design in order to fully (or at least maximally) prevent XSS, and how it's critical that HTML sanitisation is performed with the unknown factor in mind. | Filtering JavaScript out of HTML | [
"",
"javascript",
"html",
"xss",
"filtering",
"sanitization",
""
] |
I'm looking for a way to debug a dynamically loaded jQuery document.ready function.
Obviously I can't just bring up the script panel and add a breakpoint with the mouse since the function does not exist there.
I've also tried adding "debugger;" to the function (without the quotes), but that did not do anything. I have ensured that the function is actually executed while I tried this.
Thanks for your help,
Adrian
**Edit:** I just noticed that Firebug actually breaks on debug. However, when it does so on a dynamically loaded script, it does not bring up the source code of that script as usual. Plus, the call stack ends right below my own code. I can bring up the implementation for document.ready via the call stack, but that does not really help. Is this a Firebug bug or have I missed something? | I just worked on this [similar question](https://stackoverflow.com/questions/874256/dynamicaly-loaded-js-function-does-not-appear-in-firebug-js-debugger/874400#874400). The solution involves adding the word debugger twice; once at the top of the external file and one more time at the top of the function that needs to be debugged.
I noticed that if the debugger word was used only once, it did not work. Example:
```
//myExternal.js
debugger;
function myExternalFunction(){
debugger;
/* do something here */
}
``` | You might try placing a break point where the event is called, and then instead of click "Play", choose "Step Into" (F11). I don't have a test case in front of me, but I think this may work. | Making Firebug break inside dynamically loaded javascript | [
"",
"javascript",
"jquery",
"firebug",
""
] |
IDEs like Netbeans allow generation of entity classes through a persistence context. If you had access to underlying generation method (not sure if it is an external tool or part of the IDE), could you **generate database entity classes dynamically at runtime?** The idea being that you could hook into the entity classes using reflection.
I know you can go the other way and generate the database from the entity class, however due to permissions issues in my work environment that would be a no go. However, if you reverse the process and pull the classes from the database it may be feasible in my environment. The idea being that the database would serve as a single point of configuration/control. | It's theoretically possible but what would be the point? Java is statically typed so you would *only* be able to use the generated classes by reflection and you would have no way of giving them behaviour, so removing the whole point of object-relational mapping. Loading the data into Maps or just using SQL record sets would be more convenient.
If you have an existing schema you can write classes that act in the way your application needs and declaratively map them onto the schema. That way the code is the simplest expression of your application logic and is persistence-agnostic. | You can find on JBoss website a tool to do the reverse engineering from database to java objects.
The source code is available, you should dig in!
<https://www.jboss.org/tools/download/stable.html> | Is it possible to generate JPA entity classes from a database schema at runtime? | [
"",
"java",
"hibernate",
"jpa",
"code-generation",
"persistence",
""
] |
I have been programming in PHP for a while but I still dont understand the difference between == and ===. I know that = is assignment. And == is equals to. So what is the purpose of ===? | It compares both value and type equality.
```
if("45" === 45) //false
if(45 === 45) //true
if(0 === false)//false
```
It has an analog: !== which compares type and value inequality
```
if("45" !== 45) //true
if(45 !== 45) //false
if(0 !== false)//true
```
It's especially useful for functions like strpos - which can return 0 validly.
```
strpos("hello world", "hello") //0 is the position of "hello"
//now you try and test if "hello" is in the string...
if(strpos("hello world", "hello"))
//evaluates to false, even though hello is in the string
if(strpos("hello world", "hello") !== false)
//correctly evaluates to true: 0 is not value- and type-equal to false
```
[Here's a good wikipedia table](http://en.wikipedia.org/wiki/%3D%3D%3D#Object_identity_vs._Content_equality) listing other languages that have an analogy to triple-equals. | It is true that === compares both value and type, but there is one case which hasn't been mentioned yet and that is when you compare objects with == and ===.
Given the following code:
```
class TestClass {
public $value;
public function __construct($value) {
$this->value = $value;
}
}
$a = new TestClass("a");
$b = new TestClass("a");
var_dump($a == $b); // true
var_dump($a === $b); // false
```
In case of objects === compares reference, not type and value (as $a and $b are of both equal type and value). | What does === do in PHP | [
"",
"php",
"comparison",
"operators",
""
] |
I have to store relational data (text, numbers and pictures) into an XML file. I want to maintain the relationship between data and the tables structure.
How do I go about doing that?
My Windows Mobile application use Windows Communication Foundation (WCF) to get data. Once it gets the data it stores them into an XML file.
The WCF use ADO.NET Entity Framework to data retrieve.
I'm going to use SQL Server 2008.
The data will be use to show it on application. I don't want to use SQL Server CE to store data because it's slower. Maybe, instead of using XML file I can use text plain files to store texts and numbers, and image files to store images.
In short, XML will be a way to store the data instead using SQL Server CE or WCF.
Thank you! | Thanks for the additional detail.
My suggestion is first, try SQL Server CE. It might not actually be slower for what you're doing. The time you save in not reinventing the wheel might be better spent in speeding up other parts of your application.
For the rest, assuming you don't need to store the data for long, nor do much with it, I'd suggest copying the data from the Web Service return type into a DataSet. The DataSet type has a WriteXml method that can save the data, and a ReadXml method that can read it back in. | While it's a little ambiguous what is needed, you can try looking into 'FOR XML EXPLICIT' under SQL Server. This will include relationships. Link: <http://www.eggheadcafe.com/articles/20030804.asp> | Store Relational database as XML | [
"",
"c#",
".net",
"xml",
"wcf",
"entity-framework",
""
] |
I have a FileUpload with a RegularExpressionValidator with the following Validation Expression:
```
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.gif|.jpg|.JPG|.JPEG|.GIF|.jpeg|.png|.bmp|.3dm|.3dmf|.ai|.drw|.dxf|.esp|.mng|.png|.ps|.psp|.svg|.tiff)$
```
This way I make sure the User only upload images.
But for some reason it does not work when I use Firefox. Why is that and how can I go around the problem? | I found the solution.....
```
(.*\.([gG][iI][fF]|[jJ][pP][gG]|[jJ][pP][eE][gG]|[bB][mM][pP])$)
```
[Link to the answer](http://forums.asp.net/t/1342216.aspx)
Enjoy!!! | Try this:
```
(.*?)\.(jpg|jpeg|png|gif)$
``` | File Upload with RegularExpressionValidator not working with Firefox only IE | [
"",
"c#",
"asp.net",
"vb.net",
"validation",
"file-upload",
""
] |
Is it possible to display only those statements in console, which are having certain words.
For eq:
```
logger.debug ( "java: hello " );
logger.debug ( "groovy: hello " );
logger.debug ( "ruby: hello " );
```
Now, by doing some configuration or whatever, all statements which are starting with groovy: should display. | You want to use the log4j [StringMatchFilter](http://logging.apache.org/log4j/companions/extras/apidocs/org/apache/log4j/filter/StringMatchFilter.html) which is part of the "extras" package from apache logging.
Here is a quick example found [online](http://www.webdeveloper.com/forum/showthread.php?t=91074):
```
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="CustomAppender" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="custom.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="5000KB"/>
<param name="maxBackupIndex" value="5"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.StringMatchFilter">
<param name="StringToMatch" value="Here is DEBUG" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.DenyAllFilter"/>
</appender>
<root>
<appender-ref ref="CustomAppender"/>
</root>
</log4j:configuration>
``` | SLF4J markers are perhaps suitable for your purposes. All printing methods such as debug and info in `org.slf4j.Logger` [admit a Marker as a first parameter](http://www.slf4j.org/apidocs/org/slf4j/Logger.html#debug%28org.slf4j.Marker,%20java.lang.String%29). Moreover, logback-classic, a native SLF4J implementation, ships with a filter called `MarkerFilter` which I think does what you want. | Display only selected Log4j debug statements | [
"",
"java",
"log4j",
""
] |
In php, is there a tool that can generate a code coverage report **without** using automated unit test cases ?
(basically not using phpunit or similar unit testing frameworks which do a good job generating the report but require unit testcases to be written in php!).
Exactly what I am looking for, is a tool that would generate me a code coverage report based on manual testing performed by a tester. | Sheldon,
Have you heard of Xdebug? I'm using this and it is fantasic! I'm using Ubuntu 8.04 and it is available via the package repository (apt-get).
It is free and it has basic code coverage analysis functionalities:
<http://xdebug.org/docs/code_coverage>
For your information, profiling is also available:
xdebug.org/docs/profiler
(This should be a hyperlink!!! It only allows me to post one hyperlink per answer because I'm a new user... sigh...)
Hope this helps!
Kenji | Compuware's DevPartner tools can do this. I'm not sure, but you may need to manually merge the results of multiple test runs. | Is there a code coverage tool that works with manual testing? | [
"",
"php",
"phpunit",
"code-coverage",
""
] |
Greetings,
I'm using embedded java, I write the application to a low resource device. One of the problems I get is when the code crashes the device stops. I can get a little information from it with some logging that I've added. (Simple print statements)
This logging cannot remain in the application due to memory constraints.
I was wondering does anyone know is there a flag I can pass to the JVM to state if its a debug or standard compilation I require.
I'd like for the print statements to be included if its a debug build, if it is a standard build to remove the print statements. I ask because I've to constantly cut and paste the statements etc. (IT's a pain)
Thanks | You can make use of the fact that `if (constant)` is optimized by the compiler.
Make a global variable somewhere called `DEBUG`:
```
public static final boolean DEBUG = true;
```
and then do your logging like so:
```
if (DEBUG) {
System.out.println("Debug");
}
```
To disable debugging, simply change `DEBUG` to `false`, and all of the logging statements will be optimized away by the compiler. You can verify this by looking at the generated bytecode with `javap -c`.
For example:
```
class DebugTest {
public static final boolean DEBUG = true;
public static void main(String[] args) {
if (DEBUG) {
int a = 10;
System.out.println("a = " + a);
}
}
}
```
is compiled as:
```
Compiled from "DebugTest.java"
class DebugTest extends java.lang.Object{
public static final boolean DEBUG;
DebugTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: bipush 10
2: istore_1
3: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
6: new #3; //class java/lang/StringBuilder
9: dup
10: invokespecial #4; //Method java/lang/StringBuilder."":()V
13: ldc #5; //String a =
15: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: iload_1
19: invokevirtual #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
22: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
25: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
28: return
}
```
Changing `DEBUG` to `false` yields:
```
Compiled from "DebugTest.java"
class DebugTest extends java.lang.Object{
public static final boolean DEBUG;
DebugTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: return
}
``` | Well, you'll have to use a pre-processor, and still it would be a kind of ugly.
Just pre-process your source before compilation. Using `cpp`, for example.
It is said that javac sometimes might drop statements in dead condition branches, including static final booleans, like
```
private static final DEBUG = false;
if(DEBUG) System.err.println("Entered");
```
But I'm not sure, I advise you to try that and check if bytecode contains that call. | Debug / Standard build of Java application | [
"",
"java",
"debugging",
""
] |
I need to provide a means for a user to upload photos to their web site in jpeg format. However, the photos are very large in original size, and I would like to make the resize before upload option very effortless for the user. It seems my only options are a client side application that resizes the photos before uploading them via a web service, or a client side JavaScript hook on the upload operation that resizes the images. The second option is very tentative because I don't have a JavaScript image resizing library, and it will be difficult to get the JavaScript to run my current resize tool, ImageMagick.
I'm sure this is not too uncommon a scenario, and some suggestions or pointers to sites that do this will be appreciated. | You have several options:
1. Java
2. ActiveX (only on windows)
3. [Silverlight](http://silverlight.net/forums/p/45674/164450.aspx)
4. [Flash](http://www.element-it.com/MultiPowUpload.aspx)
5. [Flex](http://livedocs.adobe.com/flex/3/html/help.html?content=controls_16.html)
6. [Google Gears](http://gears.google.com/) (the most recent version is capable of resizing and drag and drop from your desktop)
I've done a lot of research looking for a similar solution to what you have described and there a lot of solutions out there that vary a lot in quality and flexibility.
My suggestion is find a solution which will do 80% of what you need and customize it to suit your needs. | In 2011, we can know do it with the File API, and canvas.
This works for now only in firefox and chrome.
Here is an example :
```
var file = YOUR_FILE,
fileType = file.type,
reader = new FileReader();
reader.onloadend = function() {
var image = new Image();
image.src = reader.result;
image.onload = function() {
var maxWidth = 960,
maxHeight = 960,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
}
else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(fileType);
}
}
reader.readAsDataURL(file);
``` | Image resize before upload | [
"",
"javascript",
"image-processing",
""
] |
Are the following Lambda and Linq expressions equivalent in terms of execution paths? I guess I'm wondering if the Linq is going to run differently because it's going to create an IEnumerable before determining if the enumeration has anything in it whereas the lambda expression will stop on the first digit it finds.
```
var x = valueToMatch
.Any(c => Char.IsDigit(c));
var y = (from c in valueToMatch
select c).Any(c => Char.IsDigit(c)); here
```
Thx! Joel | It will run differently, but not in any considerable way. If you use the [MSIL Disassembler](http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx) you will see a slightly different output for the first expression and the second, even with optimizations turned on. You can also look at it using a [Reflector](http://www.red-gate.com/products/reflector/) (which is a little easier to read).
The second version will basically pass each element through something like:
```
[CompilerGenerated]
private static char <Match2>b__2(char c)
{
return c;
}
```
before it executes the Any(c => Char.IsDigit(c)) expression. So there is indeed a difference. | They are roughly equivalent. The compiler will probably optimize out the select and the two will be 100% identical. At anyrate, Linq is lazy-evaluated so valueToMatch will be enumerated exactly the same amount in both cases. | Are the following Lambda and Linq expressions equivalent? | [
"",
"c#",
".net",
"linq",
"lambda",
""
] |
If a user is on your website and opens another link (also to your website) in a new tab, is it possible to differentiate this from the user just clicking on the link normally? This can be in javascript, on the server, whatever.
I'm guessing that the answer is that you cannot do this, but I wanted to double check. | You can sort of do it like this:
```
if (history.length == 1) { // Um, needs to be 0 for IE, 1 for Firefox
// This is a new window or a new tab.
}
```
There may be other ways for `history.length` to be `1`, but I don't know what they might be. | In addition to history.length in JavaScript you can read/write the window's name.
Thus if you check if it has a name onload... it *should* be blank on the very first load... if you then set it to "foo"... on each subsequent load in that window... the window.name property will return "foo"... unless you open a link in a new tab/window... that new window should have no name set.
(unless of course you open a popup via window.open(url, name, features); which allows you to pre-set the name)
```
<script>
if(window.name == ''){
//first load (or Nth load in a new Tab/Window)
if(!SOME_VALUE_SET_FOR_2ND_TO_NTH_LOADS){
//set name so we can catch new Tab/Window
window.name = 'myWinName';
} else {
//we have a new Tab/Window (or something funky)
alert('What?! One window not cool enough for ya?\n' +
'Calling the InterWeb Police!');
}
} else if(window.name == 'myWinName'){
//2nd-Nth load
document.title = 'All is well... we think';
}
</script>
```
Caveats:
* If your page is initially loaded in a window/frame that already had a name... things will get quirky
* If your page has (named) iframes and you have any links targeted into those iframes, there is a bug in IE7/8 whereby when the user opens those links in a new tab/window, the new tab/window will "inherit" the name of the iframe that was originally targeted (very ODD bug with no fix ever expected) | Is it possible to detect if a user has opened a link in a new tab? | [
"",
"javascript",
"tabs",
""
] |
For some reason, I've always assumed that `readonly` fields have overhead associated with them, which I thought of as the CLR keeping track of whether or not a `readonly` field has been initialized or not. The overhead here would be some extra memory usage to keep track of the state and a check when assigning a value.
Perhaps I assumed this because I didn't know a `readonly` field could only be initialized inside a constructor or within the field declaration itself and without a run-time check, you wouldn't be able to guarantee it's not being assigned to multiple times in various methods. But now I know this, it could easily be statically checked by the C# compiler, right? So is that the case?
Another reason is that I've read that the usage of `readonly` has a 'slight' performance impact, but they never went into this claim and I can't find information on this subject, hence my question. I don't know what other performance impact there might be aside from run-time checks.
A third reason is that I saw that `readonly` is preserved in the compiled IL as `initonly`, so what is the reason for this information to be in the IL if `readonly` is nothing more than a guarantee by the C# compiler that the field is never assigned to outside of a constructor or declaration?
On the other hand, I've found out you can set the value of a `readonly int` through reflection without the CLR throwing an exception, which shouldn't be possible if `readonly` was a run-time check.
So my guess is: the 'readonlyness' is only a compile time feature, can anyone confirm/deny this? And if it is, what is the reason for this information to be included in the IL? | You have to look at it from the same point of view as the access modifiers. The access modifiers exist in IL, but are they really a run-time check? (1) I can't directly assign private fields at compile-time, (2) I can assign them using reflection. So far it seems no run-time check, like *readonly*.
But let's examine access modifiers. Do the following:
1. Create Assembly A.dll with public class C
2. Create an Assembly B.exe that references A.dll. B.exe uses class C.
3. Build the two assemblies. Running B.exe works just fine.
4. Rebuild A.dll but set class C to internal. Replace A.dll in B.exe's directory.
Now, running B.exe throws a runtime exception.
Access modifiers exist in IL as well, right? So what's their purpose? The purpose is that other assemblies that reference a .Net assembly need to know what they are allowed to access and what they are not allowed to access, both compile-time AND run-time.
*Readonly seems to have a similar purpose in IL*. It tells other assemblies whether they can write to a field on a particular type. However, *readonly* **does not seem** to have that same run-time check that access modifiers exhibit in my sample above. It seems that readonly is a compile-time check and does not occur in run-time. Take a look at a sample of performance here: [Read-only performance vs const](http://dotnetperls.com/Content/readonly-Field.aspx).
Again, this doesn't mean the IL is useless. The IL makes sure that a compile-time error occurs in the first place. Remember, when you build you don't build against code, but assemblies. | If you're using a standard, instance variable, readonly will perform nearly identically to a normal variable. The IL added becomes a compile time check, but is pretty much ignored at runtime.
If you're using a static readonly member, things are a bit different...
Since the static readonly member is set during the static constructor, the JIT "knows" that a value exists. There is no extra memory - readonly just prevents other methods from setting this, but that's a compile time check.
SInce the JIT knows this member can never change, it gets "hard-coded" at runtime, so the final effect is just like having a const value. The difference is that it will take longer during the JIT time itself, since the JIT compiler needs to do extra work to hard-wire the readonly's value into place. (This is going to be very fast, though.)
[Expert C++/CLI](https://rads.stackoverflow.com/amzn/click/com/1590597567) by Marcus Hegee has a reasonably good explanation of this. | Is there any run-time overhead to readonly? | [
"",
"c#",
"performance",
"readonly",
"immutability",
""
] |
PHP prior to version 5.5 has no finally block - i.e., whereas in most sensible languages, you can do:
```
try {
//do something
} catch(Exception ex) {
//handle an error
} finally {
//clean up after yourself
}
```
PHP has no notion of a finally block.
Anyone have experience of solutions to this rather irritating hole in the language? | Solution, no. Irritating cumbersome workaround, yes:
```
$stored_exc = null;
try {
// Do stuff
} catch (Exception $exc) {
$stored_exc = $exc;
// Handle an error
}
// "Finally" here, clean up after yourself
if ($stored_exc) {
throw($stored_exc);
}
```
Yucky, but should work.
**Please note**: PHP 5.5 finally (ahem, sorry) added a finally block: <https://wiki.php.net/rfc/finally> (and it only took a few years... available in the 5.5 RC almost four years to the date since I posted this answer...) | The [RAII](https://stackoverflow.com/questions/2321511/) idiom offers a code-level stand-in for a `finally` block. Create a class that holds callable(s). In the destuctor, call the callable(s).
```
class Finally {
# could instead hold a single block
public $blocks = array();
function __construct($block) {
if (is_callable($block)) {
$this->blocks = func_get_args();
} elseif (is_array($block)) {
$this->blocks = $block;
} else {
# TODO: handle type error
}
}
function __destruct() {
foreach ($this->blocks as $block) {
if (is_callable($block)) {
call_user_func($block);
} else {
# TODO: handle type error.
}
}
}
}
```
### Coordination
Note that PHP doesn't have block scope for variables, so `Finally` won't kick in until the function exits or (in global scope) the shutdown sequence. For example, the following:
```
try {
echo "Creating global Finally.\n";
$finally = new Finally(function () {
echo "Global Finally finally run.\n";
});
throw new Exception;
} catch (Exception $exc) {}
class Foo {
function useTry() {
try {
$finally = new Finally(function () {
echo "Finally for method run.\n";
});
throw new Exception;
} catch (Exception $exc) {}
echo __METHOD__, " done.\n";
}
}
$foo = new Foo;
$foo->useTry();
echo "A whole bunch more work done by the script.\n";
```
will result in the output:
```
Creating global Finally.
Foo::useTry done.
Finally for method run.
A whole bunch more work done by the script.
Global Finally finally run.
```
### $this
PHP 5.3 closures can't access `$this` (fixed in 5.4), so you'll need an extra variable to access instance members within some finally-blocks.
```
class Foo {
function useThis() {
$self = $this;
$finally = new Finally(
# if $self is used by reference, it can be set after creating the closure
function () use ($self) {
$self->frob();
},
# $this not used in a closure, so no need for $self
array($this, 'wibble')
);
/*...*/
}
function frob() {/*...*/}
function wibble() {/*...*/}
}
```
### Private and Protected Fields
Arguably the biggest problem with this approach in PHP 5.3 is the finally-closure can't access private and protected fields of an object. Like accessing `$this`, this issue is resolved in PHP 5.4. For now, [private and protected properties](https://stackoverflow.com/q/3722394/90527) can be accessed using references, as Artefacto shows in his [answer](https://stackoverflow.com/a/3722429/90527) to a question on this very topic elsewhere on this site.
```
class Foo {
private $_property='valid';
public function method() {
$this->_property = 'invalid';
$_property =& $this->_property;
$finally = new Finally(function () use (&$_property) {
$_property = 'valid';
});
/* ... */
}
public function reportState() {
return $this->_property;
}
}
$f = new Foo;
$f->method();
echo $f->reportState(), "\n";
```
[Private and protected methods](https://stackoverflow.com/q/6386733/90527) can be accessed using reflection. You can actually use the same technique to access non-public properties, but references are simpler and more lightweight. In a comment on the PHP manual page for [anonymous functions](http://www.php.net/manual/en/functions.anonymous.php#98384), Martin Partel gives an example of a `FullAccessWrapper` class that opens up non-public fields to public access. I won't reproduce it here (see the two previous links for that), but here is how you'd use it:
```
class Foo {
private $_property='valid';
public function method() {
$this->_property = 'invalid';
$self = new FullAccessWrapper($this);
$finally = new Finally(function () use (&$self) {
$self->_fixState();
});
/* ... */
}
public function reportState() {
return $this->_property;
}
protected function _fixState() {
$this->_property = 'valid';
}
}
$f = new Foo;
$f->method();
echo $f->reportState(), "\n";
```
### `try/finally`
`try` blocks require at least one `catch`. If you only want `try/finally`, add a `catch` block that catches a non-`Exception` (PHP code can't throw anything not derived from `Exception`) or re-throw the caught exception. In the former case, I suggest catching `StdClass` as an idiom meaning "don't catch anything". In methods, catching the current class could also be used to mean "don't catch anything", but using `StdClass` is simpler and easier to find when searching files.
```
try {
$finally = new Finally(/*...*/);
/* ... */
} catch (StdClass $exc) {}
try {
$finally = new Finally(/*...*/);
/* ... */
} catch (RuntimeError $exc) {
throw $exc
}
``` | How can I get around the lack of a finally block in PHP? | [
"",
"php",
"exception",
"resource-cleanup",
""
] |
I'm doing some exploration of operator-overloading at the moment whilst re-reading some of my old University text-books and I think I'm mis-understanding something, so hopefully this will be some nice easy reputation for some answerers. If this is a duplicate please point me in the right direction.
I've created a simple counter class that has (at this stage) a single member, val (an int).
I have initialised three of these counters, varOne to varThree, and want the third counter to be the sum of the first two (e.g. varThree.val is set to 5 in the below code)
```
counter::counter(int initialVal)
{
val = initialVal;
//pVal = new int;
//*pVal = 10; // an arbitrary number for now
}
int main (int argc, char const* argv[])
{
counter varOne(3), varTwo(2), varThree;
varThree = varOne + varTwo;
return 0;
}
```
I've overloaded operator+ like so:
```
counter operator+(counter& lhs, counter& rhs)
{
counter temp(lhs.val + rhs.val);
return temp;
}
```
I've made this a non-member function, and a friend of the counter class so that it can access the private values.
My problem starts when adding another private member, **pVal** (a pointer to an int). Adding this means that I can no longer do a simple `varThree = varOne` copy because when varOne is destroyed, varThree.pVal will still be pointing to the same bit of memory.
I've overloaded `operator=` as follows.
```
int counter::getN()
{
return *newVal;
}
counter& counter::operator=(counter &rhs)
{
if (this == &rhs) return *this;
val = rhs.val;
delete pVal;
pVal = new int;
*pVal = rhs.getN();
return *this;
}
```
Now if I do something like `varThree = varOne` everything copies correctly, however trying to do `varThree = varOne + varTwo` gives me the following error:
```
counter.cpp: In function ‘int main(int, const char**)’:
counter.cpp:96: error: no match for ‘operator=’ in ‘varThree = operator+(counter&, counter&)(((counter&)(& varTwo)))’
counter.cpp:55: note: candidates are: counter& counter::operator=(counter&)
make: *** [counter] Error 1
```
It looks as though `counter::operator=` is having trouble coping with the return output from `operator+`, and that I need to overload `operator=` further to accept the type that `operator+` is returning, but I've had no luck and I'm beginning to think that maybe I've done something fundamentally wrong. | You need to pass your parameters as const reference. For example:
```
counter& counter::operator=( const counter &rhs )
```
And similarly for operator+(). This is necessary in order to be able to bind temporary values to the function parameter(s). Temporary values are created when you return by value, so when you say:
```
varOne + varTwo
```
a nameless temporary is created. This is the right thing to do, but you have to make sure that functions such as the assignment op can accept such values by making their parameters const.
You also need to implement the copy constructor and destructor for your class, though lack of these will not cause compilation errors (unfortunately). | Another way to approach this problem is to use the PImpl pattern and swap for the assignment operator. Assuming that you still have a counter(int) constructor you could write operator= as follows
```
counter& counter::operator=(const counter& rhs) {
counter temp(rhs.getN());
std::swap(&pVal,rhs.pVal);
return *this;
}
```
This has the benefit of leaving the messy memory management functions in the constructor and destructor where they should be. | c++ overloading operators, assignment, deep-copy and addition | [
"",
"c++",
"operator-overloading",
"deep-copy",
""
] |
Is it faster for the randomize the sort order of a large set of results on the MySQL server or after I have received the data in PHP?
Does anyone have any data to backup either side, or even anecdotal experience? | My educated guess is that MySQL wins hands down. It's made to handle data this way. The sheer overhead of having to move all the data over to PHP for sorting gives it an advantange to boot.
You can find out for yourself by doing some benchmarking, of course. | For sure you should do it on `MySQL` side.
But note that `ORDER BY RAND()` is *very* inefficient in `MySQL` since it requires `filesort`.
See how to select `10` random rows efficiently with a single table scan:
```
SELECT *
FROM (
SELECT @cnt := COUNT(*) + 1,
@lim := 10
FROM t_random
) vars
STRAIGHT_JOIN
(
SELECT r.*,
@lim := @lim - 1
FROM t_random r
WHERE (@cnt := @cnt - 1)
AND RAND() < @lim / @cnt
) i
```
See this article in my blog for performance details:
* [**Selecting random rows**](http://explainextended.com/2009/03/01/selecting-random-rows/)
For a `1,000,000` records table, it runs in less than a second instead of `15` seconds using `ORDER BY RAND()`. | Faster to randomize many results on MySQL Server or in PHP | [
"",
"php",
"mysql",
""
] |
i want to find out a log10 of an integer in python and i get an error like
math domain error
my code is this
w=math.log10(q\*q1)/math.log10(2)
where q1,q2 are integers
yeah q1 is 0 sometimes | Is q or q1 equal to zero or one of them negative? | You can only compute the logarithm of a positive number. Trying to compute the logarithm for a negative number or zero will result in a "math domain error" in Python.
By the way: it looks like you're actually trying to compute a logarithm base 2. You can do this with `math.log`:
```
w=math.log(q*q1, 2)
```
The second, optional, parameter is the base. It defaults to e (ie: natural log). | python logarithm | [
"",
"python",
""
] |
I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.
1. How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)
2. How would I access its members? (`myArray[0][1]` or `myArray[0,1]`?) | Practically? Yes. You can create an array of arrays which functions as an 2D array as every item is an array itself:
```
let items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);
```
But technically this is just an array of arrays and not a “true” 2D array, as [I. J. Kennedy](https://stackoverflow.com/users/8677/) pointed out.
It should be noted that you could keep nesting arrays into one another and so create “multidimensional” arrays. | You simply make each item within the array an array.
```
var x = new Array(10);
for (var i = 0; i < x.length; i++) {
x[i] = new Array(3);
}
console.log(x);
``` | How can I create a two dimensional array in JavaScript? | [
"",
"javascript",
"arrays",
"multidimensional-array",
""
] |
After having successfully build a static data structure ([see here](https://stackoverflow.com/questions/960963/trie-prefix-tree-in-python)), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a file and load this file for each query. Needless to say (as I figured out), this turns out to be too time-consuming, as the file is rather large.
Any ideas how I can easily speed up this thing? Splitting the file into multiple files? Or a program running on the server? (How difficult is this to implement?)
Thanks for your help! | My suggestion would be not to rely on having an object structure. Instead have a byte array (or mmap'd file etc) which you can do random access operations on and implement the cross-referencing using pointers inside that structure.
True, it will introduce the concept of pointers to your code, but it will mean that you don't need to unpickle it each time the handler process starts up, and it will also use a lot less memory (as there won't be the overhead of python objects).
As your database is going to be fixed during the lifetime of a handler process (I imagine), you won't need to worry about concurrent modifications or locking etc.
Even if you did what you suggest, you shouldn't have to rebuild it on every user request, just keep an instance in memory in your worker process(es), which means it won't take too long to build as you only build it when a new worker process starts. | You can dump it in a memory cache (such as [memcached](http://www.danga.com/memcached/)).
This method has the advantage of cache key invalidation. When underlying data changes you can invalidate your cached data.
### EDIT
Here's the python implementation of memcached: [python-memcached](http://www.tummy.com/Community/software/python-memcached/). Thanks [NicDumZ](https://stackoverflow.com/users/115023/nicdumz). | How can I speed up a web-application? (Avoid rebuilding a structure.) | [
"",
"python",
"apache",
"web-applications",
"pickle",
""
] |
Since [this question](https://stackoverflow.com/questions/947302/if-java-didnt-have-to-care-about-backwards-compatibility-how-would-it-be-differe) is back to four votes to close, I'm trying again to ask a more narrow question that hopefully the community will view more favorably.
Which specific design decisions in Java are documented to be done the way that they are not because that was the preferred design decision, but rather because it was necessary to support backwards compatibility.
The obvious case is Generics, where you cannot detect the type parameter at runtime. (So you can't do:
```
public void addEmptyMember(List<?> someList) {
if (someList instanceof List<String>) {
((List<String>) someList).add("");
}
}
```
What other such examples exist in the language design and standard API? | Because this question doesn't have a single right answer, I'm not sure if it'll fare any better than your other question.
Three features I can think of (in addition to generic erasure, which you already mentioned) that made compromises in the name of backward compatibility were the new for loop syntax, varargs, and autoboxing.
The new for loop syntax probably should have read `for (item in List)`, but that would have required making `in` into a reserved word. This would caused numerous backwards compatibility problems, not the least of which being the fact that `System.in` would have to be renamed.
varargs and autoboxing both added the possibilities of ambiguity. For example, if you pass an array of Objects to a method that accepts `Object...` does that mean the array should be passed as the vararg array or as an element of the vararg array? This gets even more complicated if there are overloads. Autoboxing has similar ambiguity problems with overloading. The solution to both of these problems was to make it a rule that when resolving method calls they are first resolved with the pre-1.5 rules (ie: no autoboxing, and `Object...` is treated as `Object[]`). Only if the method call can't be resolved with the pre-1.5 rules are the new 1.5 rules considered. | There are lots of examples in the standard library
* java.awt.Color has the same constants with upper and lower case names
* All the deprecated methods in java.util.Date given the introduction of java.util.Calendar - what a mess!!
* java.util.Enumeration still being used where java.util.Iterator could replace it
* Classes in Swing that accept Vectors as arguments but could have had support added for java.util.Collection | What Java designs are explicitly done to support backwards compatability? | [
"",
"java",
"backwards-compatibility",
""
] |
I'm trying to subscribe to change events on an input tag for an ajax auto complete form. These change events are not firing when the user clicks an autocomplete suggestion from FireFox.
I've seen fixes for IE, but not FireFox. You can view this behavior [here](http://jehiah.cz/sandbox/onchange.html)
Steps to recreate:
type any input in one of the boxes and click submit.
Start typing the value again in the same box.
You should see the autocomplete suggestion box appear below the input box. Notice that clicking the suggestion does not fire the change event (it also doesn't fire the click event)
Currently my only option is to disable autocomplete on this field, but I do not want to do that. | If it makes you feel better, it is a [known bug](https://bugzilla.mozilla.org/show_bug.cgi?id=87943)
Proposed workaround: (Not mine, from [here](http://forums.mozillazine.org/viewtopic.php?f=38&t=584166&start=0&st=0&sk=t&sd=a)
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Mozilla Firefox Problem</title>
<script type="text/javascript">
function fOnChange()
{
alert('OnChange Fired');
}
var val_textBox;
function fOnFocus()
{
val_textBox = document.getElementById('textBox').value;
}
function fOnBlur()
{
if (val_textBox != document.getElementById('textBox').value) {
fOnChange();
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr>
<td><input type="text" id="textBox" name="textBox" onFocus="fOnFocus()" onBlur="fOnBlur()"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
</body>
</html>
``` | Firefox 4+ fire 'oninput' event when autocomplete is used.
Here's some jQuery to make this more actionable:
```
$('#password').bind('input', function(){ /* your code */});
``` | FireFox capture autocomplete input change event | [
"",
"javascript",
"firefox",
"autocomplete",
""
] |
I'm storing time-temperature data in a database, which is really just CSV data. The first column is time in seconds, starting at zero, with the following (one or more) column(s) being temperature:
```
0,197.5,202.4
1,196.0,201.5
2,194.0,206.5
3,192.0,208.1 ....etc
```
Each plot represents about 2000 seconds. Currently I'm compressing the data before storing it in a `output_profile longtext` field.
```
CREATE TABLE `outputprofiles` (
`id` int(11) NOT NULL auto_increment,
`output_profile` longtext NOT NULL,
PRIMARY KEY (`id`)
```
This helps quite a bit...I can compress a plot which is 10K of plain text down to about 2.5K. There is no searching or indexing needed on this data since it's just referenced in another table.
My question: Is there any other way to store this data I'm not thinking about which is more efficient in terms of storage space? | Is there any reason to think that storage space will be a limiting constraint on your application? I'd try to be pretty sure that's the case before putting a higher priority on that, compared to ease of access and usage; for which purpose it sounds like what you have is satisfactory. | I actually do not understand quite well what you mean with "compressing the plot". Means that, that you are compressing 2000 measurements or you are compressing each line?
Anyway, space is cheap. I would make it in the traditional way, i.e. two columns, one entry for each measurements.
If for some reason this doesn't work and if you want to save 2000 measurements as one record then you can do it pretty much better.
. Create a csv file with your measurements.
. zip it (gzip -9 gives you the maximal compression)
. save it as a **blob** (or **longblob** depending the DB you are using) NOT as a longtext
Then just save it at the DB.
This will give you maximal compression. | Storing time-temperature data in DB | [
"",
"sql",
"mysql",
"database",
"postgresql",
""
] |
I'm working in Microsoft Visual C# 2008 Express and with SQLite.
I'm querying my database with something like this:
```
SQLiteCommand cmd = new SQLiteCommand(conn);
cmd.CommandText = "select id from myTable where word = '" + word + "';";
cmd.CommandType = CommandType.Text;
SQLiteDataReader reader = cmd.ExecuteReader();
```
Then I do something like this:
```
if (reader.HasRows == true) {
while (reader.Read()) {
// I do stuff here
}
}
```
What I want to do is count the number of rows *before* I do "reader.Read()" since the number returned will affect what I want/need to do. I know I can add a count within the while statement, but I really need to know the count before.
Any suggestions? | The DataReader runs lazily, so it doesn't pick up the entirety of the rowset before beginning. This leaves you with two choices:
1. Iterate through and count
2. Count in the SQL statement.
Because I'm more of a SQL guy, I'll do the count in the SQL statement:
```
cmd.CommandText = "select count(id) from myTable where word = '" + word + "';";
cmd.CommandType = CommandType.Text;
int RowCount = 0;
RowCount = Convert.ToInt32(cmd.ExecuteScalar());
cmd.CommandText = "select id from myTable where word = '" + word + "';";
SQLiteDataReader reader = cmd.ExecuteReader();
//...
```
Note how I counted \*, not id in the beginning. This is because count(id) will ignore id's, while count(\*) will only ignore completely null rows. If you have no null id's, then use count(id) (it's a tad bit faster, depending on your table size).
Update: Changed to ExecuteScalar, and also count(id) based on comments. | What you request is not feasible -- to quote [Igor Tandetnik](http://www.mail-archive.com/sqlite-users@sqlite.org/msg38161.html), my emphasis:
> SQLite produces records one by one, on request, every time you call `sqlite3_step`.
> **It simply doesn't know how many there are going to be**, until on some `sqlite3_step`
> call it discovers there are no more.
(`sqlite3_step` is the function in SQLite's C API that the C# interface is calling here for each row in the result).
You could rather do a `"SELECT COUNT(*) from myTable where word = '" + word + "';"` first, before your "real" query -- *that* will tell you how many rows you're going to get from the real query. | How do I count the number of rows returned in my SQLite reader in C#? | [
"",
"c#",
"sqlite",
""
] |
I saw the following in the source for [WebKit HTML 5 SQL Storage Notes Demo](http://webkit.org/misc/DatabaseExample.html):
```
function Note() {
var self = this;
var note = document.createElement('div');
note.className = 'note';
note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
note.addEventListener('click', function() { return self.onNoteClick() }, false);
this.note = note;
// ...
}
```
The author uses *self* in some places (the function body) and *this* in other places (the bodies of functions defined in the argument list of methods). What's going on? Now that I've noticed it once, will I start seeing it everywhere? | See this [article on alistapart.com](http://www.alistapart.com/articles/getoutbindingsituations). (Ed: The article has been updated since originally linked)
`self` is being used to maintain a reference to the original `this` even as the context is changing. It's a technique often used in event handlers (especially in closures).
**Edit:** Note that using `self` is now discouraged as [`window.self`](https://developer.mozilla.org/en-US/docs/Web/API/Window/self) exists and has the potential to cause errors if you are not careful.
What you call the variable doesn't particularly matter. `var that = this;` is fine, but there's nothing magic about the name.
Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.
For example, a simple event callback:
```
function MyConstructor(options) {
let that = this;
this.someprop = options.someprop || 'defaultprop';
document.addEventListener('click', (event) => {
alert(that.someprop);
});
}
new MyConstructor({
someprop: "Hello World"
});
``` | I think the variable name 'self' should not be used this way anymore, since modern browsers provide a [global variable `self`](https://developer.mozilla.org/en-US/docs/Web/API/Window/self) pointing to the global object of either a normal window or a WebWorker.
To avoid confusion and potential conflicts, you can write `var thiz = this` or `var that = this` instead. | What underlies this JavaScript idiom: var self = this? | [
"",
"javascript",
"scope",
"closures",
""
] |
I'm writing a prototype to prove the feasibility of something I'm working on. Basically, it requires loading assemblies not on disk into an application domain. On the surface, it sounds easy. In fact, it's child's play in the WinForms world where a process is a process.
For the ASP.Net Web Applications, it's a bit squirrelly. I've got it working 99.99%. The current method is somewhat working like this:
```
public class AppDomainManager : System.AppDomainManager
{
PhantomAssemblyLoader m_phantomAssemblyLoader;
public AppDomainManager()
{
m_phantomAssemblyLoader = new PhantomAssemblyLoader();
}
public override void InitializeNewDomain(AppDomainSetup appDomainInfo)
{
m_phantomAssemblyLoader.Attach(AppDomain.CurrentDomain);
}
}
public class PhantomAssemblyLoader
{
public PhantomAssemblyLoader()
{
}
public void Attach(AppDomain appDomain)
{
appDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);
appDomain.DomainUnload += new EventHandler(DomainUnload);
}
public void Detach(AppDomain appDomain)
{
appDomain.AssemblyResolve -= AssemblyResolve;
appDomain.DomainUnload -= DomainUnload;
}
void DomainUnload(object sender, EventArgs e)
{
this.Detach(sender as AppDomain);
}
private Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly asssembly = Assembly.Load(BlackMagic.GetBytes(sender, args));
return asssembly;
}
}
```
The problem seems to be that a new AppDomain is instantiated and unloaded for each page load. The above code loads the required assembly, unloads it, loads it again and so on. I know this is happening because the static data within these phantom assemblies does not persist between page loads.
The correct solution can load these phantom assemblies into the same context as those assemblies found in the /bin folder. These are loaded when the application starts and are never unloaded during the session. | If you read [documentation on AppDomainManager](http://msdn.microsoft.com/en-us/library/system.appdomainmanager.aspx) you will see a note:
> Do not use AppDomainManager to configure an application domain in ASP.NET. In ASP.NET, configuration must be handled by the host.
Therefore, you should not use environment variables or registry to customize AppDomainManager.
I believe you can achieve what you want by simply adding AssemblyResolve event handler to AppDomain.CurrentDomain. I created simple website and it works as expected - dynamic assembly doesn't get unloaded between page loads.
```
protected void Page_Load(object sender, EventArgs e)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);
Assembly assembly = Assembly.Load("PhantomAssembly");
Type t = assembly.GetType("PhantomAssembly.Test");
MethodInfo m = t.GetMethod("GetIt");
Response.Write(m.Invoke(null, null));
t.GetMethod("IncrementIt").Invoke(null, null);
}
private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly asssembly = Assembly.Load(File.ReadAllBytes(@"C:\PhantomAssembly.dll"));
return asssembly;
}
``` | You might want to check out the MSDN article on [ASP.NET Application Life Cycle](http://msdn.microsoft.com/en-us/library/ms178473(VS.80).aspx) and investigate loading your Assembly in the Application\_Start event. | How do I Dynamically Load Assemblies Not on Disk into an ASP .Net Web Application? | [
"",
"c#",
"asp.net",
""
] |
I have an array:
```
$arr[0] = 95
$arr[1] = 8
$arr[2] = 0
$arr[3] = 0
```
That are bytes. I need a DWORD.
I tried:
```
$dword = $arr[0]+$arr[1]*265+$arr[2]*265*265+$arr[3]*265*265*265;
```
Is that right or am I doing it wrong? | Try:
```
$dword = (($arr[3] & 0xFF) << 24) | (($arr[2] & 0xFF) << 16) | (($arr[1] & 0xFF) << 8) | ($arr[0] & 0xFF);
```
It can also be done your way with some corrections:
```
$dword = $arr[0] + $arr[1]*0x100 + $arr[2]*0x10000 + $arr[3]*0x1000000;
```
Or using pack/unpack:
```
$dword = array_shift(unpack("L", pack("CCCC", $arr[0], $arr[1], $arr[2], $arr[3])));
``` | Or try
```
<?php
$arr = array(95,8,0,0);
$bindata = join('', array_map('chr', $arr));
var_dump(unpack('L', $bindata));
```
both (Emil H's and my code) give you 2143 as the result. | PHP Bytes 2 DWord | [
"",
"php",
"byte",
"dword",
""
] |
I'd like to programmatically modify my app.config file to set which service file endpoint should be used. What is the best way to do this at runtime? For reference:
```
<endpoint address="http://mydomain/MyService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IASRService"
contract="ASRService.IASRService" name="WSHttpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
``` | I think what you want is to swap out at runtime a version of your config file, if so create a copy of your config file (also give it the relevant extension like .Debug or .Release) that has the correct addresses (which gives you a debug version and a runtime version ) and create a postbuild step that copies the correct file depending on the build type.
Here is an example of a postbuild event that I've used in the past which overrides the output file with the correct version (debug/runtime)
```
copy "$(ProjectDir)ServiceReferences.ClientConfig.$(ConfigurationName)" "$(ProjectDir)ServiceReferences.ClientConfig" /Y
```
where :
$(ProjectDir) is the project directory where the config files are located
$(ConfigurationName) is the active configuration build type
**EDIT:**
Please see Marc's answer for a detailed explanation on how to do this programmatically. | Is this on the client side of things??
If so, you need to create an instance of WsHttpBinding, and an EndpointAddress, and then pass those two to the proxy client constructor that takes these two as parameters.
```
// using System.ServiceModel;
WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress(new Uri("http://localhost:9000/MyService"));
MyServiceClient client = new MyServiceClient(binding, endpoint);
```
If it's on the server side of things, you'll need to programmatically create your own instance of ServiceHost, and add the appropriate service endpoints to it.
```
ServiceHost svcHost = new ServiceHost(typeof(MyService), null);
svcHost.AddServiceEndpoint(typeof(IMyService),
new WSHttpBinding(),
"http://localhost:9000/MyService");
```
Of course you can have multiple of those service endpoints added to your service host. Once you're done, you need to open the service host by calling the .Open() method.
If you want to be able to dynamically - at runtime - pick which configuration to use, you could define multiple configurations, each with a unique name, and then call the appropriate constructor (for your service host, or your proxy client) with the configuration name you wish to use.
E.g. you could easily have:
```
<endpoint address="http://mydomain/MyService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IASRService"
contract="ASRService.IASRService"
name="WSHttpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="https://mydomain/MyService2.svc"
binding="wsHttpBinding" bindingConfiguration="SecureHttpBinding_IASRService"
contract="ASRService.IASRService"
name="SecureWSHttpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="net.tcp://mydomain/MyService3.svc"
binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IASRService"
contract="ASRService.IASRService"
name="NetTcpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
```
(three different names, different parameters by specifying different bindingConfigurations) and then just pick the right one to instantiate your server (or client proxy).
But in both cases - server and client - you have to pick before actually creating the service host or the proxy client. **Once created, these are immutable** - you cannot tweak them once they're up and running.
Marc | How to programmatically modify WCF app.config endpoint address setting? | [
"",
"c#",
"wcf",
"app-config",
"configuration-files",
""
] |
I'm looking for a way to embed a cmd "Shell" into a Form. I want to build a C# based application that acts as a Terminal, better than the Powershell window (no tabs) or cmd (no nothing). Just start these interpreters in the backend.
I guess MS never thought of doing this. Any ideas what From elements I could use?
Thanks,
i/o | That's not a trivial task you're undertaking. I know of one project ([Console2](http://console.sf.net/)) which basically polls the screen buffer of the underlying console window and displays in its own. You certainly will have trouble coping with interactive applications like Far and the like as they (a) rely on getting keyboard events and (b) on manipulating their screen buffer. Both are icky things if you want a suitable wrapper around the console window functionality. Mouse input is possible as well (unless Quick Edit mode is enabled) which could give you further headaches.
I doubt you can use a ready-made control for this. Basically you need to display a grid of cells each of which has a foreground and background color. You could probably use a RichTextBox for this but I'd guess it's far from ideal.
Also I don't think no one at MS ever thought of this. It's just that there's a limited budget for new features and every one of them needs to be specified, implemented, tested, tested more for regressions with millions of applications out there, etc. It's just a freaking expensive thing (if you don't want to misuse your customers as testers, which they aren't). | It would propably be the easiest to extend the Textbox class and add logic so that it behaves like a console (respond to the KeyPressed/KeyUp/KeyDown events or similar). You can also add events for those things that your console needs to respond to. For example, add a CommandEntered event.
Basing your new console on a TextBox gives you the editing and display features of the textbox "for free", so you do not need to re-implement that. | Windows Terminal - Windows Form to embed cmd | [
"",
"c#",
"winforms",
"shell",
"terminal",
""
] |
```
CODE:
struct Stringdata
{
// Length of data in buffer.
size_t len;
// Allocated size of buffer.
size_t alc;
// Buffer.
char data[1];
};
typedef std::list<Stringdata*> Stringdata_list;
Stringdata_list strings_;
Stringdata *psd = this->strings_.front();
//...
if (len > psd->alc - psd->len)
alc = sizeof(Stringdata) + buffer_size;
else
{
char* ret = psd->data + psd->len;
memcpy(ret, s, len - sizeof(Stringpool_char));
memset(ret + len - sizeof(Stringpool_char), 0,
sizeof(Stringpool_char));
psd->len += len;
return reinterpret_cast<const Stringpool_char*>(ret);
}
```
In the code sample above, I have confused about the operations in the else
branch.
Does it create a new element and insert it after the front element or
just place a new element after within the first element of list? | Your code appears to do neither. The code in the else branch does not modify the `strings_` structure at all. The code is only modifying the element return from the front of the list. This should have no affect on the actual list structure. | It doesn't create a new element -- just appends data from s to the data that's already in the front element, if there's space. Very confusingly written code, though. | One question about element inserting in STL list | [
"",
"c++",
"memory",
"list",
"stl",
""
] |
I would like to have this function:
```
function count(inputObj, ouputObj)
{
outputObj.value = inputObj.value.length;
}
```
And I would like to call it in this way:
```
<asp:TextBox ID="txtUSERGUID" runat="server" onkeyup="count(this, document.getElementById('<%=txtUSERGUIDLength.ClientID%>'));" onkeydown="count(this, document.getElementById('<%=txtUSERGUIDLength.ClientID%>'));" />
<asp:TextBox ID="txtUSERGUIDLength" runat="server" />
<asp:Label ID="lblUSERGUIDLength" runat="server" Text="chars" />
```
But I keep getting a javascript error that says: 'outputObj' is undefined. Can I call this function like this or am I going the completely wrong direction? | You can't have this inside of a server tag it won't execute the server side code:
```
<%=txtUSERGUIDLength.ClientID%>
```
If you are going to do it do something like
```
<script language='javascript'>
var g_clientID = '<%=txtUSERGUIDLength.ClientID%>'
<script/>
```
then do:
```
onclick(this, document.getElementById(g_clientID))
``` | Check your page source, I think you'll find that the "onkeyup" event handler still has the server side code in it. Since you are setting a property on a server control, the "<%= %>" code is not executed. You'll have to move this to a separate javascript function if you want to do this. | Pass asp control as parameter to javascript | [
"",
"javascript",
""
] |
I am about to employ a new programmer for our ASP.NET MVC projects. I put a lot of weight in an interview as to just how much I like a candidate's attitude and how I see them working with, talking to and enjoying being part of the team, but on a more practical note I need to weedle out those who talk a good game from those who actually have ability to adapt and overcome programming problems day to day.
Can anyone suggest any good short questions/exercises (preferably in C#) to separate the smart candidates from the good talkers?
UPDATE - Many thanks to all who answered, I have chosen the most voted for in traditional StackOverlfow manner, but still thanks for all the other suggestions. | First things first. Do they even know what MVC. Not just the TLA (three letter acronym) but can they describe it to you. Then what are the benefits. Also it doesn't hurt to ask them their opinion on it. It is good to know if they even like MVC frameworks.
Next, ask them if they have used any other MVC frameworks. Struts, Spring MVC, Zend or anything like that.
Ask them if they know when a session starts, the general state problem on the net etc etc.
Also a little bit of database. Ask them if they have any experience with database persistence layers.
Then just because you can ask a hard technical question, ask them to write a function that compares two binary trees both in value and structure to see if they are identicial. | Which letter from MVC acronym should be responsible for performing the following features in online shop web application:
* calculating the total amount to pay for items in cart (M)
* build an html table of items to purchase (V)
* redirecting not authenticated users to the page where they can enter billing information (C)
etc. | What is a good C# ASP.NET MVC question to ask a prospective employee? | [
"",
"c#",
"asp.net-mvc",
""
] |
We have a lot of data layer code that follows this very general pattern:
```
public DataTable GetSomeData(string filter)
{
string sql = "SELECT * FROM [SomeTable] WHERE SomeColumn= @Filter";
DataTable result = new DataTable();
using (SqlConnection cn = new SqlConnection(GetConnectionString()))
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("@Filter", SqlDbType.NVarChar, 255).Value = filter;
result.Load(cmd.ExecuteReader());
}
return result;
}
```
I think we can do a little better. My main complaint right now is that it forces all the records to be loaded into memory, even for large sets. I'd like to be able to take advantage of a DataReader's ability to only keep one record in ram at a time, but if I return the DataReader directly the connection is cut off when leaving the using block.
How can I improve this to allow returning one row at a time? | Once again, the act of composing my thoughts for the question reveals the answer. Specifically, the last sentence where I wrote "one row at a time". I realized I don't really care that it's a datareader, as long as I can enumerate it row by row. That lead me to this:
```
public IEnumerable<IDataRecord> GetSomeData(string filter)
{
string sql = "SELECT * FROM [SomeTable] WHERE SomeColumn= @Filter";
using (SqlConnection cn = new SqlConnection(GetConnectionString()))
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("@Filter", SqlDbType.NVarChar, 255).Value = filter;
cn.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return (IDataRecord)rdr;
}
}
}
}
```
This will work even better once we move to 3.5 and can start using other linq operators on the results, and I like it because it sets us up to start thinking in terms of a "pipeline" between each layer for queries that return a lot of results.
The down-side is that it will be awkward for readers holding more than one result set, but that is exceedingly rare.
**Update**
Since I first started playing with this pattern in 2009, I have learned that it's best if I also make it a generic `IEnumerable<T>` return type and add a `Func<IDataRecord, T>` parameter to convert the DataReader state to business objects in the loop. Otherwise, there can be issues with the lazy iteration, such that you see the last object in the query every time. | In times like these I find that lambdas can be of great use. Consider this, instead of the data layer giving us the data, let us give the data layer our data processing method:
```
public void GetSomeData(string filter, Action<IDataReader> processor)
{
...
using (IDataReader reader = cmd.ExecuteReader())
{
processor(reader);
}
}
```
Then the business layer would call it:
```
GetSomeData("my filter", (IDataReader reader) =>
{
while (reader.Read())
{
...
}
});
``` | Return DataReader from DataLayer in Using statement | [
"",
"c#",
".net",
"database",
".net-2.0",
""
] |
I am implementing a piece of Java software that will hopefully allow for C libraries as plugins. In order to call these future functions, I need to somehow create a native function in Java from which I can call the code that doesn't exist yet. The method signature will be static but the method and class names may change.
Is there a way to check the loaded libraries or available functions? The way I hope it would work would be as follows:
In my Java class I would have a function;
```
public static native void thirdParty(String class, String method, int[] data, int[] params);
```
Which would call a function in my C library;
```
JNIEXPORT void JNICALL Java_com_ex_app_Native_thirdParty(JNIEnv *, jclass, jstring, jstring, jintArray, jintArray);
```
From which I could take the class and method name and call them if they exist and throw an exception if they don't.
I guess what I'm looking for is some kind of Java style reflection but in C or failing that C++.
How can I achieve this? | The standard way (or common since there is no real standard)
Is to create a DLL (shared lib).
That DLL has a "C" function with a a fixed name that returns a pointer to a factory object.
You can then use the factory to build objects.
Example:
```
DLL-> Wdigets1.dll C function -> extern "C" Fac& getWidgetFactory();
DLL-> BoilerWidget.dll C function -> extern "C" Fac& getWidgetFactory();
DLL-> RoundWidget.dll C function -> extern "C" Fac& getWidgetFactory();
```
Thus whatever dll you load all you need to do is get a pointer to the function getWidgetFactory() and now you can use the factory to build the appropriate widgets.
The reason behind this:
The libraries that allow you to load libraries dynamically also allow you to find methods/function by name. But the name you need to use is the full name. In "C" this is well defined. In "C++" this is the mangeled name and varies across compilers/platforms etc. So portable code can only find "C" names. | C and C++ don't really have Java-style reflection (though sometimes you can play tricks with looking up symbols in a shared library).
A more typical approach is to create a plugin interface in Java. Then for each external library, you write a (hopefully) small amount of custom Java and/or JNI code to translate plugin interface calls to calls to the backend library. | C/C++ Reflection and JNI - A method for invoking native code which hasn't been written yet | [
"",
"c++",
"c",
"reflection",
"java-native-interface",
""
] |
I'm creating a test platform for a protocol project based on Apache MINA. In MINA when you receive packets the `messageReceived()` method gets an Object. Ideally I'd like to use a JUnit method `assertClass()`, however it doesn't exist. I'm playing around trying to work out what is the closest I can get. I'm trying to find something similar to `instanceof`.
Currently I have:
```
public void assertClass(String msg, Class expected, Object given) {
if(!expected.isInstance(given)) Assert.fail(msg);
}
```
To call this:
```
assertClass("Packet type is correct", SomePacket.class, receivedPacket);
```
This works without issue, however in experimenting and playing with this my interest was peaked by the `instanceof` operator.
```
if (receivedPacket instanceof SomePacket) { .. }
```
How is instanceof able to use `SomePacket` to reference the object at hand? It's not an instance of an object, its not a class, what is it?! Once establishing what type `SomePacket` is at that point is it possible to extend my `assertClass()` to not have to include the `SomePacket.class` argument, instead favouring `SomePacket`? | The argument to instanceof is a class/interface name, and it is implemented directly as a JVM instruction. As such it is pretty efficient.
<http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#instanceof>
One advantage of instanceof instead of comparing the classes is that instanceof will still work if the class has been proxied.
It will also work if the object being checked is null. | Take a look at the Hamcrest matchers, now included in JUnit. What you want is something like:
```
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
assertThat(receivedPacket, instanceOf(SomePacket.class));
```
That does everything you need, including a decent error message upon assertion failure. | Creating a assertClass() method in JUnit | [
"",
"java",
"junit",
""
] |
I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening.
I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file using regex.
If i print the locations as I find them, they print with the characters so the encoding must be ok:
```
Le Pré-Saint-Gervais, France
Hôtel-de-Ville, France
```
I'm storing the data in a SQLite table using SQLAlchemy:
```
Base = declarative_base()
class Point(Base):
__tablename__ = 'points'
id = Column(Integer, primary_key=True)
pdate = Column(Date)
ptime = Column(Time)
location = Column(Unicode(32))
weather = Column(String(16))
high = Column(Float)
low = Column(Float)
lat = Column(String(16))
lon = Column(String(16))
image = Column(String(64))
caption = Column(String(64))
def __init__(self, filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption):
self.filename = filename
self.pdate = pdate
self.ptime = ptime
self.location = location
self.weather = weather
self.high = high
self.low = low
self.lat = lat
self.lon = lon
self.image = image
self.caption = caption
def __repr__(self):
return "<Point('%s','%s','%s')>" % (self.filename, self.pdate, self.ptime)
engine = create_engine('sqlite:///:memory:', echo=False)
Base.metadata.create_all(engine)
Session = sessionmaker(bind = engine)
session = Session()
```
I loop through the files and insert the data from each one into the database:
```
for filename in filelist:
# open the file and extract the information using regex such as:
location_re = re.compile("<h2>(.*)</h2>",re.M)
# extract other data
newpoint = Point(filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption)
session.add(newpoint)
session.commit()
```
I see the following warning on each insert:
```
/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/default.py:230: SAWarning: Unicode type received non-unicode bind param value 'Spitalfields, United Kingdom'
param.append(processors[key](compiled_params[key]))
```
And when I try to do anything with the table such as:
```
session.query(Point).all()
```
I get:
```
Traceback (most recent call last):
File "./extract_trips.py", line 131, in <module>
session.query(Point).all()
File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1193, in all
return list(self)
File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1341, in instances
fetch = cursor.fetchall()
File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 1642, in fetchall
self.connection._handle_dbapi_exception(e, None, None, self.cursor, self.context)
File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 931, in _handle_dbapi_exception
raise exc.DBAPIError.instance(statement, parameters, e, connection_invalidated=is_disconnect)
sqlalchemy.exc.OperationalError: (OperationalError) Could not decode to UTF-8 column 'points_location' with text 'Le Pré-Saint-Gervais, France' None None
```
I would like to be able to correctly store and then return the location names with the original characters intact. Any help would be much appreciated. | I found this article that helped explain my troubles somewhat:
<http://www.amk.ca/python/howto/unicode#reading-and-writing-unicode-data>
I was able to get the desired results by using the 'codecs' module and then changing my program as follows:
When opening the file:
```
infile = codecs.open(filename, 'r', encoding='iso-8859-1')
```
When printing the location:
```
print location.encode('ISO-8859-1')
```
I can now query and manipulate the data from the table without the error from before. I just have to specify the encoding when I output the text.
*(I still don't entirely understand how this is working so I guess it's time to learn more about Python's unicode handling...)* | Try using a column type of Unicode rather than String for the unicode columns:
```
Base = declarative_base()
class Point(Base):
__tablename__ = 'points'
id = Column(Integer, primary_key=True)
pdate = Column(Date)
ptime = Column(Time)
location = Column(Unicode(32))
weather = Column(String(16))
high = Column(Float)
low = Column(Float)
lat = Column(String(16))
lon = Column(String(16))
image = Column(String(64))
caption = Column(String(64))
```
Edit: Response to comment:
If you're getting warnings about unicode encodings then there are two things you can try:
1. Convert your location to unicode. This would mean having your Point created like this:
newpoint = Point(filename, pdate, ptime, unicode(location), weather, high, low, lat, lon, image, caption)
The unicode conversion will produce a unicode string when passed either a string or a unicode string, so you don't need to worry about what you pass in.
2. If that doesn't solve the encoding issues, try calling encode on your unicode objects. That would mean using code like:
newpoint = Point(filename, pdate, ptime, unicode(location).encode('utf-8'), weather, high, low, lat, lon, image, caption)
This step probably won't be necessary but what it essentially does is converts a unicode object from unicode code-points to a specific byte representation (in this case, utf-8). I'd expect SQLAlchemy to do this for you when you pass in unicode objects but it may not. | Unicode Problem with SQLAlchemy | [
"",
"python",
"unicode",
"encoding",
"character-encoding",
"sqlalchemy",
""
] |
I have a pretty simple question, but with an answer that I am unable to find. I was wondering if it is possible to lock a web browser (sticking with IE for now is fine) from being resized under (or past or smaller than) a certain set of dimensions.
For example, a new pop up window that starts at 500px by 500px, but can be enlarged to any size, but cannot shrink below 400px by 400px. So, when the user tries to go below these boundaries, the browser simply locks, not allowing the user to go any further.
A javascript/css/html solution would be preferred.
Thanks!
Jaime | You may find [this](http://oddhammer.com/index.php/site/comments/javascript_minimum_window_size/) link to be useful. Essentially, he describes his issues with doing exactly what you're wanting to do. It SHOULD be simple; simply (within Javascript) trap the resize event, and check the size; if below the minimum size, force a resize to your minimum size. Sadly, it appears to not be that simple, but he describes a reasonable workaround. | Never tried it, but [this site gives a pretty good overview](http://radio.javaranch.com/pascarello/2005/02/16/1108571848000.html) of the technique. | Lock browsers | [
"",
"javascript",
"html",
"css",
"browser",
""
] |
Suppose I have two C++ classes:
```
class A
{
public:
A() { fn(); }
virtual void fn() { _n = 1; }
int getn() { return _n; }
protected:
int _n;
};
class B : public A
{
public:
B() : A() {}
virtual void fn() { _n = 2; }
};
```
If I write the following code:
```
int main()
{
B b;
int n = b.getn();
}
```
One might expect that `n` is set to 2.
It turns out that `n` is set to 1. Why? | Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.
The [C++ FAQ Lite](https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctors) covers this in section 23.7 in pretty good detail. I suggest reading that (and the rest of the FAQ) for a followup.
Excerpt:
> [...] In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. Objects are constructed from the base up, “base before derived”.
>
> [...]
>
> Destruction is done “derived class before base class”, so virtual functions behave as in constructors: Only the local definitions are used – and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object.
**EDIT** Corrected Most to All (thanks litb) | Calling a polymorphic function from a constructor is a recipe for disaster in most OO languages. Different languages will perform differently when this situation is encountered.
The basic problem is that in all languages the Base type(s) must be constructed previous to the Derived type. Now, the problem is what does it mean to call a polymorphic method from the constructor. What do you expect it to behave like? There are two approaches: call the method at the Base level (C++ style) or call the polymorphic method on an unconstructed object at the bottom of the hierarchy (Java way).
In C++ the Base class will build its version of the virtual method table prior to entering its own construction. At this point a call to the virtual method will end up calling the Base version of the method or producing a *pure virtual method called* in case it has no implementation at that level of the hierarchy. After the Base has been fully constructed, the compiler will start building the Derived class, and it will override the method pointers to point to the implementations in the next level of the hierarchy.
```
class Base {
public:
Base() { f(); }
virtual void f() { std::cout << "Base" << std::endl; }
};
class Derived : public Base
{
public:
Derived() : Base() {}
virtual void f() { std::cout << "Derived" << std::endl; }
};
int main() {
Derived d;
}
// outputs: "Base" as the vtable still points to Base::f() when Base::Base() is run
```
In Java, the compiler will build the virtual table equivalent at the very first step of construction, prior to entering the Base constructor or Derived constructor. The implications are different (and to my likings more dangerous). If the base class constructor calls a method that is overriden in the derived class the call will actually be handled at the derived level calling a method on an unconstructed object, yielding unexpected results. All attributes of the derived class that are initialized inside the constructor block are yet uninitialized, including 'final' attributes. Elements that have a default value defined at the class level will have that value.
```
public class Base {
public Base() { polymorphic(); }
public void polymorphic() {
System.out.println( "Base" );
}
}
public class Derived extends Base
{
final int x;
public Derived( int value ) {
x = value;
polymorphic();
}
public void polymorphic() {
System.out.println( "Derived: " + x );
}
public static void main( String args[] ) {
Derived d = new Derived( 5 );
}
}
// outputs: Derived 0
// Derived 5
// ... so much for final attributes never changing :P
```
As you see, calling a polymorphic (*virtual* in C++ terminology) methods is a common source of errors. In C++, at least you have the guarantee that it will never call a method on a yet unconstructed object... | Why is a call to a virtual member function in the constructor a non-virtual call? | [
"",
"c++",
"constructor",
"overriding",
"virtual-functions",
"member-functions",
""
] |
I have a gridview and usercontrol on the page, I want to alter gridview from usercontrol. how can i do that?
And also how can I call functions in usercontrol's "host" page from the usercontrol?
**UPDATE:**
I have a dropdownlist inside this usercontrol, when the it's SelectedIndexChanged event is triggered i want the gridview on the host page to DataBind().
(Then, gridview using objectdatasource will read this dropdownlist selected item and use it as select parameter)
Also if it possible to make it as general as it possible, because the altered control is not always a gridview...
Thanks | First of all, you would not want to do neither. That's against the concept of user control.
If you want to modify a gridview using the user control's state, you can expose the control's state and make the gridview to behave according to this state.
```
// This handles rowdatabound of gridview
OnRowDataBound(object sender, RowDataBoundEventArgs e)
{
var control = e.Row.Find("UserControlId");
if (control.SomeProperty == SomeValue)
someTextBox.Value = "something";
}
```
If you really need to pass a handle of gridview to a user control, define a property on the user control of grid view type:
```
// This is a property of user control
public GridView Container { get; set; }
```
and set the control's container to the gridview, before accessing it.
```
userControl.Container = gridView;
```
If the user control is a part of the itemtemplate on the grid, since your user control is created while rows of the gridview are created, you can only this after you bind your gridview.
Finally, for calling a function on the container page, you can expose an event inside of your user control and bind to that event.
```
public delegate void SomethingHappenedEventHandler(object sender, EventArgs e);
// In user control:
public event SomethingHappenedEventHandler SomethingHappened;
// Trigger inside a method in user control:
SomethingHappenedEventHandler eh = SomethingHappened;
if (eh != null) eh(this, EventArgs.Empty);
// In page:
userControl.SomethingHappened = new SomethingHappendEventHandler(OnSomething);
private void OnSomething(object sender, EventArgs e)
{
// When something happens on user control, this will be called.
}
``` | **EDIT:** In your user control, simply create a public property to hold the grid. That property will then hold a reference to grid in the host page. For example, you could add the following to your UserControl's code behind.
```
public string CurrentGridID
{
get;
set;
}
public void ModifyGrid()
{
//make changes to the grid properties
GridView grid = Page.FindControl(CurrentGridID);
grid.AutoGenerateColumns = false;
}
```
From your the page hosting the control, you could do something like this.
```
protected void Page_Load(object source, EventArgs e)
{
this.myUserControl1.CurrentGridID = this.gridView1.ID;
}
``` | How to pass an ASP server control as parameter to a usercontrol? | [
"",
"c#",
"asp.net",
"user-controls",
""
] |
EDIT: Apparently, the problem is in the read function: I checked the data in a hex editer
`02 00 00 00 01 00 00 00 00 00 00 00`
So the zero is being stored as zero, just not read as zero.
Because when I use my normal store-in-bin file function:
```
int a = 0;
file.write(reinterpret_cast<char*>(&a), sizeof(a));
```
It stores 0 as the `char` version, or "\0", which obviously isn't stored (because it's a null value?) so when I call my function to read the zero value, it reads the value right after it (or right before if it would be the last in the file). So how can I store zero in a .bin file properly?
EDIT: Here are some of the functions relating to the read/write process:
```
//Init program: creates a sector.bin for another program to read from.
#include<fstream>
using namespace std;
int main()
{
fstream file;
file.open("sector.bin", ios::out | ios::binary);
if(!file.is_open())
{
file.open("sector.bin", ios::out | ios::binary);
file.close();
file.open("sector.bin", ios::out | ios::binary);
if(!file.is_open())
{
return -1;
}
}
file.seekp(file.beg);
int a = 2;
int b = 1;
int c = 0;
file.write(reinterpret_cast<char*>(&a), sizeof(a));
file.write(reinterpret_cast<char*>(&b), sizeof(b));
file.write(reinterpret_cast<char*>(&c), sizeof(c));
file.close();
return 0;
}
//Read function: part of another program that intializes variables based off
//of sector.bin
void sector::Init(std::fstream& file)
{
int top_i = FileRead(file,0);
std::cout<<top_i<<std::endl;
for(int i = 0; i < top_i; i++)
{
accessLV[i] = FileRead(file,i+1);
std::cout<<accessLV[i]<<std::endl;
}
std::cin.ignore();
viral_data.add(new X1(5,5,'X'));
viral_data.add(new X1(9,9,'X'));
player.set(0,0,'O');
return;
}
//the FileRead used in init
int FileRead(std::fstream& file, int pos)
{
int data;
file.seekg(file.beg + pos);
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
```
Also, the output for using `sector::Init` is as follows:
```
2
1
1
```
The ouput that I was trying to write into the bin was
```
2
1
0
```
So either the 0 is being read/written as a 1, or its not being written and Init is reading the last value twice. | It's not clear what do you mean by "storing integer value 0" in a file. Files contain bytes, not integers. Do you need to store sizeof(int) 0-bytes, or just one '\0' byte?
P.S. I also would guess the problem might be in your read code. Did you look at your .bin file in a hex editor?
P.P.S. **Your problem is in seekg() function usage. Instead of passing the offset in bytes, you pass pos. It should be pos \* sizeof(int) instead.** | ```
int num = 0;
write( fd, #, sizeof( int ));
``` | How to store the integer value "0" in a .bin file? (C++) | [
"",
"c++",
"file-io",
"binary-data",
"zero",
""
] |
How can I select a tab as if it was clicked by clicking on a button?
I have googled and looked at all the actions but there are just just so many... :(
Anyone know off hand?
Thanks in advance! | Add an action listener to the button that calls setSelectedComponent, or setSelectedIndex on the JTabbedPane. | I'm not sure what you mean about the button, but you might be looking for [`setSelectedComponent`](http://java.sun.com/javase/6/docs/api/javax/swing/JTabbedPane.html#setSelectedComponent(java.awt.Component)) or [`setSelectedIndex`](http://java.sun.com/javase/6/docs/api/javax/swing/JTabbedPane.html#setSelectedIndex(int)). | Java JTabbedPane, how can I select a tab from a button? | [
"",
"java",
"swing",
"jtabbedpane",
""
] |
I am going to move to a 64 bit machine and a 64 bit OS (Windows) and am trying to figure out if any of the extensions/packages I am using are going to be lost when I make the move. I can't seem to find whether someone has built a list of known issues as flagged on the Python 2.5 [release page](http://www.python.org/download/releases/2.5/). I have been using 2.5 but will at this time move to 2.6. I see that the potential conflicts will arise because of the module relying on a C extension module that would not be compatible in a 64 bit environment. But I don't know how to anticipate them. I want to move to a 64 bit system to because my IT guys told me that is the only way to make a meaningful move up the memory ladder. | It really depends on the specific modules you are using. I am running several 64-bit Linux systems and I have yet to come across problems with any of the C modules that I use.
Most C modules can be built from source, so you should read about the Python distribution utility [distutils](http://docs.python.org/install/index.html#install-index) to see how you can build these modules if you cannot find 64-bit binaries.
Whether a specific module will work in a 64-bit environment depends on how the code was written. Many modules work correctly when compiled for 64-bits, however there is a chance that it won't. Many popular modules such those from [SciPy](http://www.scipy.org/) work just fine.
In short you will either need to just try the module on a 64-bit system or you will have to find the developer/project page and determine if there is a 64-bit build or if there are known bugs. | We're running 2.5 on a 64-bit Red Hat Enterprise Linux server.
Everything appears to be working.
I would suggest you do what we did.
1. Get a VM.
2. Load up the app.
3. Test it.
It was easier than trying to do research. | Is there a list of Python packages that are not 64 bit compatible somewhere? | [
"",
"python",
"64-bit",
"package",
""
] |
I was wondering if it was possible to get Javascript to write some HTML onto the page in a certain DIV.
This is due to the fact, there are certain areas of the site where i don't have access to the markup. But i would like to add a small section there.
For example the container i want to add some html to is
<*div id="topics"><*/div>
Is it possible to get Javascript to do this
<\*div id="topics"> <*div id="mysection"> <*/div> <\*/div>
Many thanks! | This is fairly simple to do, even using plain JavaScript.
```
var topicsDiv = document.getElementById("topics");
topicsDiv.innerHTML = '<div id="mysection"> </div>';
```
If you're going to be doing some serious DOM (Document Object Model, i.e. HTML structure) manipulation, however, then I would recommend you look into using the [JQuery](http://jquery.com/) library. Yet if the task is limited to your question, then normal JavaScript should be fine, as shown above. | With simple Javascript (without JQuery or something you could do):
HTML:
```
<div id="topics"></div>
```
JS:
```
document.getElementById('topics').innerHTML = '<div id="mysection"></div>';
```
Using JQuery you would simply do:
```
$('#topics').append('<div id="mysection"></div>');
``` | Using Javascript to add HTML? | [
"",
"javascript",
"html",
""
] |
If I want to call a server function from JavaScript to retrieve a name of a person from a database (just as an example)... and I went...
```
name = myServices.getName(userId);
```
If I have a script manager with a service reference to a `.asmx` file that has the web method `getName( int userId ) {}` then this function should be called properly and would, eventually, return the name for that `userId`.
Unfortunately, I want to do...
```
name = myServices.getName(userId);
alert(name);
```
however, when doing ASP.NET AJAX, it would call the web method and continue executing before waiting for a response from the server (which I understand is the point of AJAX, to stop the browser from freezing while waiting for data)
I need to get the name back from the server before I can continue executing... How can I approach this to fix this issue? | There is a method you can add as a parameter to the service method that will call the method on success where you can do other stuff.
For example:
```
function test() {
PageMethods.MyMethod("name", OnMyMethodComplete);
}
function OnMyMethodComplete(result, userContext, methodName) {
alert(result);
}
``` | If you want to call a Web method synchronously, you'll need to set up the request manually and use a `Sys.Net.XMLHttpSyncExecutor`.
[Here's an example](http://weblogs.asp.net/ricardoperes/archive/2009/03/06/calling-web-service-methods-synchronously-in-asp-net-ajax.aspx) (see ExecuteSynchronously function). | How does ASP.NET AJAX work when retrieving values from the server? | [
"",
"asp.net",
"javascript",
"ajax",
""
] |
I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.
Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the instance but wouldnt be easier to just work direct with the class?
Sometimes geting the concepts of the language is harder than working with it. | Your question is really rather broad as classes and instances/objects are vital parts of object-oriented programming, so this is not really Python specific. I recommend you buy some books on this as, while initially basic, it can get pretty in-depth. [In essense](http://en.wikipedia.org/wiki/Class-based_programming), however:
> The most popular and developed model of OOP is a class-based model, as opposed to an object-based model. In this model, objects are entities that combine state (i.e., data), behavior (i.e., procedures, or methods) and identity (unique existence among all other objects). The structure and behavior of an object are defined by a class, which is a definition, or blueprint, of all objects of a specific type. An object must be explicitly created based on a class and an object thus created is considered to be an instance of that class. An object is similar to a structure, with the addition of method pointers, member access control, and an implicit data member which locates instances of the class (i.e. actual objects of that class) in the class hierarchy (essential for runtime inheritance features).
So you would, for example, define a `Dog` class, and create instances of particular dogs:
```
>>> class Dog():
... def __init__(self, name, breed):
... self.name = name
... self.breed = breed
... def talk(self):
... print "Hi, my name is " + self.name + ", I am a " + self.breed
...
>>> skip = Dog('Skip','Bulldog')
>>> spot = Dog('Spot','Dalmatian')
>>> spot.talk()
Hi, my name is Spot, I am a Dalmatian
>>> skip.talk()
Hi, my name is Skip, I am a Bulldog
```
While this example is silly, you can then start seeing how you might define a `Client` class that sets a blueprint for what a Client is, has methods to perform actions on a particular client, then manipulate a particular *instance* of a client by creating an object and calling these methods in that context.
Sometimes, however, you have methods of a class that don't really make sense being accessed through an instance of the class, but more from the class itself. These are known as [static methods](http://docs.python.org/library/functions.html#staticmethod). | I am not sure of what level of knowledge you have, so I apologize if this answer is too simplified (then just ignore it).
A class is a template for an object. Like a blueprint for a car. The instance of a class is like an actual car. So you have one blueprint, but you can have several different instances of cars. The blueprint and the car are different things.
So you make a class that describes what an instance of that class can do and what properties it should have. Then you "build" the instance and get an object that you can work with. | Need help with the class and instance concept in Python | [
"",
"python",
""
] |
I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a `<td>`, and I'd like to get the `<tr>` object.
Why wont "$(this).parent().parent()" work? What will?
Thanks,
Brendan
**Edit:** It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution. | The best way would probably be using `closest`:
```
$(this).closest('tr');
```
[Check out the documentation](http://docs.jquery.com/Traversing/closest):
> Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned. | It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.
For example:
```
$(this).parents("tr:first")
```
Will find the closest tr "up the chain". | jQuery parent of a parent | [
"",
"javascript",
"jquery",
""
] |
I'm designing a new revision of my Java application (using an embedded H2 database) around a redesign of the way I'll be handling my data. Here's how I have it planned:
* Entries table-
+ Entry ID
+ Entry name
* Properties table-
+ Property ID
+ Property name
* (Individual property) value table-
+ Value ID
+ Entry ID
+ (Value columns...)
* (Individual entry) value table-
+ Property name
+ (Individual property) value ID
Each entry can have multiple properties (including multiple properties of the same type). Each property has its own way of storing its values. I need to look up all properties defined for a given entry, and maybe all entries for each given property.
Is this a good way to do it?
**Edit:** I'm not sure I explained it well... | In my opinion, that's a very bad way to model data, but this is a very ivory-tower way of looking at the situation as I haven't had to use this model in practice. By the way, it's called the "Entity-Attribute-Value" approach. And the reason I dislike it is because it's very un-schema-like in that most SQL functionality has to be replicated in some way.
There's definitely a time and a place for it (like if you intend to model many objects that have disparate models) or that have schemas that change frequently. But I personally think it's terrible. | If I understand you correctly, I would use intersection or [junction](http://en.wikipedia.org/wiki/Intersection_table) tables instead of what you described.
So you can create a query to get you all the Properties per Entery, or all the Enteries per Property. | Database tables for entries of another table? | [
"",
"java",
"database",
"h2",
""
] |
I decided to find out how our C/C+ \*nix practitioners use the gdb debugger.
Here is what I typically use:
1. b - break filename.c:line #, function, filename.cpp:function, className::Member
2. n, c, s -- next continue step
3. gdb program name => set breakpoints ==> run [parameter list] (I do this to set break points before the program starts)
4. l - to list the surrounding source code.
5. attach processID
6 break [location]
6. gdb programName corefile.core (to examine why app crashed)
7. I also sometimes set breakpoint at exit function (break exit) to examine program stacks
8. info b to examine all the breakpoints
9. clear [breakpoints list ]
How do you use it? | Most useful gdb commands in my opinion (aside from all already listed):
* **info threads** - information about threads
* **thread *N*** - switch to thread *N*
* **catch throw** - break on any thrown exception. Useful when you caught the bug only after the stack unwound.
* **printf**,**print** - examine any and all expressions, printf accepts C-style formatting specifiers
Finally, if debugging over a slow link, the text UI might be of use. To use it, start gdb with the `--tui` command-line switch. | Besides things that have already been posted i also use:
* a [.gdbinit](http://www.yolinux.com/TUTORIALS/src/dbinit_stl_views-1.03.txt) file for STL containers
* `signal SIGNAL noprint nostop` for some custom signals that are of no real interest when debugging
* C-Casts to dereference pointers
* catchpoints (catch throw, catch catch)
* *condition* for conditional break- and watchpoints
* rarely *gdbserver* for remote debugging
* gdb *program* *coredump*, for those embarassing segfaults ;)
PS: One reason i personally love gdb btw. is that it supports tab-completion for nearly everything (gdb commands, symbols in the symbol table, functions, memberfunctions etc.). This is a fairly good productivity boost in my opinion. | How do you use gdb? | [
"",
"c++",
"c",
"gdb",
""
] |
After 2 hours now I couldn't get it right.
The Kohana installation is accessible directly under my domain, i.e. "<http://something.org/>"
Instead of <http://something.org/index.php/welcomde/index> I want to have URLs like <http://something.org/welcome/index>
My .htaccess is messed up completely. It's actually the standard example.htaccess that came with the download. It's almost useless. On the kohana page is a tutorial "how to remove the index.php". It's really useless as well, since it will not even talk about how to remove it. Totally confusing.
Please, can someone provide his working .htaccess for a standard kohana installation? | My htaccess looks like the example.
```
RewriteEngine On
RewriteBase /
RewriteRule ^(application|modules|system) - [F,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
```
But you also have to change the [config.php](http://dev.kohanaphp.com/projects/kohana2/repository/entry/tags/2.3.4/application/config/config.php#L17) file to:
```
$config['index_page'] = '';
``` | This is our .htaccess file right now, and it seems to be working.
```
RewriteEngine On
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT,L]
```
Note that we have our application, system and modules directories all outside of the web root. | How to set up .htaccess for Kohana correctly, so that there is no ugly "index.php/" in the URL? | [
"",
"php",
".htaccess",
"kohana",
""
] |
I am trying the get the user’s local time to store into my database. I cannot use PHP function `now()` as it returns the server’s time.
I have got the `TimezoneOffset` by using JavaScript:
```
d = new Date();
alert(d.getTimezoneOffset()/60);
```
How can I calculate the time by using this? And what type should I use for MySQL data type?
Thanks | I'd have to recommend storing all your times in UTC, then also storing the user's timezone offset. This allows for maximum flexibility, and some decent separation between actual data (UTC time) and display logic (UTC +/- Offset).
For storage, no matter how many times I try RDBMS specific time fields, unix timestamps in an int field always offer the best flexibility and portability.
You could store the user's timezone offset in seconds to make the process even simpler. So EST (-5) would become -18 000
Then, for displaying time -/+ user's offset, simple second maths will work just fine:
```
$now = time();
$userTime = $now + $user->getTimezoneOffset();
```
This'll work fine because adding a negative number is just like subtracting a positive one.
Edit:
You will be able to format the user's timestamp using PHP's standard *gmdate()* function. Just pass the calculated timestamp as the function's second parameter. See <https://www.php.net/manual/en/function.gmdate.php>
Whoops... date() is current locale aware. should use gmdate() instead.
There is of course, one totally different approach which may be better:
Store a textual representation of the User's timezone which is compatible with PHP's date\_default\_timezone\_set() . Then, on each request, if you have an authenticated user, you can set timezone, and all date functions will obey it. | First store the value of d.getTimeZoneOffset() (without dividing) in your table as an INT.
Then, when getting the timezone, run:
```
SELECT `time` AS original_time, DATE_ADD(original_time, INTERVAL `usersettings`.`timezoneoffset` MINUTES) AS new_time FROM `times`
```
(Note: this is untested!) | Calculate user’s time using TimezoneOffset | [
"",
"javascript",
"timezone",
"locale",
""
] |
I have 2 pages: login.php and index.php. Both pages start with
```
session_start();
```
When I set
```
$_SESSION['user'] = "name";
```
in login.php and than open index.php, my session object is empty. How come?
EDIT:
I found the problem: IE 7. I had to grand access to my domain. However, I thought a session is stored on the server, instead of the client? Than why do I have IE grand access to my domain? (<http://www.pcwindowstips.com/2007/09/04/how-to-enable-cookies-in-internet-explorer-7/>) | > I thought a session is stored on the server, instead of the client? Than why do I have IE grant access to my domain? (<http://www.pcwindowstips.com/2007/09/04/how-to-enable-cookies-in-internet-explorer-7/>)
The way sessions work is that a session cookie is stored for the site, which contains your session ID. The only way the server knows who you are is when it reads the session ID cookie on every page load. All of the $\_SESSION data is stored on the server for each user, but the cookie must be set for the server to know which $\_SESSION data to retrieve.
This is also why you can essentially "become" another user if you obtain their session id cookie. | Internet Explorers have a stricter cookie policy than most other browsers. Check your [session cookie parameters](http://docs.php.net/manual/en/session.configuration.php) (see also [`session_get_cookie_params()`](http://docs.php.net/session_get_cookie_params)) and try to replace the default values by explicit values where possible. Additionally you might send a [fake P3P policy](<http://msdn.microsoft.com/en-us/library/ms537343(VS.85).aspx)> to satisfy the Internet Explorers. | PHP Session not working in PHP5 | [
"",
"php",
"session",
""
] |
> **Possible Duplicate:**
> [Java Serial Communication on Windows](https://stackoverflow.com/questions/264277/java-serial-communication-on-windows)
Friends,
I want to connect and transfer data to COM PORT (either virtual or original) in JAVA? | This question has been asked and answered many times:
[Read file from serial port using Java](https://stackoverflow.com/questions/544824/read-file-from-serial-port-java)
[Reading serial port in Java](https://stackoverflow.com/questions/336714/reading-serial-port-in-java)
[Reading file from serial port in Java](https://stackoverflow.com/questions/560328/reading-file-from-serial-port-in-java)
[Is there Java library or framework for accessing Serial ports?](https://stackoverflow.com/questions/747539/is-there-java-library-or-framework-for-accessing-serial-ports)
[Java Serial Communication on Windows](https://stackoverflow.com/questions/264277/java-serial-communication-on-windows)
to reference a few.
Personally I recommend SerialPort from <http://serialio.com> - it's not free, but it's well worth the developer (no royalties) licensing fee for any commercial project. Sadly, it is no longer royalty free to deploy, and SerialIO.com seems to have remade themselves as a hardware seller; I had to search for information on SerialPort.
From personal experience, I strongly recommend **against** the Sun, IBM and RxTx implementations, all of which were unstable in 24/7 use. Refer to my answers on some of the aforementioned questions for details. To be perfectly fair, RxTx may have come a long way since I tried it, though the Sun and IBM implementations were essentially abandoned, even back then.
A newer free option that looks promising and may be worth trying is [jSSC (Java Simple Serial Connector)](https://code.google.com/p/java-simple-serial-connector/), as suggested by @Jodes comment. | The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): <http://www.oracle.com/technetwork/java/index-jsp-141752.html> | How to send data to COM PORT using JAVA? | [
"",
"java",
"serial-port",
""
] |
If I say
```
x.hello()
```
In Java, object x is "calling" the method it contains.
In Ruby, object x is "receiving" the method it contains.
Is this just different terminology for expressing the same idea or is there a fundamental difference in ideology here?
Coming from Java I find Ruby's "receiver" idea quite baffling. Perhaps someone could explain this in relation to Java? | In your example `x` is *not* calling `hello()`. Whatever object contains that snippet is "calling" (i.e., it's the "caller"). In Java, `x` can be referred to as the receiver; it is receiving the call to the `hello()` method. | The difference is more than terminology. In Java, the VM determines whether a given object "accepts" the message that you're trying to send (i.e., the method you're trying to call). If the object's type space doesn't define that method, an exception is thrown and the message is never delivered.
In Ruby, the message is **always** delivered. The object may find a method that matches it, or it may not, and in the latter case it may throw an exception, *or it may not*. Rails is built on this fundamental difference. It's one of the reasons why there isn't a DB-backed web app framework as useful as Rails on the Java platform yet (though some are getting close). | Is the "caller" in Java the same as the "receiver" in Ruby? | [
"",
"java",
"ruby",
"terminology",
""
] |
I wonder what is the fastest way to do shallow copying in C#? I only know there are 2 ways to do shallow copy:
1. MemberwiseClone
2. Copy each field one by one (manual)
I found that (2) is faster than (1). I'm wondering if there's another way to do shallow copying? | This is a complex subject with lots of possible solutions and many pros and cons to each. There is a wonderful article [here](http://www.csharp411.com/c-object-clone-wars/) that outlines several different ways of making a copy in C#. To summarize:
1. Clone Manually
Tedious, but high level of control.
2. Clone with MemberwiseClone
Only creates a shallow copy, i.e. for reference-type fields the original object and its clone refer to the same object.
3. Clone with Reflection
Shallow copy by default, can be re-written to do deep copy. Advantage: automated. Disadvantage: reflection is slow.
4. Clone with Serialization
Easy, automated. Give up some control and serialization is slowest of all.
5. Clone with IL, Clone with Extension Methods
More advanced solutions, not as common. | I'd like to start with a few quotes:
> In fact, MemberwiseClone is usually much better than others, especially for complex type.
and
> I'm confused. MemberwiseClone() should annihilate the performance of anything else for a shallow copy. [...]
Theoretically the best implementation of a shallow copy is a C++ copy constructor: it *knows* the size compile-time, and then does a memberwise clone of all fields. The next best thing is using `memcpy` or something similar, which is basically how `MemberwiseClone` should work. This means, in theory it should obliterate all other possibilities in terms of performance. *Right?*
... but apparently it isn't blazing fast and it doesn't obliterate all the other solutions. At the bottom I've actually posted a solution that's over 2x faster. So: *Wrong.*
**Testing the internals of MemberwiseClone**
Let's start with a little test using a simple blittable type to check the underlying assumptions here about performance:
```
[StructLayout(LayoutKind.Sequential)]
public class ShallowCloneTest
{
public int Foo;
public long Bar;
public ShallowCloneTest Clone()
{
return (ShallowCloneTest)base.MemberwiseClone();
}
}
```
The test is devised in such a way that we can check the performance of `MemberwiseClone` agaist raw `memcpy`, which is possible because this is a blittable type.
To test by yourself, compile with unsafe code, disable the JIT suppression, compile release mode and test away. I've also put the timings after every line that's relevant.
**Implementation 1**:
```
ShallowCloneTest t1 = new ShallowCloneTest() { Bar = 1, Foo = 2 };
Stopwatch sw = Stopwatch.StartNew();
int total = 0;
for (int i = 0; i < 10000000; ++i)
{
var cloned = t1.Clone(); // 0.40s
total += cloned.Foo;
}
Console.WriteLine("Took {0:0.00}s", sw.Elapsed.TotalSeconds);
```
Basically I ran these tests a number of times, checked the assembly output to ensure that the thing wasn't optimized away, etc. The end result is that I know approximately how much seconds this one line of code costs, which is 0.40s on my PC. This is our baseline using `MemberwiseClone`.
**Implementation 2**:
```
sw = Stopwatch.StartNew();
total = 0;
uint bytes = (uint)Marshal.SizeOf(t1.GetType());
GCHandle handle1 = GCHandle.Alloc(t1, GCHandleType.Pinned);
IntPtr ptr1 = handle1.AddrOfPinnedObject();
for (int i = 0; i < 10000000; ++i)
{
ShallowCloneTest t2 = new ShallowCloneTest(); // 0.03s
GCHandle handle2 = GCHandle.Alloc(t2, GCHandleType.Pinned); // 0.75s (+ 'Free' call)
IntPtr ptr2 = handle2.AddrOfPinnedObject(); // 0.06s
memcpy(ptr2, ptr1, new UIntPtr(bytes)); // 0.17s
handle2.Free();
total += t2.Foo;
}
handle1.Free();
Console.WriteLine("Took {0:0.00}s", sw.Elapsed.TotalSeconds);
```
If you look closely at these numbers, you'll notice a few things:
* Creating an object and copying it will take roughly 0.20s. Under normal circumstances this is the fastest possible code you can have.
* However, to do that, you need to pin and unpin the object. That will take you 0.81 seconds.
So why is all of this so slow?
My explanation is that it has to do with the GC. Basically the implementations cannot rely on the fact that memory will stay the same before and after a full GC (The address of the memory can be changed during a GC, which can happen at any moment, including during your shallow copy). This means you only have 2 possible options:
1. Pinning the data and doing a copy. Note that `GCHandle.Alloc` is just one of the ways to do this, it's well known that things like C++/CLI will give you better performance.
2. Enumerating the fields. This will ensure that between GC collects you don't need to do anything fancy, and during GC collects you can use the GC ability to modify the addresses on the stack of moved objects.
`MemberwiseClone` will use method 1, which means you'll get a performance hit because of the pinning procedure.
**A (much) faster implementation**
In all cases our unmanaged code cannot make assumptions about the size of the types and it has to pin data. Making assumptions about size enables the compiler to do better optimizations, like loop unrolling, register allocation, etc. (just like a C++ copy ctor is faster than `memcpy`). Not having to pin data means we don't get an extra performance hit. Since .NET JIT's to assembler, in theory this means that we should be able to make a faster implementation using simple IL emitting, and allowing the compiler to optimize it.
So to summarize on why this can be faster than the native implementation?
1. It doesn't require the object to be pinned; objects that are moving around are handled by the GC -- and really, this is relentlessly optimized.
2. It can make assumptions about the size of the structure to copy, and therefore allows for better register allocation, loop unrolling, etc.
What we're aiming for is the performance of raw `memcpy` or better: 0.17s.
To do that, we basically cannot use more than just a `call`, create the object, and perform a bunch of `copy` instructions. It looks a bit like the `Cloner` implementation above, but some important differences (most significant: no `Dictionary` and no redundant `CreateDelegate` calls). Here goes:
```
public static class Cloner<T>
{
private static Func<T, T> cloner = CreateCloner();
private static Func<T, T> CreateCloner()
{
var cloneMethod = new DynamicMethod("CloneImplementation", typeof(T), new Type[] { typeof(T) }, true);
var defaultCtor = typeof(T).GetConstructor(new Type[] { });
var generator = cloneMethod .GetILGenerator();
var loc1 = generator.DeclareLocal(typeof(T));
generator.Emit(OpCodes.Newobj, defaultCtor);
generator.Emit(OpCodes.Stloc, loc1);
foreach (var field in typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
generator.Emit(OpCodes.Ldloc, loc1);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, field);
generator.Emit(OpCodes.Stfld, field);
}
generator.Emit(OpCodes.Ldloc, loc1);
generator.Emit(OpCodes.Ret);
return ((Func<T, T>)cloneMethod.CreateDelegate(typeof(Func<T, T>)));
}
public static T Clone(T myObject)
{
return cloner(myObject);
}
}
```
I've tested this code with the result: 0.16s. This means it's approximately 2.5x faster than `MemberwiseClone`.
More importantly, this speed is on-par with `memcpy`, which is more or less the 'optimal solution under normal circumstances'.
Personally, I think this is the fastest solution - and the best part is: if the .NET runtime will get faster (proper support for SSE instructions etc), so will this solution.
*Editorial Note:*
The sample code above assumes that the default constructor is public. If it is not, the call to `GetConstructor` returns null. In that case, use one of the other `GetConstructor` signatures to obtain protected or private constructors.
See <https://learn.microsoft.com/en-us/dotnet/api/system.type.getconstructor?view=netframework-4.8> | Fastest Way to do Shallow Copy in C# | [
"",
"c#",
"cloning",
"shallow-copy",
""
] |
is it possible to make a default typecast for an enum?
I use enum for a lot, such as states and I want to compare enums directly to LINQ fields, but I have to typecast all the time. | The answer was MUCH more simple!!!
A good friend of mine told me this is very simple! have a look at this sample!
```
public enum State:byte
{
EmailNotValidated = 0x00,
EmailValidated = 0x10,
Admin_AcceptPending = 0x40,
Active = 0x80,
Admin_BlockedAccount = 0xff
}
```
---
Pay attention to the **:BYTE** part after the name of the Enum... there is the trick I was looking for! But thanks to everyone trying for me! | You should be able to have properties in your LINQ objects that have an enum type. This way you do not have to cast.
So just change your properties to have the correct enum type and you don't have to worry about casts any longer. You can do this in the LINQtoSQL designer. Just right-click on a property, select 'Properties' and set the appropriate Type in the Visual Studio Properties window. | Enum with default typecast? is that possible? | [
"",
"c#",
"asp.net",
"linq",
"linq-to-sql",
"enums",
""
] |
Having a table with the following fields:
Order,Group,Sequence
it is required that all orders in a given group form a continuous sequence. For example: 1,2,3,4 or 4,5,6,7. How can I check using a single SQL query what orders do not comply with this rule? Thank you.
```
Example data:
Order Group Sequence
1 1 3
2 1 4
3 1 5
4 1 6
5 2 3
6 2 4
7 2 6
Expected result:
Order
5
6
7
```
Also accepted if the query returns only the group which has the wrong sequence, 2 for the example data. | Assuming that the sequences are generated and therefore cannot be duplicated:
```
SELECT group
FROM theTable
GROUP BY group
HAVING MAX(Sequence) - MIN(Sequence) <> (COUNT(*) - 1);
``` | Personaly I think I would consider rethinking the requirement. It is the nature of relational databases that gaps in sequences can easily occur due to records that are rolled back. For instance, supppose an order starts to create four items in it, but one fails for some rason and is rolled back. If you precomputed the sequences manually, you would then have a gap is the one rolled back is not the last one. In other scenarios, you might get a gap due to multiple users looking for sequence values at approximately the same time or if at the last minute a customer deleted one record from the order. What are you honestly looking to gain from having contiguous sequences that you don't get from a parent child relationship? | Continuous sequences in SQL | [
"",
"sql",
"ms-access",
"sequence",
""
] |
What is the cleanest way to recursively search for files using C++ and MFC?
EDIT: Do any of these solutions offer the ability to use multiple filters through one pass? I guess with CFileFind I could filter on \*.\* and then write custom code to further filter into different file types. Does anything offer built-in multiple filters (ie. \*.exe,\*.dll)?
EDIT2: Just realized an obvious assumption that I was making that makes my previous EDIT invalid. If I am trying to do a recursive search with CFileFind, I have to use \*.\* as my wildcard because otherwise subdirectories won't be matched and no recursion will take place. So filtering on different file-extentions will have to be handled separately regardless. | Using [`CFileFind`](http://msdn.microsoft.com/en-us/library/f33e1618(VS.80).aspx).
Take a look at this [example](http://msdn.microsoft.com/en-us/library/scx99850(VS.80).aspx) from MSDN:
```
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
if (finder.IsDirectory())
{
CString str = finder.GetFilePath();
cout << (LPCTSTR) str << endl;
Recurse(str);
}
}
finder.Close();
}
``` | Use [Boost's Filesystem](http://www.boost.org/doc/libs/release/libs/filesystem/doc/index.htm) implementation!
The recursive example is even on the filesystem homepage:
```
bool find_file( const path & dir_path, // in this directory,
const std::string & file_name, // search for this name,
path & path_found ) // placing path here if found
{
if ( !exists( dir_path ) ) return false;
directory_iterator end_itr; // default construction yields past-the-end
for ( directory_iterator itr( dir_path );
itr != end_itr;
++itr )
{
if ( is_directory(itr->status()) )
{
if ( find_file( itr->path(), file_name, path_found ) ) return true;
}
else if ( itr->leaf() == file_name ) // see below
{
path_found = itr->path();
return true;
}
}
return false;
}
``` | Recursive file search using C++ MFC? | [
"",
"c++",
"mfc",
"recursion",
"file-search",
""
] |
What's the best Python equivalent of Common Lisp's `maplist` function? From the [maplist documentation](http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun_mapccm_ma_istcm_mapcon.html):
> maplist is like mapcar except that
> function is applied to successive
> sublists of the lists. function is
> first applied to the lists themselves,
> and then to the cdr of each list, and
> then to the cdr of the cdr of each
> list, and so on.
Example (pseudoy-code, not tested):
```
>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
```
**Note**: the arguments passed to `p` in the example above would be the lists `[1, 2, 3]`, `[2, 3]`, `[3]`; i.e., `p` is not applied to the elements of those lists. E.g.:
```
>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
``` | You can write a little function for that
```
def maplist(func, values):
return [map(func, values[i:]) for i in xrange(len(values))]
>>> maplist(lambda a: a* 2, [1,2,3])
[[2, 4, 6], [4, 6], [6]]
```
**[Edit]**
if you want to apply the function on the sublists you can change the function to this:
```
def maplist(func, values):
return [func(values[i:]) for i in xrange(len(values))]
>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
``` | As @Cybis and others mentioned, you can't keep the O(N) complexity with Python lists; you'll have to create a linked list. At the risk of proving [Greenspun's 10th rule](http://en.wikipedia.org/wiki/Greenspun%27s_Tenth_Rule), here is such a solution:
```
class cons(tuple):
__slots__=()
def __new__(cls, car, cdr):
return tuple.__new__(cls, (car,cdr))
@classmethod
def from_seq(class_, l):
result = None
for el in reversed(l):
result = cons(el, result)
return result
@property
def car(self): return self._getitem(0)
@property
def cdr(self): return self._getitem(1)
def _getitem(self, i):
return tuple.__getitem__(self, i)
def __repr__(self):
return '(%s %r)' % (self.car, self.cdr)
def __iter__(self):
v = self
while v is not None:
yield v.car
v = v.cdr
def __len__(self):
return sum(1 for x in self)
def __getitem__(self, i):
v = self
while i > 0:
v = v.cdr
i -= 1
return v.car
def maplist(func, values):
result = [ ]
while values is not None:
result.append(func(values))
values = values.cdr
return result
```
Testing yields:
```
>>> l = cons.from_seq([1,2,3,4])
>>> print l
(1 (2 (3 (4 None))))
>>> print list(l)
[1, 2, 3, 4]
>>> print maplistr(lambda l: list(reversed(l)), cons.from_seq([1,2,3]))
[[3, 2, 1], [3, 2], [3]]
```
EDIT: Here is a generator-based solution that basically solves the same problem without the use of linked lists:
```
import itertools
def mapiter(func, iter_):
while True:
iter_, iter2 = itertools.tee(iter_)
iter_.next()
yield func(iter2)
```
Testing yields:
```
>>> print list(mapiter(lambda l: list(reversed(list(l))), [1,2,3]))
[[3, 2, 1], [3, 2], [3]]
``` | Python equivalent of maplist? | [
"",
"python",
"functional-programming",
"lisp",
""
] |
This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | VB and C# have different interpretations of what "protected" means.
[Here's an explanation](https://stackoverflow.com/questions/509541/difference-between-vb-net-and-c-as-new-webcontrol/509616#509616) copied below:
> The default constructor for WebControl
> is protected.
>
> VB and C# have different
> interpretations of what "protected"
> means.
>
> In VB, you can access a protected
> member of a class from any method in
> any type that derives from the class.
>
> That is, VB allows this code to
> compile:
>
> ```
> class Base
> protected m_x as integer
> end class
>
> class Derived1
> inherits Base
> public sub Foo(other as Base)
> other.m_x = 2
> end sub
> end class
>
> class Derived2
> inherits Base
> end class
> ```
>
> Because a "Derived1" is a base, it can
> access protected members of "other",
> which is also a base.
>
> C# takes a different point of view. It
> doesn't allow the "sideways" access
> that VB does. It says that access to
> protected members can be made via
> "this" or any object of the same type
> as the class that contains the method.
>
> Because "Foo" here is defined in
> "Derived1", C# will only allows "Foo"
> to access "Base" members from a
> "Derived1" instance. It's possible for
> "other" to be something that is not a
> "Derived1" (it could, for example, be
> a "Derived2"), and so it does not
> allow access to "m\_x". | VB.NET has support for CIL Exception Filters, C# doesn't:
```
Try
...
Catch ex As SomeException When ex.SomeProperty = 1
...
End Try
``` | What is allowed in Visual Basic that's prohibited in C# (or vice versa)? | [
"",
"c#",
"vb.net",
""
] |
I have a form on one of my ASP.Net MVC views that I created using the following code
```
<% using (Html.BeginForm(null, null, FormMethod.Post))
```
Using this code I have no control as far as I am aware of setting the name of the form. I'm now trying to write a javascript function to submit the form, is this possible without knowing the forms name?
Thanks | You can use jquery to submit the form:
```
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm"})) { %>
```
(the last part is for htmlAttributes parameter)
just do this:
```
$("#myForm").submit();
```
and do not forget to include jquery-1.2.6.js that comes with mvc (or use a higher version). | If you want to use jQuery without naming the form, and you will only have one form on the page, you can just add a link like this to your page:
```
<a href="#" class="submitForm">Submit</a>
```
And then add this jQuery which will wire up the link to submit **every** form:
```
$(document).ready(function () {
$("a.submitForm").click(function () {
$("form").submit();
});
});
```
So this is a way of doing it (the way I just did it on my site) that doesn't require you to name the form - provided you only have one. Saying that, you may want to submit multiple forms .. | ASP.Net MVC, Submit a form using javascript | [
"",
"javascript",
"asp.net-mvc",
""
] |
I have a rather large program that uses Hibernate for its ORM needs. Due to the age of the project it is using hbm.xml to configure it. I would like to convert it to annotations but I'm vary of investing days (weeks?) in manually adding the annotations and then testing everything.
Is there any tool out there that can help facilitate this? | I don't think so. But you don't have to do it in one go, you can mix annotation and .xml config quite easily.
Also, why do you feel the need to convert to annotations? I wouldn't say they're so much better than xml config to warrant the investment in time to convert them. | I know this question is rather old, but this may help someone coming from a search engine:
We recently undertook this endeavor in our own fairly large project and wrote a tool that parses hbm.xml-files and generates annotations into Java-files to help us.
[You can find it here](https://github.com/SchweizerischeBundesbahnen/hibernate_hbm2annotation).
It automates a majority of the migration, leaving you to only do the difficult parts.
All the easy things are done for you. | Converting from Hibernate hbm.xml to annotations | [
"",
"java",
"hibernate",
""
] |
As part of a project at work, I implemented a Read/Write lock class in C++. Before pushing my code to production, what sort of tests should I run on my class to be sure it will function correctly.
I've obviously performed some sanity tests on my class (making sure only one writer can access at a time, making sure releases and claims increment and decrement properly, etc.)
I'm looking for tests that will guarantee the stability of my class and to prevent edge cases. It seems testing multi-threaded code is much harder than standard code. | It is very difficult to test multi-threaded code, so you should supplement your tests with a detailed code review by colleagues experienced in writing multi-threaded applications. | I guess that you can start by looking at tests included in well-established code. For example the pthreads implementation of GNU libc (nptl) includes read-write locks and some tests.
```
$ ls nptl/tst-rwlock*
nptl/tst-rwlock1.c
nptl/tst-rwlock10.c
nptl/tst-rwlock11.c
nptl/tst-rwlock12.c
nptl/tst-rwlock13.c
nptl/tst-rwlock14.c
nptl/tst-rwlock2.c
nptl/tst-rwlock3.c
nptl/tst-rwlock4.c
nptl/tst-rwlock5.c
nptl/tst-rwlock6.c
nptl/tst-rwlock7.c
nptl/tst-rwlock8.c
nptl/tst-rwlock9.c
``` | Read/Write Locks | [
"",
"c++",
"multithreading",
"testing",
"synchronization",
""
] |
I'm looking for a data structure that is basically a bounded stack.
If I declare that the stack can hold at most 3 items, and I push another item in,
the oldest item is popped. | Well a LIFO (Last In First Out) structure is known as a Stack which is what you need for the main part of your requirement
A FIFO (First In First Out) structure is known as a Queue which is what you need for the ability to pop the oldest Items off the back.
A combination of these is known as a Deque. Where you have to the ability to push or pop from either end.
I'm not sure if Java has a built-in Deque datastructure, but if it does (or you can find an implementation on google), You can just put some wrapping logic around to ensure that if you push to the front, and the deque.Count > 3, then also pop from the back. | You'll be able to implement this using a wrapper over a deque (<http://en.wikipedia.org/wiki/Deque>), or double-ended queue. Just make sure to call the pollLast method inside the offerFirst method if the stack size is reached. | What data structure will hold a bounded stack of items in LIFO? | [
"",
"java",
"algorithm",
"data-structures",
"stack",
""
] |
My first try to use anonymous types(test):
```
private void button4_Click(object sender, EventArgs e)
{
test(new { a = "asd" });
}
private void test(string a)
{
}
```
I get an error "cannot convert from 'AnonymousType#1' to 'string' "
Also I'd like to know how to pass an anonymous type if the parameter is a string[]
```
private void test(string[] a)
{
}
```
Thanks in advance! | a is a string property on your anonymous type
```
private void button4_Click(object sender, EventArgs e)
{
test((new { a = "asd" }).a);
}
private void test(string a)
{
}
```
Edit: Anonymous types do not derive from anything other than object so you cannot create a method that expects an anonymous type parameter.
Edit 2: when you create an anonymous type the compiler create an entirely new type based on the properties you set and the order in which they appear. You cannot create an anonymous type and use it in place of any other type (other than object). The most common scenario I've used them in is for binding when you need to flatten your object graph.
warning, I am horrible at coming up with good example scenarios and this is all from memory!
for example if I had a list of Person objects that had a name property and an address property that contained the street address and needed to bind to a list box
```
var people = new List<Person>()
listbox.TextMember = "Text";
listbox.ValueMember = "Value"
listbox.DataSource = from p in people
select new { Text = p.Name, Value = p.Address.StreetAddress };
``` | Something about your design is faulty. If your test function accepts only strings, then you can never pass an anonymous type to it, just as you can't pass an int, object, or any other non-string type. | Anonymous type as method parameter | [
"",
"c#",
".net",
"anonymous-types",
""
] |
My application has a very simple model right now and I'm trying to find the best way to traverse through an aggregate. As you can see in my model diagram at the bottom, I have an account, a trip and a list of people attending a trip. I would like to be able to view all of the trips an account is apart of and I have come up with something like this:
```
public List<Trip> GetAllTripsFor(int accountid)
{
var tripRepository = new TripRepository();
var trips = tripRepository.FindAll();
var userTrips = new List<Trip>();
foreach (Trip trip in trips)
{
foreach (TripPeople person in trip.People)
{
// If this trip's person list contains this accountid
// then add this trip to the userTrips list.
if(person.Account.Id == accountid)
userTrips.Add(trip);
}
}
return userTrips;
}
```
To me this doesn't seem very efficient and that I'm not thinking about things correctly. Do any of you have ideas on a better way of implementing this? Perhaps I'm thinking about my model wrong? Thanks
[](https://i.stack.imgur.com/QAxXc.png) | thanks for your help. I think I figured out last night what I was trying to achieve. I'm not totally sure it's the best way but it is working good so far. I was able to come up with an interface like the following:
```
//Return a list of trips for the user
var user = accountRepository.GetUserBy(123);
var userTrips = user.Trips;
//Return all of the users attending a trip
var peopleAttendingTrip = tripRepository.GetTripBy(234).People;
//Check user's status for a trip. A user must pay some kind of deposit
//before they are considered active.
var userStatus = userTrips.SingleOrDefault().GetStatusFor(user);
```
To achieve this I created a many-to-many table that holds the the primary keys from User and Trip and then mapped the relationship in NHibernate to the User Class and Trip Class. Also to achieve the user's status for a trip, I created an Entity that stores the user's state along with the trip and user info. That's a little duplication of data it seems like but I like the way it currently works and looks.
If you guys have any comments or a better way to implement this let me know. I'm always up for improving something! Thanks again
[](https://i.stack.imgur.com/ibpHY.png) | Im not supprised this doesn't feel right to you, it not. Infact it's so wrong it hurts!But instead of just just giving you grief ill explain all the reason why this is wrong@
Firstly, your load in ALL the trips into memory from the database, this essentially means you are querying a data store to get a whole load of data that you don't need and then passing it down the wire. This is fine if you have a few trips, but this will not scale at all.
Next you are recursing through each trip and calling the property "trip.People". This will then hit the database again and load ALL the data for people on EACH one of these trips. Again, this will kill you if you have several trips with several attendees. Now, this is assuming that you have no filters on your mappings or you have specifically asked NHibernate not to lazy load your People collection, but either way that's a whole load of data you don't want.
My advice would be to look at the NHibernate documents concerning querying your object model using either HQL or Linq-To-NHibernate, and you'll end up with queries that look something like the following:
HQL (MY HQL Sucks so this could be very wrong):
> var hql = @"from Trip as t
> join t.People as p
> with p.Account.Id = :accountId select t"
Edit:
Actually, my brain is a little slow right now as its late, but I just realized that your doing things a little backwards here. What your actually after is all the trips that an person has been on, so why doesn't your account object have a Trips collection mapped to is? You should essentially be aiming for something like this:
> var trips = accountRepo.GetAccount(123).Trips;
Edit:
Again I am tired so this may be nonsense, but I think the mapping you are looking for will look like this:
```
<bag name="Trip" cascade="all" table="TripToAccount" lazy="true">
<key column="AccountId" />
<many-to-many class="Trip">
<column name="TripId" not-null="true"/>
</many-to-many>
</bag>
```
Edit:
Damn it, i should go to bed. Now I see you already have a mapping between the people and their trips so why not:
> var query = "from TripPeople as tp
> Where tp.Account.Id = :accountId AND
> tp.IsActive = true select tp.Trip"
Going to stop answering now, before I do more stupid things. | NHibernate Aggregate Traversal (C#) | [
"",
"c#",
"nhibernate",
"domain-driven-design",
"aggregate",
"traversal",
""
] |
I have built a small app that allows me to choose a directory and count the total size of files in that directory and its sub directories.
It allows me to select a drive and this populates a tree control with the drives immediate folders which I can then count its size!
It is written in .net and simply loops round on the directories and for each directory adds up the file sizes.
It brings my pc to a halt when It runs on say the windows or program files folders.
I had thought of Multi threading but I haven't done this before.
Any ideas to increase performance?
thanks | Your code is really going to slog since you're just using strings to refer to directories and files. Use a DirectoryInfo on your root directory; get a list of FileSystemInfos from that one using DirectoryInfo.GetFileSystemInfos(); iterate on that list, recursing in for DirectoryInfo objects and just adding the size for FileInfo objects. That should be a LOT faster. | **I'd simply suggest using a [background worker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to preform the work**. You'll probably want to make sure controls that shouldn't be usable aren't but anything that would be usable could stay usable.
Google: <http://www.google.com/search?q=background+worker>
This would allow your application to be multi-threaded with out some of the complexity of multiple threads. Everything has been packaged up and it convenient to use. | App to analyze folder sizes?? c# .net | [
"",
"c#",
".net",
""
] |
The tutorials I've found on WxPython all use examples from Linux, but there seem to be differences in some details.
For example, in Windows a Panel behind the widgets is mandatory to show the background properly. Additionally, some examples that look fine in the tutorials don't work in my computer.
So, do you know what important differences are there, or maybe a good tutorial that is focused on Windows?
**EDIT:** I just remembered this: Does anybody know why when subclassing wx.App an OnInit() method is required, rather than the more logical `__init__`()? | I've noticed odd peculiarities in a small GUI I wrote a while back, but it's been a long time since I tried to the specifics are a rather distant memory. Do you have some specific examples which fail? Maybe we can improve them and fix the bugs?
Have you tried [the official wxPython tutorials](http://www.wxpython.org/tut-part1.php)? ...or were you after something more specific?
**r.e. your edit** - You should use `OnInit()` because you're subclassing [wx.App](http://docs.wxwidgets.org/stable/wx_wxapp.html#wxapponinit) (i.e. it's a requirement for wxWidgets rather than Python) and the wxPython implementation is wherever possible, just a wrapper for wxWidgets.
**[Edit]** Zetcode has [a fairly lengthy tutorial on wxPython](http://zetcode.com/wxpython/). I've not looked through it all myself, but it might be of some help?
The [`wxWidgets::wxApp::OnInit()`](http://docs.wxwidgets.org/stable/wx_wxapp.html#wxapponinit) documentation is fairly clear:
> This must be provided by the application, and will usually create the application's main window, optionally calling wxApp::SetTopWindow. You may use OnExit to clean up anything initialized here, provided that the function returns true.
If wxWidgets didn't provide a common interface then you'd have to do different things in C++ (using a constructor) compared to Python's `__init__(self,...)`. Using a language-independent on-initialisation allows wxWidgets ports to other languages look more alike which should be a good thing right? :-) | I find a number of small differences, but don't remember all of them. Here are two:
1) The layout can be slightly different, for example, causing things to not completely fit in the window in one OS when the do in the other. I haven't investigated the reasons for this, but it happens most often when I use positions rather than sizers to arrange things.
2) I have to explicitly call `Refresh` more in Windows. For example, if you place one panel over another, you won't see it the top panel in Windows until you call Refresh.
I general, I write apps in Linux and run them in Windows, and things work similarly enough so this is a reasonable approach, but it's rare for me when something runs perfectly straight out of the gate after an OS switch. | WxPython differences between Windows and Linux | [
"",
"python",
"windows",
"linux",
"user-interface",
"wxpython",
""
] |
I am developing a log4net using CF 3.5 VS 2008 on windows mobile 6.
I have used log4net before in my windows xp applications, and I always put the configuration in the app.config file.
However, this is my first time using log4net with CF3.5. And I have noticed there is no app.config file, and when I try to add a new item there is no template for one. Am I missing something here?
If 3.5 doesn't have a app.config file. Where can I put my log4net configuration? I would like to log4net using the file appender and save the log in the directory where the application is executing from.
Many thanks for any suggestions, | Compact framework does not support app.config files but you can emulate such behavior.
Create a xml with setting and then read content of that file.
I found this workaround that work for me:
<http://www.eggheadcafe.com/articles/dotnetcompactframework_app_config.asp> | This reaction is a bit late, and probably you have solved it already.
However there might be some other users that have the same problem.
You can also specify that you want to use a different config-file using the XmlConfiguratorAttribute. See [here](http://logging.apache.org/log4net/release/sdk/log4net.Config.XmlConfiguratorAttribute.html).
For instance you could specify the log4net-configuration in 'log4net.config' which is in your bin-directory and add in the assemblyInfo.cs:
```
[assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config",Watch=true)]
``` | log4net compact framework 3.5 No app.config to add file appenders | [
"",
"c#",
"log4net",
""
] |
I have 2 strings which are actually dates but they are in different format:
1. 2004-06-01 00:00:00 (This value I get from Excel database through JDBC)
2. 6/1/2004
Is their any pre-defined Class in Java which I can use to create Date kind of object? So that I can just invoke its constructor over these Strings and finally compare them.
Or will I have to write my own function to compare using String functions? Please Help.
Thanks for reading. | You are looking for [SimpleDateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html).
SimpleDateFormat is an implementation of the abstract [DateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/DateFormat.html). You first define the pattern of the date in the constructor and then use parse method.
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
Date date = sdf.parse(dateString);
```
If you are using a Locale other than the default, you need to define it at the constructor. | There is no `Date` constructor that accepts an arbitrarily formatted string, but you could write a method easily enough:
```
Date parseDate(String dateFormat, String dateValue) throws ParseException {
return new SimpleDateFormat(dateFormat).parse(dateValue);
}
```
Usage:
```
Date myExcelDate = parseDate("yyyy-MM-dd HH:mm:ss", "2004-06-01 00:00:00");
Date myOtherDate = parseDate("d/M/yyyy", "6/1/2004");
```
You'll need to catch a potential ParseException. See [SimpleDateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html) for format string details. | Date processing in Java | [
"",
"java",
"date",
""
] |
As the title says, I want to know the exact reason why JavaScript is called a "scripting language"?
My understanding is it's because JavaScript is only interpreted by the browser (and not compiled). Correct me if I'm wrong.
But if there is no compilation then how come `0 == ''` is true? Doesn't the compiler coerce the values, or is that the JavaScript engine...? I am a bit confused. | I think first two sentences from [wikipedia](http://en.wikipedia.org/wiki/Scripting_language) are clear enough:
> A scripting language, script language
> or extension language is a programming
> language that allows some control of a
> single or many software
> application(s). Languages chosen for
> scripting purposes are often much
> higher-level than the language used by
> the host application...
In this case, the *application* is the browser. And about compilation:
> Scripts are
> often, but not always, interpreted from the source
> code or "semi-compiled" to bytecode
> which is interpreted, unlike the
> applications they are associated with,
> which are traditionally compiled to
> native machine code for the system on
> which they run
About `0` being equal to `''`, the coercion it is not necessarily achieved by a compiler; it's all about the JavaScript engine in runtime.
I feel sorry for taking everything from Wikipedia but it's so clear and I put it quoted
PS: I find worth to paste this too:
> Many people view 'scripting' languages
> as inferior or somehow different than
> languages that haven't achieved
> popularity on the scripting scene.
> Ironically, these same languages were
> carefully chosen for scripting due to
> their quality and versatility. | ## An update for 2017
> "Scripting languages are a lot like obscenity. I can't define it, but I'll know it when I see it." - *Larry Wall*
For the purposes of this answer let's assume it to mean a language that:
1. lacks some of the features of a "real" language (whatever that means) so is most useful as the "glue" between other components in the system, and
2. is interpreted rather than compiled.
Javascript was indeed at one point considered a scripting language, with basic features to manipulate the DOM, perform form validation and make the Jesus dance. It was executed directly from source by an [interpreter](https://en.wikipedia.org/wiki/Interpreted_language).
But JS has matured considerably over the last few years, with advanced features such as lambdas, classes (for better or worse), destructuring, iterators and modules that bring its capabilities on par with most other modern languages. No longer restricted to the browser, is it also commonly found running standalone on the server under NodeJS.
Javascript is now universally JIT compiled, either to bytecode (like Java and C#), or directly to machine code (like C and C++). And modern engines offer an optimization phase, similar to most traditional compiled languages.
### V8 (Chrome, Node)
> V8 compiles JavaScript directly to [native machine code](https://en.wikipedia.org/wiki/Chrome_V8) before executing it.
### Chakra Code (Edge)
> Chakra Core [can] do [parallel JIT compilation](https://developers.redhat.com/blog/2016/05/31/javascript-engine-performance-comparison-v8-charkra-chakra-core-2/)...
### SpiderMonkey (Firefox)
> SpiderMonkey 38 includes a just-in-time compiler (JIT) that [compiles JavaScript to machine code](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/38)...
Therefore, if modern JS is considered a *scripting language* then the same should apply to most other non-"scripting" languages. | Why is JavaScript called a "scripting language"? | [
"",
"javascript",
"scripting",
""
] |
Ok so here is how things are going:
```
[Server] Start
[Server] Socket.AcceptConnection
[Client] Start
[Client] Socket.Connect
[Server] Receive //blocking
[Client] Send
[Server] Print
[Server] Receive
[Client] Close socket
```
Is there any way to know when the client as closed the connection?
I am currently using the fake packet trick as described on MSDN where on a separate thread I do a
```
[Server] socket.Send(byte[], 0,0);
```
And I check if it throw any error but it does not, even if the client as closed the socket.
P.S. I am actualy thinking, might it be a problem if I have a socket on the server side (TCP) and a TcpClient on the client side?
Thank you. | According to the docs for [Socket.Connected](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx):
> The value of the Connected property
> reflects the state of the connection
> as of the most recent operation. If
> you need to determine the current
> state of the connection, make a
> nonblocking, zero-byte Send call. If
> the call returns successfully or
> throws a WAEWOULDBLOCK error code
> (10035), then the socket is still
> connected; otherwise, the socket is no
> longer connected.
Note that your current call is a blocking call as far as I can see - you need to make a nonblocking call according to that documentation. | TCP connection should return `0`, i.e. `EOF`, on a read from socket on which FIN has been received, but you'd be much better off designing your protocol so parties tell each other when it's time to disconnect/close the socket. Also playing with the same socket from multiple threads will bite you - avoid it. | Using System.Net.Socket, how can we know when the remote socket is closed? | [
"",
"c#",
".net",
"sockets",
""
] |
With a DataGridView control on a Windows form, when you move the mouse over a row label (or column label) it's (the label cell) background changes to a shade of blue (or other colour depending on your Windows colour scheme no doubt).
I would like to produce that effect when moving the mouse over any cell in the grid - i.e. highlight the row label for the row the mouse is currently hovering over.
The logic for changing the style of the current row is simple enough using mouseover event. I can change other attributes of the row (like say the backcolor) but I would really like something more subtle than that and I think highlighting of the row label would be very effective.
Can it be done - if so how? (C# preferably) | You could override the [OnCellPainting](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.oncellpainting.aspx) event to do what you want. Depending on the size of your [DataGridView](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview(VS.85).aspx), you might see flickering, but this should do what you want.
```
class MyDataGridView : DataGridView
{
private int mMousedOverColumnIndex = int.MinValue;
private int mMousedOverRowIndex = int.MinValue;
protected override void OnCellMouseEnter(DataGridViewCellEventArgs e)
{
mMousedOverColumnIndex = e.ColumnIndex;
mMousedOverRowIndex = e.RowIndex;
base.OnCellMouseEnter(e);
base.Refresh();
}
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
if (((e.ColumnIndex == mMousedOverColumnIndex) && (e.RowIndex == -1)) ||
((e.ColumnIndex == -1) && (e.RowIndex == mMousedOverRowIndex)))
{
PaintColumnHeader(e, System.Drawing.Color.Red);
}
base.OnCellPainting(e);
}
private void PaintColumnHeader(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, System.Drawing.Color color)
{
LinearGradientBrush backBrush = new LinearGradientBrush(new System.Drawing.Point(0, 0), new System.Drawing.Point(100, 100), color, color);
e.Graphics.FillRectangle(backBrush, e.CellBounds);
DataGridViewPaintParts parts = (DataGridViewPaintParts.All & ~DataGridViewPaintParts.Background);
e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None;
e.AdvancedBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.None;
e.Paint(e.ClipBounds, parts);
e.Handled = true;
}
}
``` | You can hook into the DataGridView's CellMouseEnter and CellMouseLeave events and then change the backcolor accordingly. Something like this:
```
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0) //column header / row headers
{
return;
}
this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightBlue;
}
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0) //column header / row headers
{
return;
}
this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
}
``` | How do you highlight the row and/or column labels of a datagridview on mouseover of any cell (in c#)? | [
"",
"c#",
"winforms",
"datagridview",
""
] |
Introducing some of the goodness of collection operations to our codebase without adding a new external library dependency, we are adding these methods to our utility package.
```
static public List<T> filter(List<T> source, Predicate<T> filter);
static <Y,T> public List<Y> transform(List<T> source, Mutator<Y,T> filter);
static public boolean exists(List<T> source, Predicate<T> filter);
static public T findFirst(List<T> source, Predicate<T> filter);
static public boolean trueForAll(List<T> source, Predicate<T> filter);
```
With the attendant interfaces
```
public interface Predicate<T> { public boolean apply(T item); }
public interface Mutator<T,Y> { public Y apply(T item); }
```
So the questions:
* Is Filters a good name for the class containing the extensions? If not, a better?
* Is Mutator<T,Y> appropriately named?
* Should I prefer **map** to **transform** and **reduce** to **filter**?
* Are there any important set-based functions that I've forgotten to include in the library class?
**Edited to add**: A significant argument I have against **map** (and thus in favor of **transform**) is that **map** has significant semantic load due to the many uses for java.util.Map | I would call them **map** and **filter**. Reduce has a slightly different meaning for me, and transform is too vague. As for the class name, Filters may not be the best, but I don't have a better recommendation.
I know you weren't asking for this specifically, but some of the signatures in the generic methods can be improved:
```
static public <T> List<T> filter(List<T> source, Predicate<? super T> filter);
static public <Y,T> List<Y> transform(List<T> source, Mutator<Y,? super T> filter);
static public <T> boolean exists(List<T> source, Predicate<? super T> filter);
static public <T> T findFirst(List<T> source, Predicate<? super T> filter);
static public <T> boolean trueForAll(List<T> source, Predicate<? super T> filter);
``` | > Are there any important set-based
> functions that I've forgotten to
> include in the library class?
For higher-order collection functions I use the approach outlined by Adrian Kuhn in his article "[Pimp My Foreach](http://www.iam.unibe.ch/~akuhn/blog/2008/pimp-my-foreach-loop/)".
Some of these you've already got, but thought I'd throw them out there anyway:
* AllSatisfy
* AnySatisfy
* Cardinality
* Collect
* Count
* CutPieces
* Detect
* Fold
* GroupedBy
* IndexOf
* Inject
* Reject
* Select | Naming Collection Extensions for clarity | [
"",
"java",
"generics",
"collections",
"coding-style",
""
] |
I am trying to figure out why a program I am working on goes in to "not responding" mode when I ask it to output a large amount of characters to the console it is running in.
I tried creating a small example that just prints out characters, and this will indeed also go "not responding" on me after some 10-20 seconds:
```
static void Main(string[] args)
{
for (int i = 0; i < 255; i = (i+1) % 255)
{
Console.Write(((char)i));
}
}
```
The program is still running though, even though the console window is "not responding", I can still pause the debugger and continue it, but the console window is broken.
The thing is, the console do not mind spitting out an endless amount of integers:
```
static void Main(string[] args)
{
for (int i = 0; i < 255; i = (i+1) % 255)
{
Console.Write(i);
}
}
```
Any ideas is much appreaciated. Thanks! | Well it will spew out a lot of nonsense (and beep a lot, unless you mask out character 7, which is a bell) but it never becomes unresponsive for me.
It will depend on how your console handles control characters though - which console are you using, on which operating system and with which language?
Moreover, why do you *want* to send unprintable characters to the console? If you keep your loop to ASCII (32-126) what happens? For example:
```
using System;
class Test
{
static void Main(string[] args)
{
int i=32;
while (true)
{
Console.Write((char)i);
i++;
if (i == 127)
{
i = 32;
}
}
}
}
```
Does that still exhibit the same behaviour?
You mention the debugger - do you get the same behaviour if you run outside the debugger? (I've only tested from the command line so far.) | When you cast it to a character, you're also sending control characters to the console for some lower values of `i`. I'd guess is has something to do with outputting some of those control characters repeatedly. | .net console app stop responding when printing out lots of chars in a row | [
"",
"c#",
".net",
"console-application",
""
] |
The following method is pretty simple, I'm trying to determine a line-item rate by matching up another property of the line-item with a lookup from a parent object. There's a few things I don't like about it and am looking for elegant solutions to either make the method smaller, more efficient, or both. It works in it's current state and it's not like it's noticeably inefficient or anything. This isn't mission critical or anything, more of a curiosity.
```
private decimal CalculateLaborTotal()
{
decimal result = 0;
foreach (ExtraWorkOrderLaborItem laborItem in Labor)
{
var rates = (from x in Project.ContractRates where x.ProjectRole.Name == laborItem.ProjectRole.Name select x).ToList();
if (rates != null && rates.Count() > 0)
{
result += laborItem.Hours * rates[0].Rate;
}
}
return result;
}
```
I like the idea of using `List<T>.ForEach()`, but I was having some trouble keeping it succinct enough to still be easy to read/maintain. Any thoughts? | Something like this should do it (untested!):
```
var result =
(from laborItem in Labor
let rate = (from x in Project.ContractRates
where x.ProjectRole.Name == laborItem.ProjectRole.Name
select x).FirstOrDefault()
where rate != null
select laborItem.Hours * rate.Rate).Sum();
```
Or (assuming only one rate can match) a join would be even neater:
```
var result =
(from laborItem in Labor
join rate in Project.ContractRates
on laborItem.ProjectRole.Name equals rate.ProjectRole.Name
select laborItem.Hours * rate.Rate).Sum();
``` | Okay, well how about this:
```
// Lookup from name to IEnumerable<decimal>, assuming Rate is a decimal
var ratesLookup = Project.ContractRates.ToLookup(x => x.ProjectRole.Name,
x => x.Rate);
var query = (from laborItem in Labor
let rate = ratesGroup[laborItem].FirstOrDefault()
select laborItem.Hours * rate).Sum();
```
The advantage here is that you don't need to look through a potentially large list of contract rates every time - you build the lookup once. That may not be an issue, of course. | Cleaning up a simple foreach with linq | [
"",
"c#",
"linq",
""
] |
I have a table with 4 things I want... the Name, Price, QTY, and a specific Date
There are lots of Entries per date:
```
Name Price Date
Twin Private $25 06/02/09
Double $35 06/02/09
Single $20 06/02/09
Twin Private $25 06/03/09
Double $35 06/03/09
Single $20 06/03/09
Twin Private $25 06/04/09
Double $35 06/04/09
Single $20 06/04/09
```
How can I condense it into:
```
Name Price_06/02/09 Price_06/03/09 Price_06/04/09
Twin Private $25 $25 $30
Double $35 $35 $50
Single $20 $20 $40
``` | I ended up using something like this:
I'm using mysql, does it support PIVOT?
```
SELECT
name, room_id,
MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 0, price, '')) AS Day1,
MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 1, price, '')) AS Day2,
MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 2, price, '')) AS Day3,
MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 3, price, '')) AS Day4,
MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 4, price, '')) AS Day5,
MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 5, price, '')) AS Day6,
MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 6, price, '')) AS Day7, spots
FROM `availables`
GROUP BY name
``` | I think this will do it:
```
select Name,
max(Price_06/02/09) as Price_06/02/09,
max(Price_06/03/09) as Price_06/03/09,
max(Price_06/04/09) as Price_06/04/09
from (
select Name,
case Date
when '06/02/09' then Price
else null
end as Price_06/02/09,
case Date
when '06/03/09' then Price
else null
end as Price_06/03/09,
case Date
when '06/04/09' then Price
else null
end as Price_06/04/09
from Rates) as Aggregated
group by
Name
```
This works in two stages, the inner query stretches the data out so you'll end up with:
```
Name Price_06/02/09 Price_06/03/09 Price_06/04/09
Twin Private $25 null null
Double $35 null null
Single $20 null null
Twin Private null $25 null
Double null $35 null
Single null $20 null
Twin Private null null $25
Double null null $35
Single null null $20
```
Then the outer query groups by the name to flatten it to:
```
Name Price_06/02/09 Price_06/03/09 Price_06/04/09
Twin Private $25 $25 $25
Double $35 $35 $35
Single $20 $20 $20
``` | condensing query using SQL | [
"",
"sql",
"mysql",
"group-by",
"aggregate",
"sql-order-by",
""
] |
I'd like to embed an html tag in Javascript, between the script> tag
Thanks | Is [E4X](https://developer.mozilla.org/en-US/docs/E4X) what you're looking for? It allows you to embed XML/XHTML within your JavaScript, like this:
```
var someXml = <div><b>Some Text</b></div>;
```
I doubt that's what you need, but that's the only way you can do what you're asking. ~~Also, I don't think it works in Internet Explorer.~~ Scratch that, it *only* works in Firefox.
If that's not what you want, use `document.write()`, as suggested by others.
---
**Edit:** E4X is now deprecated and has been removed from newer versions of Firefox. Don't use it. You should use jQuery, as the answer below me suggests, or simply create the elements via `document.createElement` and friends and inject them into the document. | Hey maybe you're looking for jQuery.
```
$("p").text("<b>Some</b> new text.");
```
See embedded HTML tag.
Write Less, Do More
[jQuery](http://jquery.com/) | embed HTML tag in JavaScript | [
"",
"javascript",
""
] |
I've create a c# application which uses up 150mb of memory (private bytes), mainly due to a big dictionary:
```
Dictionary<string, int> Txns = new Dictionary<string, int>();
```
I was wondering how to free this memory up. I've tried this:
```
Txns = null;
GC.Collect();
```
But it doesn't seem to make much of a dent in my private bytes - they drop from say 155mb to 145mb.
Any clues?
Thanks
-edit-
Okay I'm having more luck with this code (it gets the private bytes down to 50mb), but why?
```
Txns.Clear(); // <- makes all the difference
Txns = null;
GC.Collect();
```
-edit-
Okay for everyone who says 'don't use GC.collect', fair enough (I'm not going to debate that, other than saying you can see my C background coming through), but it doesn't really answer my question:
Why does the garbage collector only free the memory if i clear the transaction list first? Shouldn't it free the memory anyway, since the dictionary has been dereferenced? | Private bytes reflect the process' memory usage. When objects are collected the associated memory segment may or may not be freed to the OS. The CLR manages memory at the OS level and since allocating and freeing memory isn't free there's no reason to free each piece of memory immediately as chances are that the application will probably request more memory later. | If you call `GC.Collect()` it starts to do its job, but returns immediately instead of blocking so you don't see any effect. If you just call `GC.WaitForPendingFinalizers()` it will block your app until `GC.Collect()` has finished its job. | Explicitly freeing memory in c# | [
"",
"c#",
".net",
"memory",
"memory-leaks",
"profiling",
""
] |
I recently ran into a problem where it seems I need a 'static abstract' method. I know why it is impossible, but how can I work around this limitation?
For example I have an abstract class which has a description string. Since this string is common for all instances, it is marked as static, but I want to require that all classes derived from this class provide their own Description property so I marked it as abstract:
```
abstract class AbstractBase
{
...
public static abstract string Description{get;}
...
}
```
It won't compile of course. I thought of using interfaces but interfaces may not contain static method signatures.
Should I make it simply non-static, and always get an instance to get that class specific information?
Any ideas? | Combining static and abstract is somewhat meaningless, yes. The idea behind static is one need not present an instance of the class in order to use the member in question; however with abstract, one expects an instance to be of a derived class that provides a concrete implementation.
I can see why you'd want this sort of combination, but the fact is the only effect would be to deny the implementation use of 'this' or any non-static members. That is, the parent class would dictate a restriction in the implementation of the derived class, even though there's no underlying difference between calling an abstract or 'static abstract' member (as both would need a concrete instance to figure out what implementation to use) | You can't.
The place to do this is with Attributes.
Eg
```
[Name("FooClass")]
class Foo
{
}
``` | C#, implement 'static abstract' like methods | [
"",
"c#",
"static",
"abstract",
""
] |
I am trying to maximize JFrame from within JMenuBar, I can not pass a reference to the frame. Is it possible to get a reference to the frame that it is used in?
i can get to the top level component but it does not have a way to maximize and minimize frame.
```
public Container getApplicationFrame(ActionEvent event){
JMenuItem menuItem = (JMenuItem) event.getSource();
JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent();
Component invoker = popupMenu.getInvoker();
JComponent invokerAsJComponent = (JComponent) invoker;
Container topLevel = invokerAsJComponent.getTopLevelAncestor();
return topLevel;
}
``` | You can get the Window that contains the JPanel via
```
Window window = SwingUtilities.getWindowAncestor(popupMenu);
```
You can then either maximise it using `window.setSize()` -- or, since you seem to know that it's a JFrame, cast it to Frame and use the `setExtendedState` method that Kevin mentions. [Example code](http://www.exampledepot.com/egs/java.awt/frame_FrameIconify.html) from the Java Developers' Almanac for that:
```
// This method minimizes a frame; the iconified bit is not affected
public void maximize(Frame frame) {
int state = frame.getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
frame.setExtendedState(state);
}
``` | Surely you can stash the frame in question in a local variable somewhere?
As for actually maximizing the Frame once you've got ahold of it, Frame.setExtendedState(MAXIMIZED\_BOTH) is probably what you want. [Javadoc](http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Frame.html#setExtendedState(int))
While not as elegant as it could be, quick path to ground on your existing code:
```
public Frame getApplicationFrame(ActionEvent event){
if(event.getSource() == null) return null;
Window topLevel = SwingUtilities.getWindowAncestor(event.getSource());
if(!(topLevel instanceof Frame)) return null;
return (Frame)topLevel;
}
...
//Somewhere in your code
Frame appFrame = getApplicationFrame(myEvent);
appFrame.setExtendedState(appFrame.getExtendedState() | Frame.MAXIMIZED_BOTH);
...
```
Minimum Java version 1.4.2. Be forwarned I have not tested the above code, but you should get the idea. | Controlling JFrame from JMenuBar | [
"",
"java",
"swing",
"jframe",
""
] |
Best reference sites for HTML and JavaScript programming:
* [W3C WebEd Wiki](http://www.w3.org/community/webed/wiki/Main_Page) (this site has a self-teaching curriculum as well as reference material): [HTML](http://www.w3.org/community/webed/wiki/HTML/Elements), [CSS](http://www.w3.org/community/webed/wiki/CSS/Properties)
* W3C Specifications: [HTML4](http://www.w3.org/TR/html4/), [HTML5](http://www.w3.org/TR/html5/) (working draft), [CSS 2.1](http://www.w3.org/TR/CSS2/), [DOM Tech Reports: levels 1-3](http://www.w3.org/DOM/DOMTR)
* ECMAScript: [ECMAScript 5.1](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (PDF), [ECMAScript 3rd Ed.](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf), [Annotated ES 5.1](http://es5.github.com/), [HTML ES 3](http://bclary.com/2004/11/07/)
* SitePoint: [DOM JavaScript](http://reference.sitepoint.com/javascript/domcore), [HTML](http://reference.sitepoint.com/html), [CSS](http://reference.sitepoint.com/css) -- [Search](http://tools.sitepoint.com/codeburner/)
* Mozilla Dev Center: [DOM](https://developer.mozilla.org/En/DOM), [JavaScript](https://developer.mozilla.org/En/JavaScript), [JS Lang](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide), [AJAX](https://developer.mozilla.org/En/AJAX), [HTML](https://developer.mozilla.org/En/HTML), [XHTML](https://developer.mozilla.org/en/XHTML), [SVG](https://developer.mozilla.org/En/SVG), [Standards](https://developer.mozilla.org/en/Web_Standards)
* MSDN: [HTML Elements](http://msdn.microsoft.com/en-us/library/ms533029.aspx), [IE HTML Reference](http://msdn.microsoft.com/en-us/library/hh772960.aspx), [CSS Attributes](http://msdn.microsoft.com/en-us/library/ms533029.aspx), [IE CSS Reference](http://msdn.microsoft.com/en-us/library/ms531209.aspx), [JavaScript Language](http://msdn.microsoft.com/en-us/library/d1et7k7c.aspx), [DOM](http://msdn.microsoft.com/en-us/library/windows/desktop/ms764730.aspx)
* Quirksmode: [DOM Javascript](http://quirksmode.org/js/contents.html), [CSS](http://quirksmode.org/css/contents.html), [Compatibility](http://quirksmode.org/compatibility.html)
* ZVON: [HTML, XML, CSS](http://www.zvon.org/index.php?nav_id=references&mime=html)
* DevGuru - [JavaScript](http://devguru.com/technologies/javascript/home.asp), [HTML](http://devguru.com/technologies/html/home.asp), [CSS](http://devguru.com/technologies/css2/home.asp), [XML, Server-side](http://devguru.com/technologies/technologies.asp)
* Aptana - [DOM0](http://www.aptana.com/reference/html/api/HTMLDOM0.index-frame.html), [DOM1+2](http://www.aptana.com/reference/html/api/HTMLDOM2.index-frame.html), [JavaScript Lang](http://www.aptana.com/reference/html/api/JSKeywords.index.html), [Core](http://www.aptana.com/reference/html/api/JSCore.index-frame.html), [HTML](http://www.aptana.com/reference/html/api/HTML.index.html), [CSS](http://www.aptana.com/reference/html/api/CSS.index.html)
* GotAPI - [DOM JavaScript](http://www.gotapi.com/jsdomw3s), [HTML](http://www.gotapi.com/html), [CSS, Server-side, Multimedia, XML](http://www.gotapi.com/)
* SELFHTML French: [DOM JavaScript](http://fr.selfhtml.org/javascript/index.htm), [HTML](http://fr.selfhtml.org/html/index.htm), [DHTML](http://fr.selfhtml.org/dhtml/index.htm), [CSS](http://fr.selfhtml.org/css/index.htm), [XML](http://fr.selfhtml.org/xml/index.htm), [Server-side](http://fr.selfhtml.org/)
* SELFHTML German: [DOM JavaScript](http://de.selfhtml.org/javascript/index.htm), [HTML](http://de.selfhtml.org/html/index.htm), [DHTML](http://de.selfhtml.org/dhtml/index.htm), [CSS](http://de.selfhtml.org/css/index.htm), [XML](http://de.selfhtml.org/xml/index.htm), [Server-side](http://de.selfhtml.org/)
* Blooberry - [HTML](http://blooberry.com/indexdot/html/index.html), [CSS](http://blooberry.com/indexdot/css/index.html)
* HTMLDog - [HTML](http://htmldog.com/reference/htmltags/), [CSS](http://htmldog.com/reference/cssproperties/)
* W3schools: [DOM](http://www.w3schools.com/htmldom/dom_reference.asp), [JavaScript](http://www.w3schools.com/jsref/default.asp), [HTML, CSS, XML, Multimedia, Server-side](http://www.w3schools.com/sitemap/sitemap_references.asp)\*
\*There is some controversy over the quality and accuracy of the information in the tutorials offered by W3Schools. Not as many, however, take issue with the reference section.
---
Related questions, mostly the source of the above links:
* [What is the best online javascript/css/html/xhtml/dom reference?](https://stackoverflow.com/questions/63918/what-is-the-best-online-javascript-css-html-xhtml-dom-reference)
* [Best resources to learn JavaScript](https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript)
* [Good javascript reference](https://stackoverflow.com/questions/458453/good-javascript-reference/458474) | I find the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/Guide) very helpful.
Steve | [MSDN](http://msdn.microsoft.com/library/) has a lot of reference materials for [web development](http://msdn.microsoft.com/library/aa155073(en-us).aspx). It contains only IE-specific information which can be either an advantage or a disadvantage depending on what you are looking for. Here are direct links to the [HTML/CSS](http://msdn.microsoft.com/library/aa155133(en-us).aspx) (includes DOM), [JScript](http://msdn.microsoft.com/library/hbxc2t98(en-us,VS.85).aspx) (Microsoft flavor of ECMAScript aka JavaScript) and [VBScript](http://msdn.microsoft.com/library/t0aew7h6(en-us,VS.85).aspx). The documentation is very well written, and is a great source for answers to DOM/JavaScript questions, since they tend to be mostly the same across browsers.
Also, as references go, let's not forget the official specifications for [HTML](http://www.w3.org/html/), [CSS](http://www.w3.org/Style/CSS/), and the myriad of other standards specified by [W3C](http://www.w3.org/). | What are some of the best reference sites for HTML and JavaScript programming | [
"",
"javascript",
"html",
"reference",
""
] |
Javascript Confirm popup, I want to show Yes, No button instead of OK and Cancel.
I have used this vbscript code:
```
<script language="javascript">
function window.confirm(str) {
execScript('n = msgbox("' + str + '","4132")', "vbscript");
return (n == 6);
}
</script>
```
this only works in IE, In FF and Chrome, it doesn't work.
Is there any workround to achieve this in Javascript?
I also want to change the title of popup like in IE 'Windows Internet Explorer' is shown, I want to show here my own application name. | Unfortunately, there is no cross-browser support for opening a confirmation dialog that is not the default OK/Cancel pair. The solution you provided uses VBScript, which is only available in IE.
I would suggest using a Javascript library that can build a DOM-based dialog instead. Try Jquery UI: <http://jqueryui.com/> | The only way you can accomplish this in a cross-browser way is to use a framework like jQuery UI and create a custom Dialog:
**[jquery Dialog](http://jqueryui.com/demos/dialog/)**
It doesn't work in exactly the same way as the built-in confirm popup but you should be able to make it do what you want. | Javascript Confirm popup Yes, No button instead of OK and Cancel | [
"",
"javascript",
"html",
"button",
"popup",
"confirm",
""
] |
Why should I sign my JAR files?
I know that I need to sign my client-side JAR files (containing Applets) so that special things like filesystem access can be done, and so that the annoying bit at the bottom of windows doesn't show, but why else? And do I need to sign my server-side JAR files containing Servlets, etc.?
Some basic rules for when and when not to sign JARs would be appreciated - thanks! | The short answer - don't, unless your company policy forces you to.
The long answer
Signing jars is effectively telling your customer "I made this, and I guarantee it won't mess up your system. If it does, come to me for retribution". This is why signed jars in client-side solution deployed from remote servers (applets / webstart) enjoy higher privileges than non-signed solutions do.
On server-side solutions, where you don't have to to placate the JVM security demands, this guarantee is only for your customer peace of mind.
The bad thing about signed jars is that they load slower than unsigned jars. How much slower? it's CPU-bound, but I've noticed more than a 100% increase in loading time. Also, patches are harder (you have to re-sign the jar), class-patches are impossible (all classes in a single package must have the same signature source) and splitting jars becomes a chore. Not to mention your build process is longer, and that proper certificates cost money (self-signed is next to useless).
So, unless your company policy forces you to, don't sign jars on the server side, and keep common jars in signed and non-signed versions (signed go to the client-side deployment, non-signed go to server-side codebase). | Signing a jar file, just like using certificates in other contexts, is done so that people using it know where it came from. People may trust that Chris Carruthers isn't going to write malicious code, and so they're willing to allow your applet access to their file system. The signature gives them some guarantee that the jar really was created by you, and not by an impostor or someone they don't trust.
In the case of server-side or library jars, there's usually no need to provide that kind of guarantee to anybody. If it's your server, then you know what jars you're using and where they came from, and you probably trust your own code not to be malicious. | Why should I sign my JAR files? | [
"",
"java",
"jar",
"signed-applet",
""
] |
Currently, I have the following c# code to extract a value out of text. If its XML, I want the value within it - otherwise, if its not XML, it can just return the text itself.
```
String data = "..."
try
{
return XElement.Parse(data).Value;
}
catch (System.Xml.XmlException)
{
return data;
}
```
I know exceptions are expensive in C#, so I was wondering if there was a better way to determine if the text I'm dealing with is xml or not?
I thought of regex testing, but I dont' see that as a cheaper alternative. Note, I'm asking for a *less expensive* method of doing this. | You could do a preliminary check for a < since all XML has to start with one and the bulk of all non-XML will not start with one.
(Free-hand written.)
```
// Has to have length to be XML
if (!string.IsNullOrEmpty(data))
{
// If it starts with a < after trimming then it probably is XML
// Need to do an empty check again in case the string is all white space.
var trimmedData = data.TrimStart();
if (string.IsNullOrEmpty(trimmedData))
{
return data;
}
if (trimmedData[0] == '<')
{
try
{
return XElement.Parse(data).Value;
}
catch (System.Xml.XmlException)
{
return data;
}
}
}
else
{
return data;
}
```
I originally had the use of a regex but Trim()[0] is identical to what that regex would do. | The code given below will match all the following xml formats:
```
<text />
<text/>
<text />
<text>xml data1</text>
<text attr='2'>data2</text>");
<text attr='2' attr='4' >data3 </text>
<text attr>data4</text>
<text attr1 attr2>data5</text>
```
And here's the code:
```
public class XmlExpresssion
{
// EXPLANATION OF EXPRESSION
// < : \<{1}
// text : (?<xmlTag>\w+) : xmlTag is a backreference so that the start and end tags match
// > : >{1}
// xml data : (?<data>.*) : data is a backreference used for the regex to return the element data
// </ : <{1}/{1}
// text : \k<xmlTag>
// > : >{1}
// (\w|\W)* : Matches attributes if any
// Sample match and pattern egs
// Just to show how I incrementally made the patterns so that the final pattern is well-understood
// <text>data</text>
// @"^\<{1}(?<xmlTag>\w+)\>{1}.*\<{1}/{1}\k<xmlTag>\>{1}$";
//<text />
// @"^\<{1}(?<xmlTag>\w+)\s*/{1}\>{1}$";
//<text>data</text> or <text />
// @"^\<{1}(?<xmlTag>\w+)((\>{1}.*\<{1}/{1}\k<xmlTag>)|(\s*/{1}))\>{1}$";
//<text>data</text> or <text /> or <text attr='2'>xml data</text> or <text attr='2' attr2 >data</text>
// @"^\<{1}(?<xmlTag>\w+)(((\w|\W)*\>{1}(?<data>.*)\<{1}/{1}\k<xmlTag>)|(\s*/{1}))\>{1}$";
private const string XML_PATTERN = @"^\<{1}(?<xmlTag>\w+)(((\w|\W)*\>{1}(?<data>.*)\<{1}/{1}\k<xmlTag>)|(\s*/{1}))\>{1}$";
// Checks if the string is in xml format
private static bool IsXml(string value)
{
return Regex.IsMatch(value, XML_PATTERN);
}
/// <summary>
/// Assigns the element value to result if the string is xml
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryParse(string s, out string result)
{
if (XmlExpresssion.IsXml(s))
{
Regex r = new Regex(XML_PATTERN, RegexOptions.Compiled);
result = r.Match(s).Result("${data}");
return true;
}
else
{
result = null;
return false;
}
}
}
```
Calling code:
```
if (!XmlExpresssion.TryParse(s, out result))
result = s;
Console.WriteLine(result);
``` | Better way to detect XML? | [
"",
"c#",
"xml",
"optimization",
"xml-parsing",
""
] |
If I use SubSonic to create DAL for my web project do I need to worry about preventing SQL Injection Attacks? | This depends on how you construct your queries. It is totally possible to write unsafe queries with subsonic if you don't use parameters.
```
// Bad example:
string sql = "delete from Products where ProductName = " + rawUserInput;
QueryCommand qry = new QueryCommand(sql, Product.Schema.Provider.Name);
DataService.ExecuteQuery(qry);
// Should be:
string sql = "delete from Products where ProductName = @TargetName";
QueryCommand qry = new QueryCommand(sql, Product.Schema.Provider.Name);
qry.AddParamter("@TargetName", rawUserInput, DbType.String);
DataService.ExecuteQuery(qry);
``` | No, SubSonic uses parameters to pass data into the database, it takes care of this. | Sql Injection Attacks and Subsonic | [
"",
"c#",
"subsonic",
"sql-injection",
""
] |
[Protocol Buffers](http://code.google.com/p/protobuf/) (protobuf) are a way of encoding structured data in an efficient yet extensible format.
There's [plugin](http://code.google.com/p/protobuf-netbeans-plugin/) for Netbeans, but I cannot find one for Eclipse. Does it exist? If yes, please, share the link.
Thanks. | I recommend using Google's "Protocol Buffers Development Tools". It is a plugin for Eclipse that features automagic regeneration and error checking with quick fixes, among other things.
It's available here: <https://github.com/google/protobuf-dt/blob/master/README.md> . | It does [not seem to be approved by Eclipse yet](http://dev.eclipse.org/mhonarc/lists/higgins-dev/msg05454.html).
And the [EMF project uses protobuf](http://dev.eclipse.org/newslists/news.eclipse.tools.emf/msg39525.html), but not as a plugin.
So for now, no there do not seem to be any Eclipse protobuf plugin. | Eclipse plugin for working with protobuf | [
"",
"java",
"eclipse",
"eclipse-plugin",
"protocol-buffers",
""
] |
Im currently reading Code Complete by Steve McConnell, specifically page 295 on floating-point numbers.
When i ran the following code:
```
double nominal = 1.0;
double sum = 0.0;
for (int i = 0; i < 10; i++)
{
sum += 0.1;
Console.WriteLine("sum: " + sum.ToString());
}
if (equals(nominal,sum))
{
Console.WriteLine("Numbers are the same");
}
else
{
Console.WriteLine("Numbers are different");
}
```
I got a print out of
*0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Numbers are different*
How come I didn't get the output that is suppose to happen?
ie:
*0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.79999999999999999
0.89999999999999999
0.99999999999999999
Numbers are different*
Is C# rounding numbers when I do an implicit conversion from double to string? I think so because when i debug the application and step through the for loop, i can see the non-terminating repeating decimal numbers. What do you think? Am i right or wrong? | double.ToString() uses the general format which defaults to 15 decimal places if the precision is not specified. So it does do a little rounding which is why you're seeing what you're seeing. For example 0.89999999999999999 which you specified in your question is 17 decimal places. You could actually see the entire number by doing `sum.ToString("g17")`.
You can find .net's Standard Numeric Format Strings and their default precision here: <http://msdn.microsoft.com/en-us/library/dwhawy9k(VS.80).aspx> | It is is in the ToString default behaviour. If you look at sum in the debugger you get this, which shows you the value without routing through ToString:
```
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.79999999999999993
0.89999999999999991
```
Indicating that the underlying behaviour is as you would expect.
hth | Printing increments of 0.1 in c# | [
"",
"c#",
"floating-point",
""
] |
I am new in Jquery.
I want to use sortableUI to my datalist. Each row in datalist contains
text with serial number. I have used sortable ui successfully. But now
I want move the text not the serial number while sorting.
Here is my Example Code. The div displays the serial number at the
top-left corner of each li. Now If I try to strat dragging for
instance 2nd Li with 3rd li then 3rd item goes to 2nd position as
rule but problem is that it goes after 2nd item's div (where it should
be before div like first load). As a result, according to div's
style.. serial no 1 and 2 overlap at 1st item's position.
Is there any way i could use to keep the div just after it's
corresponding li while sorting?
```
<ul id="ulSortable" class="ui-sortable" >
<li class="Decide_Rank_Item_Li">test A</li>
<div class="DisplayOrder">1</div>
<li class="Decide_Rank_Item_Li">Test B</li>
<div class="DisplayOrder">2</div>
<li class="Decide_Rank_Item_Li">Test C</li>
<div class="DisplayOrder">3</div>
<li class="Decide_Rank_Item_Li">Test D</li>
<div class="DisplayOrder">4</div>
</ul>
```
Image Before sorting:
[Can't see image](http://i41.tinypic.com/34fzaqp.png)
Now if I start moving a slight, u can see the div containing serial no still shows at right place
[Can't see image](http://i42.tinypic.com/14n0ll5.png)
---
## After sorting 2nd item to 3rd
```
<ul id="ulSortable" class="ui-sortable" >
<li class="Decide_Rank_Item_Li">test A</li>
<div class="DisplayOrder">1</div>
<div class="DisplayOrder">2</div>
<li class="Decide_Rank_Item_Li">Test C</li>
<li class="Decide_Rank_Item_Li">Test B</li>
<div class="DisplayOrder">3</div>
<li class="Decide_Rank_Item_Li">Test D</li>
<div class="DisplayOrder">4</div>
</ul>
```
Image after sorting:
## [Can't see image](http://i42.tinypic.com/180n4x.png)
The style of Li and Div are shown here
Style:
```
.Decide_Rank_Item_Li
{
position: relative;
display: block;
border-color: #C0C0C0;
border-width: 1px;
border-style: solid;
vertical-align: bottom;
width: 110px;
height: 100px;
float:left;
background-color: #F8F8F8;
}
.DisplayOrder
{
position: relative;
display: block;
float: left;
top: 5px;
left: -105px;
z-index: 100;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
padding: 0px;
margin: 0px;
width: 0px;
clear: right;
color: #808080;
}
``` | Just thought of an alternate solution that is a little more elegant: <http://jsbin.com/udina>
```
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
li {
width: 100px;
height: 100px;
float: left;
background: #F8F8F8;
border: 1px solid #C0C0C0;
list-style-position: inside;
color: #C0C0C0;
}
div {
text-align: center;
color: #C0C0C0;
font-size: 120%;
}
.placeholder {
list-style-type:decimal;
}
</style>
</head>
<body>
<ol>
<li><div>Test Content A</div></li>
<li><div>Test Content B</div></li>
<li><div>Test Content C</div></li>
<li><div>Test Content D</div></li>
<li><div>Test Content E</div></li>
<li><div>Test Content F</div></li>
<li><div>Test Content G</div></li>
<li><div>Test Content H</div></li>
<li><div>Test Content I</div></li>
<li><div>Test Content J</div></li>
<li><div>Test Content K</div></li>
<li><div>Test Content L</div></li>
<li><div>Test Content M</div></li>
<li><div>Test Content N</div></li>
<li><div>Test Content O</div></li>
<li><div>Test Content P</div></li>
<li><div>Test Content Q</div></li>
<li><div>Test Content R</div></li>
<li><div>Test Content S</div></li>
<li><div>Test Content T</div></li>
<li><div>Test Content U</div></li>
<li><div>Test Content V</div></li>
<li><div>Test Content W</div></li>
<li><div>Test Content X</div></li>
<li><div>Test Content Y</div></li>
<li><div>Test Content Z</div></li>
</ol>
<script>
$(function(){
$('ol').sortable({
helper: function(evt, el){
return el.clone().css('color', '#F8F8F8');
},
placeholder: 'placeholder'
});
});
</script>
</body>
</html>
``` | I had to change the HTML and CSS but I think this achieves the effect you were after.
Here's a hosted demo: <http://jsbin.com/erigu> (Editable via <http://jsbin.com/erigu/edit>)
```
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<style type="text/css" media="screen">
* { margin: 0; padding: 0; }
#numbers>div, #sortables>div {
width: 110px;
height: 100px;
float: left;
border: 1px solid #C0C0C0;
}
#numbers>div {
padding-bottom: 20px;
font: bold 12px Arial, Helvetica, sans-serif;
color: #808080;
background-color: #F8F8F8;
}
#sortables>div {
padding-top: 20px;
text-align: center;
color: black;
}
#sortables {
position: absolute;
left: 0px;
}
</style>
</head>
<body>
<div id="numbers">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div id="sortables">
<div>Test A</div>
<div>Test B</div>
<div>Test C</div>
<div>Test D</div>
</div>
<script>
$(function(){
$('#sortables').sortable({
/*
The helper option allows you to customize the dragged element.
in this case we are adding a background.
*/
helper: function(evt, el){
return el.clone().css({background:'#F8F8F8'});
}
});
});
</script>
</body>
</html>
``` | sort combination of <li> and <div> using jquery | [
"",
"javascript",
"jquery",
"jquery-ui-sortable",
""
] |
In a [Visual C++](http://en.wikipedia.org/wiki/Visual_C++#32-bit_versions) 2008 project, building a project will display following information in the output window:
```
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>Compiling...
1>main.cpp
1>test1.cpp
1>test2.cpp
1>Generating Code...
1>Linking...
1>LINK : test.exe not found or not built by the last incremental link; performing full link
1>Project1- 0 error(s), 0 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
```
**How can I get output like this:**
```
cl.exe /Od /I "includepath" /D "_UNICODE" /FD /EHsc /RTC1 /MDd /Zc:wchar_t- /Fo"Debug\\" /Fd"Debug\vc90.pdb" /nologo /c /ZI /TP /errorReport:prompt
```
Like a C# project will do it. | This is controlled via the "Suppress startup banner" setting in the "General" sub-tab of the "C/C++" tab in the project's property pages. If you set it to "No", it will show in the Output window the command line being used during compilation. | Switch on build logging (menu *Tools* → *Options* → *Projects and Solutions* → *VC++ Project Settings* → *Build Logging*). You should then get a build log (BuildLog.htm) in your intermediate files directory which contains all the information you need, including error messages. You will also get a `Ctrl`-clickable link in the output window to display the build log. | How do I show command-line build options in Visual C++ 2008? | [
"",
"c++",
"visual-studio",
""
] |
Well, I've looked all over the internet and just haven't been able to find an answer to this question, so maybe someone can provide some insight.
I'm working on developing a relatively simple Java app that will replace a Word doc currently used for system access requests. It's designed to allow form entry of new employee hire information - name, access needed, and so forth.
So here's my problem. Trying to make a GUI with all of the text fields and everything is surprisingly painful. Because each widget is a bit different, getting the input once the form is filled out seems to require a separate reference for each widget so I can call them individually. This means each panel for a section has 6-10 different private fields. (I attempted adding all the similar widgets to a list and calling them in a loop but that didn't seem to work.)
It seems that a web form would be a better fit for this in some ways but I don't have the infrastructure available to do that. Has anyone out there found a better solution than this for something similar? It just seems like a ton of code. Please see below for an idea (I put in some comments rather than actual code because it is so long). Thanks for looking!
```
private JComboBox my_dates;
private JTextField my_date1;
private JTextField my_date2;
private JTextField my_request_date;
private JTextField my_new_legal_name;
private JTextField my_new_pref_name;
private JTextField my_new_username;
private JTextField my_prev_legal_name;
private JTextField my_prev_pref_name;
private JTextField my_prev_username;
private JTextField my_emp_id;
private JTextField my_manager;
private JTextField my_auth_requestor;
private JTextField my_auth_phone;
public NameChangePanel(FormSection the_section)
{
super();
initialize();
buildPanel(the_section.getFields());
}
private void initialize()
{
// Create all the widgets individuall
}
private void buildPanel(List the_fields)
{
// add a field label
// add a component
// repeat for all values
}
public List getFormValues()
{
// Call all of the private fields individually
return values;
}
}
``` | Vanilla Swing is verbose - no argument there. Basically for this kind of thing I end up relying on a bunch of home-grown util/factory methods like createTextBox() that is parameterized for common usage and will execute the 3-8 statements necessary.
I will sometimes even parameterize the layout. I tend to reduce all layout to GridBagLayout (others do BorderLayout, etc; it's just a matter of personal preference) and then create methods that'll put a control at a particular point in the grid.
If you're not going Web-based, I would just stick with Swing. It might be verbose but it's not really all that difficult for a simple form. | Call me crazy but I dislike gui builders. I prefer the extra control that hand-coding brings. Also, as you wrote the code yourself it makes it far easier to debug. What is important is to layout your code in a logical order and to use methodical variable names.
You mentioned trying to use a list. However, I don't see how this is going to save you much time at all (or as I hinted eariler, what time you'll save on implementation, you'll lose during the debugging process). I'm guessing that the headaches are starting when you start sanity-checking the input of your JTextFields. I'd suggest subclassing JTextField into MoneyTextField, PhoneNumberTextField, etc. which can be used to setup the ActionListener to stop people doing stupid things. | Creating a Java GUI in Swing for form input | [
"",
"java",
"user-interface",
"swing",
""
] |
I would like to catch every undefined function error thrown. Is there a global error handling facility in JavaScript? The use case is catching function calls from flash that are not defined. | Does this help you:
```
<script>
window.onerror = function() {
alert("Error caught");
};
xxx();
</script>
```
I'm not sure how it handles Flash errors though...
Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:
[Mimic Window. onerror in Opera using javascript](https://stackoverflow.com/questions/645840/mimic-window-onerror-in-opera-using-javascript) | # How to Catch Unhandled Javascript Errors
Assign the `window.onerror` event to an event handler like:
```
<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues
var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
</script>
```
As commented in the code, if the return value of `window.onerror` is `true` then the browser should suppress showing an alert dialog.
## When does the window.onerror Event Fire?
In a nutshell, the event is raised when either 1.) there is an uncaught exception or 2.) a compile time error occurs.
> **uncaught exceptions**
>
> * throw "some messages"
> * call\_something\_undefined();
> * cross\_origin\_iframe.contentWindow.document;, a security exception
>
> **compile error**
>
> * `<script>{</script>`
> * `<script>for(;)</script>`
> * `<script>"oops</script>`
> * `setTimeout("{", 10);`, it will attempt to compile the first argument as
> a script
## Browsers supporting window.onerror
* Chrome 13+
* Firefox 6.0+
* Internet Explorer 5.5+
* Opera 11.60+
* Safari 5.1+
## Screenshot:
Example of the onerror code above in action after adding this to a test page:
```
<script type="text/javascript">
call_something_undefined();
</script>
```

## Example for AJAX error reporting
```
var error_data = {
url: document.location.href,
};
if(error != null) {
error_data['name'] = error.name; // e.g. ReferenceError
error_data['message'] = error.line;
error_data['stack'] = error.stack;
} else {
error_data['msg'] = msg;
error_data['filename'] = filename;
error_data['line'] = line;
error_data['col'] = col;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax/log_javascript_error');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('JS error logged');
} else if (xhr.status !== 200) {
console.error('Failed to log JS error.');
console.error(xhr);
console.error(xhr.status);
console.error(xhr.responseText);
}
};
xhr.send(JSON.stringify(error_data));
```
## JSFiddle:
<https://jsfiddle.net/nzfvm44d/>
## References:
* [Mozilla Developer Network :: window.onerror](https://developer.mozilla.org/en/DOM/window.onerror)
* [MSDN :: Handling and Avoiding Web Page Errors Part 2: Run-Time Errors](http://msdn.microsoft.com/en-us/library/ms976144.aspx)
* [Back to Basics – JavaScript onerror Event](http://blogs.microsoft.co.il/blogs/gilf/archive/2011/11/23/back-to-basics-javascript-onerror-event.aspx)
* [DEV.OPERA :: Better error handling with window.onerror](http://dev.opera.com/articles/view/better-error-handling-with-window-onerror/)
* [Window onError Event](http://www.mattsnider.com/window-onerror-event/)
* [Using the onerror event to suppress JavaScript errors](http://www.javascriptkit.com/javatutors/error2.shtml)
* [SO :: window.onerror not firing in Firefox](https://stackoverflow.com/q/1008692/590956) | JavaScript global event mechanism | [
"",
"javascript",
"dom-events",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.