Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Say I have the following code snippet in c# ``` static const bool DO_PERFORMANCE_CODE = false; if (DO_PERFORMANCE_CODE) { // performance monitoring code goes here } ``` Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.
When you build in "debug" the preprocessor variable DEBUG is defined. So, you can do this: ``` public void MyFunc() { //do release stuff #if DEBUG //do performance testing #endif //finish release stuff } ``` and it will be ignored by the compiler when you switch to Release mode. Alternatively, you can define your own preprocessor variable if you don't want to test in debug mode, making sure to "#define PERFORMANCE\_TESTING" when you want to test, and commenting it out when you don't. ``` #define PERFORMANCE_TESTING public void MyFunc() { //do release stuff #if PERFORMANCE_TESTING //do performance testing #endif //finish release stuff } ```
Defining your own symbols is probably cleaner, but I was curious as to what the compiler would do, so I did some experimenting (using VS 2008 in release mode). With this: ``` class Program { static void Main(string[] args) { bool foo = false; if (foo) { Console.WriteLine("Hello, world?"); } } } ``` The compiler still generates the code for the if statement: ``` .method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 16 (0x10) .maxstack 1 .locals init ([0] bool foo) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brfalse.s IL_000f IL_0005: ldstr "Hello, world\?" IL_000a: call void [mscorlib]System.Console::WriteLine(string) IL_000f: ret } // end of method Program::Main ``` If instead you do: ``` class Program { static void Main(string[] args) { bool foo = false; if (false) { Console.WriteLine("Hello, world?"); } } } ``` It doesn't generate code for the if statement: ``` .method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Program::Main ``` It also seems to skip the variable that is assigned a value that is never used. I checked with ildasm.exe, the disassembler that comes with visual studio.
Will conditionals that are always false be removed by compiler in C#
[ "", "c#", ".net", "performance", "" ]
Under what circumstances is an enum more appropriate than, for example, a Collection that guarantees unique elements (an implementer of java.util.Set, I guess...)? (This is kind of a follow up from my previous [question](https://stackoverflow.com/questions/478403/can-i-add-and-remove-elements-of-enumeration-at-runtime-in-java))
Basically when it's a well-defined, fixed set of values which are known at compile-time. You can use an enum as a set very easily (with [EnumSet](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumSet.html)) and it allows you to define behaviour, reference the elements by name, switch on them etc.
When the elements are known up front and won't change, an enum is appropriate. If the elements can change during runtime, use a Set.
When to use Enum or Collection in Java
[ "", "java", "enums", "set", "" ]
I have an app which consists of several different assemblies, one of which holds the various interfaces which the classes obey, and by which the classes communicate across assembly boundaries. There are several classes firing events, and several which are interested in these events. My question is as follows: is it good practice to implement a central EventConsolidator of some kind? This would be highly coupled, as it would need to know every class (or at least interface) throwing an event, and every consumer of an event would need to have a reference to EventConsolidator in order to subscribe. Currently I have the situation where class A knows class B (but not C), class B knows class C, etc. Then if C fires an event B needs to pick it up and fire its own event in order for A to respond. These kinds of chains can get quite long, and it may be that B is only interested in the event in order to pass it along. I don't want A to know about C though, as that would break encapsulation. What is good practice in this situation? Centralise the events, or grin and bear it and define events in each intermediate class? Or what are the criteria by which to make the decision? Thanks! Edit: [Here](https://stackoverflow.com/questions/217233/bubbling-up-events) is another question asking essentially the same thing.
You could put the event itself in an interface, so that A didn't need to know about C directly, but only that it has the relevant event. However, perhaps you mean that the instance of A doesn't have sight of an instance of C... I would try to steer clear of a centralised event system. It's likely to make testing harder, and introduced tight coupling as you said. One pattern which is worth knowing about is making event proxying simple. If B only exposes an event to proxy it to C, you can do: ``` public event FooHandler Foo { add { c.Foo += value; } remove { c.Foo -= value; } } ``` That way it's proxying the subscription/unsubscription rather than the act of raising the event. This has an impact on GC eligibility, of course - which may be beneficial or not, depending on the situation. Worth thinking about though.
What you could try is using the event brokering of either [NInject](http://ninject.org/ "NInject Homepage") or the [Unity Application Block](http://www.codeplex.com/unity "Unity Homepage"). This allows you to, for example: ``` [Publish("foo://happened")] public event EventHandler<FooArgs> FooHappened; [Subscribe("foo://happened")] public void Foo_Happened(object sender, FooArgs args) { } ``` If both objects are created through the container the events will be hooked up automatically.
C# Best practice: Centralised event controller or not
[ "", "c#", "events", "architecture", "" ]
Given a variable `foo` of type `FooClass*` and a member variable in that class named `bar`, is the distance between `foo` and `&(foo->bar)` the same in any situation with some constraints: 1. `FooClass` is a non-POD type. 2. We know that `foo` will always point to an instance of `FooClass`, and not some subtype of it. 3. We only care about behaviour under a single compiler and a single compilation; that is, the value this may result in under gcc is never used in code compiled with MSVC, and it is never saved to be re-used between compilations. It is computed in the binary and used in the binary, and that is it. 4. We don't use a custom `new`, although some instances of the class may be stack-allocated and some heap-allocated. 5. There is no explicit `ctor` for `FooClass`; it relies upon the compiler-generated one (and each of the fields in `FooClass` is either POD or default-constructable). I can't find a guarantee either way on this in the standard (nor did I expect to), but my rudimentary testing with gcc leads me to believe that it will always be the case there. I also know that this guarantee is made for POD-types, but let us assume this type can't be POD. **An update/clarification:** this is just for a single compilation of a single binary; the calculated offsets will never leave that single execution. Basically, I want to be able to uniquely identify the fields of a class in a static map and then be able to lookup into that map for some macro/template/EVIL trickery. It is merely for my own amusement, and no life support machines will rely on this code.
After you have compiled your program, **Yes\***. The offset will remain constant. There is one very important restriction, however: **foo must be pointing specifically to a FooClass object**. Not a class derived from FooClass, or anything else for that matter. The reason that C++ makes the POD distinction regarding member offsets is because both multiple inheritance and the location (or lack of) a vtable pointer can create situations where the address of an object is not the same as the address of that object's base.
I'm no expert but i gonna try answering you anyway :) 1. FooClass is a non-POD type. This mean it could have more than one sections of `private`, `public` or `protected`. Within such a section, the order is that of the definition of the members, but across those sections, order is arbitrary and unspecified. 2. foo will always point to FooClass. Well so we have guarantee there is no offset adjustment done. At least in one compilation, offsets will be the same then (don't have the backing up Standard quote. But it can't work if they were different). 3. We only care about behavior on a single compiler. Well since the order of members is unspecified across sections of access modifiers and the compiler is allowed to put padding between members, this won't buy us much. 4. We only care about objects on the stack (automatic storage duration). Well i don't see how that changes anything of the object layout. So after all i don't think you have any guarantee that the offset will be constant across compilations. For considerations within one compilation (so if we would play with a compiler whose generated code uses an ABI that changes with each different compilation), the offset just can't be different. But even if you know the offset, you can't access the member. Your only way to access a member is using the member access operator `->` and `.` (that's said in 9.2/9). Why not use data member pointers? They allow accessing members safely. Here is an example: ([looking up members by name](https://stackoverflow.com/questions/286402/initializing-struct-using-an-array#287353)).
C++ experts: is the offset of a member variable to its class constant under these conditions?
[ "", "c++", "" ]
OK, I'm designing a site and thought I'd stick some jQuery in as I really need so js experience. Page with my problem is here: <http://new.focalpix.co.uk/moreinfo.php> JS in question is: ``` $(document).ready(function(){ $(".answer").css("display","none"); $("#maincontent a.animate").click(function() { $("#maincontent .answer").slideUp('slow'); var id = $(this).attr('href'); $(id).slideDown('slow'); return false; }); }); ``` This works fine, but if you click on a link where the answer has already slid down, then it slides up, then back down again. I'm not sure on the cleanest way to stop this happening - any ideas?
First, I'd suggest the following structure for your faq's: ``` <div id="faq"> <div class="qa" id="faq_greenandflies"> <span class="q">What is <a href="#faq_greenandflies">green and flies</a></span> <div class="a"> Super Pickle! </div> </div> <div class="qa" id="faq_redandbadforteeth"> <span class="q">What is <a href="#faq_redandbadforteeth">Red and bad for your teeth</a></span> <div class="a"> a Brick </div> </div> <!-- More FAQ's here --> </div> ``` and then defining your jQuery as follows: ``` <script type="text/javascript"> $(function(){ // hide all answers $('div#faq .qa .a').hide(); // bind a click event to all questions $('div#faq .qa .q a').bind( 'click', function(e){ // roll up all of the other answers (See Ex.1) $(this).parents('.qa').siblings().children('.a').slideUp(); // reveal this answer (See Ex.2) $(this).parents('.qa').children('.a').slideDown(); // return true to keep any other click events return true; }); // check location.hash to see if we need to expand one (direct link) $(location.hash).find('.q a').click(); }); </script> ``` Explanation: (Ex.1) * *this* is the link that was clicked * get the element that contains *this* and has a class of 'qa' (the box that contains both question and answer) * select all of its siblings. (we now have all qa's as a jQ object) * hide the answers (Ex.2) * *this* is the line or link that was clicked * get the element that contains *this* and has a class of 'qa' (the box that contains both question and answer) * reveal the answer A **working demo** is [here](http://yaauie.com/stackoverflow/433802/). This does several things for you: * If a user [deep-links to an answer](http://yaauie.com/stackoverflow/433802/#whiteandrocky), the answer is automatically revealed * If a user clicks on one answer, all other answers are hidden * You can give your divs proper ids, so which helps search engine optimization of links to individual answers
You should be using the [.slideToggle()](http://docs.jquery.com/Effects/slideToggle) effect. ``` $(document).ready(function() { $(".answer").css("display","none"); $("#maincontent a.animate").click(function() { $("#maincontent .answer").slideToggle('slow'); }); }); ```
Getting my head around jQuery
[ "", "javascript", "jquery", "" ]
I am trying to write a JTextPane which supports some sort of coloring: as the user is typing the text, I am running some code that colors the text according to a certain algorithm. This works well. The problem is that the coloring operations is registered with the undo manager (a DefaultDocumentEvent with EventType.CHANGE). So when the user clicks undo the coloring disappears. Only at the second undo request the text itself is rolled back. (Note that the coloring algorithm is somewhat slow so I cannot color the text as it is being inserted). If I try to prevent the CHANGE events from reaching the undo manager I get an exception after several undo requests: this is because the document contents are not conforming to what the undoable-edit object expects. Any ideas?
You could intercept the CHANGE edits and wrap each one in another UndoableEdit whose `isSignificant()` method returns `false`, before adding it to the UndoManager. Then each Undo command will undo the most recent INSERT or REMOVE edit, plus every CHANGE edit that occurred since then. Ultimately, I think you'll find that the styling mechanism provided by JTextPane/StyledDocument/etc. is too limited for this kind of thing. It's slow, it uses too much memory, and it's based on the same Element tree that's used to keep track of the lexical structure of the document. It's okay (I guess) for applications in which the styles are applied by the user, like word processors, but not for a syntax highlighter that has to update the styles constantly as the user types. There are several examples out there of syntax-highlighting editors based on custom implementations of the Swing `JTextComponent`, `View` and `Document` classes. Some, like JEdit, re-implement practically the whole `javax.swing.text` package, but I don't think you need to go that far.
How are you trying to prevent the CHANGE events from reaching the undo manager? Can you not send the UndoManager a lastEdit().die() call immediately after the CHANGE is queued?
Hide certain actions from Swing's undo manager
[ "", "java", "swing", "undo", "" ]
I am programming with normal pointers, but I have heard about libraries like Boost that implement smart pointers. I have also seen that in Ogre3D rendering engine there is a deep use of shared pointers. What exactly is the difference between the three, and should I stick on using just a type of them?
Sydius outlined the types fairly well: * **Normal pointers** are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point. * **Smart pointers** are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the [RAII](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as *releasing* the pointer, allowing someone else to own it. Copying them does not make sense. * **Shared pointers** is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted. How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure. There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base. There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer. The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.
the term "smart pointer" *includes* shared pointers, auto pointers, locking pointers and others. you meant to say auto pointer (more ambiguously known as "owning pointer"), not smart pointer. Dumb pointers (T\*) are never the best solution. They make you do explicit memory management, which is verbose, error prone, and sometimes nigh impossible. But more importantly, they don't signal your intent. Auto pointers delete the pointee at destruction. For arrays, prefer encapsulations like vector and deque. For other objects, there's very rarely a need to store them on the heap - just use locals and object composition. Still the need for auto pointers arises with functions that return heap pointers -- such as factories and polymorphic returns. Shared pointers delete the pointee when the last shared pointer to it is destroyed. This is useful when you want a no-brainer, open-ended storage scheme where expected lifetime and ownership can vary widely depending on the situation. Due to the need to keep an (atomic) counter, they're a bit slower than auto pointers. Some say half in jest that shared pointers are for people who can't design systems -- judge for yourself. For an essential counterpart to shared pointers, look up weak pointers too.
Pointers, smart pointers or shared pointers?
[ "", "c++", "pointers", "" ]
I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python. I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution? The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.
You can look at the [Django framework](http://www.djangoproject.com) (but take their licence into account!) for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly. The Django text utils define a function, [`slugify()`](https://docs.djangoproject.com/en/4.0/ref/utils/#django.utils.text.slugify), that's probably the gold standard for this kind of thing. Essentially, their code is the following. ``` import unicodedata import re def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace, dashes, and underscores. """ value = str(value) if allow_unicode: value = unicodedata.normalize('NFKC', value) else: value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub(r'[^\w\s-]', '', value.lower()) return re.sub(r'[-\s]+', '-', value).strip('-_') ``` And the older version: ``` def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) value = unicode(re.sub('[-\s]+', '-', value)) # ... return value ``` There's more, but I left it out, since it doesn't address slugification, but escaping.
You can use list comprehension together with the string methods. ``` >>> s 'foo-bar#baz?qux@127/\\9]' >>> "".join(x for x in s if x.isalnum()) 'foobarbazqux1279' ```
Turn a string into a valid filename?
[ "", "python", "filenames", "slug", "sanitize", "" ]
I encountered a strange problem today. Whenever i put a breakpoint in one of my js files, the breakpoint is not hit. I use Visual Studio 2005 in combination with TFS. In ie the disable script options are both disabled. The only thing that changed is that I installed Visual Basic 6 for an old project, but I don't see how that would impact debugging via Visual Studio 2005. Did anyone had this problem before, or better does anyone know a solution? thx.
A collegue found the issue: the Just in time debugger was only set to handle Managed and native code, and no scripting. I just had to re-set it in the visual studio options pane.
In order for Javascript debugging to work the Visual Studio needs to be attached as a debugger to the IE process and it needs to be able to resolve the phyiscal path of the javascript file with the URL of the same script loaded in IE. Have you checked that when you start debugging in VS that it actually attaches to the IE process that gets spun up? Customizer your toolbar, on the commands tab select the debug category then find the "Script Explorer" command, drag it to a tool bar. Close the dialog. Using script explorer you should be able to find the script that ought to have the break point on. Ordinarily VS is able to combine the root path it specifies for the developer web server with the physical JS file path in order to determine what its URL would look like from the browsers perspective, it can then novate the break point from the physical file to the script loaded in the browser.
JavaScript debugging issue with vs2005
[ "", "javascript", "debugging", "visual-studio-2005", "" ]
Suppose I have the following code: ``` class siteMS { ... function __CONSTRUCT() { require 'config.php'; $this->config = new siteMSConfig; ... } ... } ``` From inside the siteMSConfig class can I determine weather or not it is being called from inside the siteMS class?
Yes, but there's no "pretty" way to do it - you'll end up looking through a [backtrace](http://www.php.net/debug_backtrace) or something similar. It would be better to pass an (optional?) parameter to the `siteMSConfig` constructor like this: ``` class siteMSConfig { public function __construct($inSiteMS = false) { } } ``` or alternatively, subclass `siteMSConfig`: ``` class siteMSsiteMSConfig extends siteMSConfig { public function __construct() { // Possibly call parent::__construct(); } } ```
Technically yes, you could use [debug\_backtrace](https://www.php.net/debug_backtrace) to figure out who your caller was. Writing a class which alters its behaviour based purely on where it called from is asking for a world of pain later on though. Why not parameterise the different behaviour, or make a subclass?
Is class being called from another class
[ "", "php", "oop", "" ]
Ok, I have an application written in C#. We have data in an SQL Server. Among that data we have user accounts, which will give access to the application. I've read around, and I know that you should salt and hash and possibly hash a bunch of times, etc. But, where do I do what? What do I send to and from the SQL Server? Exactly what do I store in the database? Do I hash it in SQL? (possibly a hash function there, like in mysql?) Do I hash and do the fancy stuff in my code? Do I send the hash to the server and compare, or do I get the hash from the server and compare in my application? What about the salt? Where do I make it? Where do I store it? How do I get it? In other words, could someone give me a nice and clear walkthrough of a login scenario (and possibly a user add/reset password scenario). What goes where, what should be used where, etc. Hope someone can clear these things up for me =)
I agree with Joel Coehoorn completely, the best choice is to trust someone else's tried and true implementation. If, however, you're determined to roll your own security implementation, then my advice is the following: 1. Store the hash and salt in the database. 2. Generate the hash and the salt in your own code. That way you're not tying yourself to a specific database. 3. Never send the password over the wire as plaintext. I would recommend fetching the hash and the salt from the database and comparing it to the ones you calculated from the username and password supplied by the party that wishes to be authenticated.
For C# + SQL Server, you can just use the MembershipProvider model, which will take care of all this for you. And IMO, the most important part of getting all this stuff right is *not doing it yourself*. Rather, rely on the mechanism provided by your platform. It's just so easy to get it wrong in a subtle way that *appears* to work. Then you deploy, and you don't even know anything is wrong until *after* you are hacked.
C# and SQL Server: Passwords. Where to do what?
[ "", "c#", "sql-server", "encryption", "passwords", "hash", "" ]
Is there a way to use yield blocks to implement an `IEnumerator<T>` which can go backward (`MoveLast()`) as well as forward?
Not directly from the iterator block, no. However, the caller can always buffer the results, for example into a `List<T>`, or just call `Reverse()` - but this doesn't always apply.
No, the state machine generated by the C# compiler is strictly forward. It doesn't even make sense to go backwards in many cases. Imagine an iterator reading from a network stream - to go backwards, it would have to remember everything that it had ever read, because it couldn't rewind time and ask the network for the data again. (Ditto anything that generated data in some lossy way. Imagine an iterator which returned a new board for Conway's Life on each iteration - there are multiple boards which could all have been the *previous* one, so to go backwards you again have to remember what you've already returned.)
Implementing a bidirectional enumerator in C#
[ "", "c#", "iterator", "ienumerator", "" ]
I have to do some work work with integers, but I am interested in treat them as binary data, in a way that for example I can take the 4 most significant bits of an 32 bit value. What I am trying to do is, I have several 32 bit value I want to take for example, in the first one 4 bits, the second one 6 bits and the last one 22 bits, and after concatenate them and get another 32 bits value. Can anyone please recommend any library or any othe way to do this?. Thank you.
It seems that you don't need a library for that. Just bit shifting, logical and, or and xor should be sufficient for what you want to do. EDIT: Just to give an example. Suppose `a` is a 32-bit `int`, and you want to take the first 4 bit and store it in the lowest bit positions in another integer `b`, you could do this: ``` b = (a & (0xf << (31-4))) >> (31-4) ```
I always prefer to use bit-fields and let the compiler figure out all the bit shifts. It also makes it easier if you ever want to make a change. However, you have to be careful with signed integers and understand how the compiler treats them with respect to bitfields. Nonetheless... ``` union _type { struct { unsigned int a : 22; unsigned int b : 6; unsigned int c : 4; }; unsigned int u; int s; }; ```
How to work with the data in Binary in C/C++
[ "", "c++", "c", "binary", "" ]
So, I have this situation where I need to see if an object is in my stl map. If it isn't, I am going to add it. ``` char symbolName[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; map<string,TheObject> theMap; if (theMap.find(symbolName)==theMap.end()) { TheObject theObject(symbolName); theMap.insert(pair<string, TheObject>(symbolName, theObject)); } ``` I am getting a core dump on the: theMap.find when the object is not already in the map. Supposedly, if the item is not in the map, it is supposed to return an iterator equivelent to map::end What is going on here? GCC: 3.4.6
It can crash because of many reasons. Without knowing the definition of at least `TheObject`'s constructors, i think we are largely left to guess at the problem. So far, your code looks fine, but it can be simplified: ``` char symbolName[] = "Hello"; map<string,TheObject> theMap; theMap.insert(make_pair(symbolName, TheObject(symbolName))); ``` It won't do anything if the symbol is already mapped, discarding the new TheObject object.
Why not just do it this way? ``` char symbolName[] = "hello"; theMap.insert(pair<string, TheObject>(symbolName, TheObject(symbolName))); ``` If your map is a `map<string, TheObject>` then you WILL get a core dump if you try to search for NULL: ``` // This will core dump: char *symbolName = NULL; // Oops! theMap.find(symbolName); // Kabang! ```
Why does STL map core dump on find?
[ "", "c++", "gcc", "dictionary", "" ]
What is the difference between `compare()` and `compareTo()` methods in Java? Do those methods give the same answer?
From [JavaNotes](http://web.archive.org/web/20090126135350/http://leepoint.net/notes-java/data/expressions/22compareobjects.html): * `a.compareTo(b)`: **Comparable interface :** Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a **natural order**, implement the `Comparable<T>` interface and define this method. All Java classes that have a natural ordering implement `Comparable<T>` - Example: `String`, [wrapper classes](http://www.javatpoint.com/wrapper-class-in-java), `BigInteger` * `compare(a, b)`: **Comparator interface :** Compares values of two objects. This is implemented as part of the `Comparator<T>` interface, and the **typical use is to define one or more small utility classes that implement this, to pass to methods such as `sort()` or for use by sorting data structures such as `TreeMap` and `TreeSet`**. You might want to create a Comparator object for the following: + **Multiple comparisons**. To provide several different ways to sort something. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the `sort()` method. + **System class** To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length. + **Strategy pattern** To implement a Strategy pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc. If your class objects have one natural sorting order, you may not need compare(). --- Summary from <http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html> **Comparable** A comparable object is capable of comparing itself with another object. **Comparator** A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. --- Use case contexts: **Comparable interface** The equals method and `==` and `!=` **operators** test for equality/inequality, but **do not provide a way to test for relative values**. Some classes (eg, String and other classes with a natural ordering) implement the `Comparable<T>` interface, which defines a `compareTo()` method. You will want to implement `Comparable<T>` in your class if you want to use it with `Collections.sort()` or `Arrays.sort()` methods. **Defining a Comparator object** You can create Comparators to **sort any arbitrary way for any class**. For example, the `String` class defines the [`CASE_INSENSITIVE_ORDER` comparator](http://www.java2s.com/Code/JavaAPI/java.lang/StringCASEINSENSITIVEORDER.htm). --- The difference between the two approaches can be linked to the notion of: **Ordered Collection**: When a Collection is ordered, it means you can iterate in the collection in a specific (not-random) order (a `Hashtable` is not ordered). A Collection with a **natural order** is not just ordered, but **sorted**. Defining a natural order [can be difficult!](https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/) (as in [natural String order](http://web.archive.org/web/20090310030619/http://weblogs.java.net/blog/skelvin/archive/2006/01/natural_string.html)). --- Another difference, pointed out by [HaveAGuess](https://stackoverflow.com/users/57344/haveaguess) in [the comments](https://stackoverflow.com/questions/420223/what-is-the-difference-between-compare-and-compareto/420240?noredirect=1#comment46816131_420240): * `Comparable` is in the implementation and not visible from the interface, so when you sort you don't really know what is going to happen. * `Comparator` gives you reassurance that the ordering will be well defined.
**`compareTo()`** is from the [**`Comparable`**](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) interface. **`compare()`** is from the [**`Comparator`**](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) interface. Both methods do the same thing, but each interface is used in a slightly different context. The [Comparable](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) interface is used to impose a natural ordering on the objects of the implementing class. The `compareTo()` method is called the natural comparison method. The [Comparator](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) interface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.
What is the difference between compare() and compareTo()?
[ "", "java", "compare", "compareto", "" ]
I have a report that I created with Crystal Reports 2008. This report uses upwards of 40 parameters to control the layout of the report. All the parameters are boolean and are defaulted to False in the saved report. The report is saved with the save data with the report option **unchecked** as I want to read the results from the database rather than within the report. However, when I go to export the report to PDF I receive a ParameterFieldCurrentValueException. I do not receive this error when the data is saved with the report. I have verified that all five tables in the report are connected to their data source with the following code. ``` foreach (Table table in reportDoc.Database.Tables) { bool isConnected = table.TestConnectivity(); Console.WriteLine(table.Name + " connected? " + isConnected.ToString()); } ``` What might be causing the ParameterFieldCurrentValueException when data not saved with a report and it is exported to disk? This is the simplest code that can reproduce this issue. ``` string report = "list_report.rpt"; string pdf = "list_report.pdf"; ReportDocument reportDoc = new ReportDocument(); reportDoc.Load(report); // Setting parameters (or not) does not have an effect on the error // All parameters have defaults // reportDoc.SetParameterValue("hideRegion", false); reportDoc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, pdf); ```
When you have Save Data with Report selected the report does not try to hit the database. It's a static report with saved data. That's why this report doesn't error compared to when you try to pass parameters without saved data. The error suggests that one or more of the parameter values you're passing at runtime does not match what the report is expecting. In your code you're exporting to PDF directly. Since you're not viewing the report there's no opportunity for the engine to prompt for missing values. You can build a simple windows application that loads your report and passes it to the Crystal Report Viewer control. Start by not passing any parameter to the report without saved data. You should be prompted for all your parameters. Add them manually in the parameter prompt form. Does this work? It should. Now start adding parameter code one at a time. The parameter prompt form should just prompt for the parameters that are missing. At some point you'll get the error again and this should help narrow down the issue. Sincerely, Dan Kelleher
This answer isn't mine, it is by a gentleman on the Crystal Reports forums. That posting can be found on the [SAP Forum](https://www.sdn.sap.com/irj/scn/thread?forumID=313&threadID=1211544) The answer there was: > When you have Save Data with Report > selected the report does not try to > hit the database. It's a static report > with saved data. That's why this > report doesn't error compared to when > you try to pass parameters. > > The error suggests that one or more of > the parameter values you're passing > does not match what the report is > expecting. Since you're not viewing > the report there's no opportunity for > the engine to prompt for missing > values. > > You can build a simple windows > application that loads your report. > Start by not passing any parameter to > the report without saved data. You > should be prompted for all your > parameters. Add them manually in the > parameter prompt form. Does this work? > It should. Now start adding parameter > code one at a time. The parameter > prompt form should just prompt for the > parameters that are missing. At some > point you'll get the error again and > this should help narrow down the > issue. What I then did was to load the report into a Crystal Report Viewer control. When this loaded it prompted me for any missing parameters I had. I had missed one parameter in a list of 40+ parameters which was causing the error. The code for that follows: ``` ReportDocument reportDoc = new ReportDocument(); reportDoc.Load(")list_report.rpt"; Form1.SetParameterValues(reportDoc); this.crystalReportViewer1.ReportSource = reportDoc; ``` If said person replies to Stack Overflow with this answer I shall select his post as the answer in order to appropriately credit the source.
ParameterFieldCurrentValueException when data not saved with a report and exporting to PDF
[ "", "c#", "crystal-reports", "parameters", "" ]
I'm developing a website in PHP and I have large JS files that I want to compress. So, I added this in my .htaccess file: ``` <FilesMatch "\.(js|css|html|htm|php|xml)$"> SetOutputFilter DEFLATE </FilesMatch> ``` It works great on my local wamp server install but once I move the files on my shared server, the DEFLATE command does not work. I don't know why... mod\_deflate is enabled on the webserver, aswell as bz2, gzip. I am allowed to user htaccess, I've cheched...Plus that I have other rules and commands running in htaccess. So the DEFLATE is the only one that does not work... Does anyone know why it works on my localhost and not on my webserver too ? Is there any module/extension that I need to enable on my webserver that I don't know of ? Any ideas ? Thank you!
Are you sure mod\_deflate is loaded and available? Apache doesn’t throw an error if you set it as filter although it is not loaded. You can use the [`apache_get_modules` function](http://docs.php.net/apache_get_modules) to see what modules are loaded.
Hmm, I guess you're right..I've checked my loaded modules with apache\_get\_modules() and mod\_deflate wasn't there. I also checked on my localhost and mod\_deflate was there. I've sent a ticket to support. I hope I'll get this done. Thank you for your help.
htaccess mod_deflate does not work on shared server
[ "", "php", "apache", ".htaccess", "gzip", "mod-deflate", "" ]
How do I access a Control in the `LayoutTemplate` of a `ListView` control? I need to get to `litControlTitle` and set its `Text` attribute. ``` <asp:ListView ID="lv" runat="server"> <LayoutTemplate> <asp:Literal ID="litControlTitle" runat="server" /> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> </LayoutTemplate> <ItemTemplate> </ItemTemplate> </asp:ListView> ``` Any thoughts? Perhaps via the `OnLayoutCreated` event?
Try this: ``` ((Literal)lv.FindControl("litControlTitle")).Text = "Your text"; ```
The complete solution: ``` <asp:ListView ID="lv" OnLayoutCreated="OnLayoutCreated" runat="server"> <LayoutTemplate> <asp:Literal ID="lt_Title" runat="server" /> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> </LayoutTemplate> <ItemTemplate> </ItemTemplate> </asp:ListView> ``` In codebehind: ``` protected void OnLayoutCreated(object sender, EventArgs e) { (lv.FindControl("lt_Title") as Literal).Text = "Your text"; } ```
Access a control inside a the LayoutTemplate of a ListView
[ "", "c#", "asp.net", "listview", "asp.net-3.5", "" ]
I have a List of a "complex" type - an object with a few string properties. The List itself is a property of another object and contains objects of a variety of types, as shown in this abbreviated class structure: ``` Customer { public List<Characteristic> Characteristics; . . . } Characteristic { public string CharacteristicType; public string CharacteristicValue; } ``` I'd like to be able to collect a List of the values of a given type of Characteristics for the current Customer, which I can do in a 2-step process as follows: ``` List<Characteristic> interestCharacteristics = customer.Characteristics.FindAll( delegate (Characteristic interest) { return interest.CharacteristicType == "Interest"; } ); List<string> interests = interestCharacteristics.ConvertAll<string>( delegate (Characteristic interest) { return interest.CharacteristicValue; } ); ``` That works fine, but it seems like a long way around. I'm sure I must be missing a simpler way of getting to this list, either by chaining together the FindAll() and Convert() methods, or something else I'm overlooking entirely. For background, I'm working in .Net 2.0, so I'm limited to the .Net 2 generics, and the Characteristic class is an external dependency - I can't change it's structure to simplify it, and there are other aspects of the class that are important, just not in relations to this problem. Any pointers or additional reading welcomed.
Here's a generator implementation ``` public static IEnumerable<string> GetInterests(Customer customer) { foreach (Characteristic c in customer.Characteristics) { if (c.CharacteristicType == "Interest") yield return c.CharacteristicValue; } } ``` sadly 3.5 extension methods and lambda are out based on your requirements but for reference here's how to do it: ``` customer.Characteristics .Where(c => c.CharacteristicType == "Interest") .Select(c => c. CharacteristicValue); ```
I would do some of the work manualy. By doing a FindAll first, and then a Convert, you're looping through your collection twice. It doesn't seem neccessary. If all you want at the end of the day, is a List of CharacteristicValue then just loop through your original collection, and add the CharacteristicValue to a List of each one that matches your criteria. Something like this: ``` Predicate<Characteristic> criteria = delegate (Characteristic interest) { return interest.CharacteristicType == "Interest"; }; List<string> myList = new List<string>(); foreach(Characteristic c in customer.Characteristics) { if(criteria(c)) { myList.Add(c.CharacteristicValue); } } ```
Method chaining generic list extensions
[ "", "c#", "generics", ".net-2.0", "findall", "convertall", "" ]
I'm looking for something like `break` for loops. Here's some example code (using Symfony's lime) where `stop()` would not let the class continue and `I_DONT_WANT_THIS_TO_RUN()` would not be executed. ``` $browser->isStatusCode(200) ->isRequestParameter('module', 'home') ->isRequestParameter('action', 'index') ->click('Register') ->stop() ->I_DONT_WANT_THIS_TO_RUN(); $browser->thenThisRunsOkay(); ``` Calling `$this->__deconstruct();` from within `stop()` doesn't seem to do the trick. Is there a function I can call within `stop()` that would make that happen?
Just return another class which will return $this for every method called. Example: ``` class NoMethods { public function __call($name, $args) { echo __METHOD__ . " called $name with " . count($args) . " arguments.\n"; return $this; } } class Browser { public function runThis() { echo __METHOD__ . "\n"; return $this; } public function stop() { echo __METHOD__ . "\n"; return new NoMethods(); } public function dontRunThis() { echo __METHOD__ . "\n"; return $this; } } $browser = new Browser(); echo "with stop\n"; $browser->runThis()->stop()->dontRunThis()->dunno('hey'); echo "without stop\n"; $browser->runThis()->dontRunThis(); echo "the end\n"; ``` Will result in: ``` with stop Browser::runThis Browser::stop NoMethods::__call called dontRunThis with 0 arguments. NoMethods::__call called dunno with 1 arguments. without stop Browser::runThis Browser::dontRunThis the end ```
You could use [PHP exceptions](http://php.net/exceptions): ``` // This function would of course be declared in the class function stop() { throw new Exception('Stopped.'); } try { $browser->isStatusCode(200) ->isRequestParameter('module', 'home') ->isRequestParameter('action', 'index') ->click('Register') ->stop() ->I_DONT_WANT_THIS_TO_RUN(); } catch (Exception $e) { // when stop() throws the exception, control will go on from here. } $browser->thenThisRunsOkay(); ```
How do you stop a PHP class from executing?
[ "", "php", "exception", "class", "" ]
As part of a numerical library test I need to choose base 10 decimal numbers that can be represented exactly in base 2. How do you detect in C++ if a base 10 decimal number can be represented exactly in base 2? My first guess is as follows: ``` bool canBeRepresentedInBase2(const double &pNumberInBase10) { //check if a number in base 10 can be represented exactly in base 2 //reference: http://en.wikipedia.org/wiki/Binary_numeral_system bool funcResult = false; int nbOfDoublings = 16*3; double doubledNumber = pNumberInBase10; for (int i = 0; i < nbOfDoublings ; i++) { doubledNumber = 2*doubledNumber; double intPart; double fracPart = modf(doubledNumber/2, &intPart); if (fracPart == 0) //number can be represented exactly in base 2 { funcResult = true; break; } } return funcResult; } ``` I tested this function with the following values: -1.0/4.0, 0.0, 0.1, 0.2, 0.205, 1.0/3.0, 7.0/8.0, 1.0, 256.0/255.0, 1.02, 99.005. It returns true for -1.0/4.0, 0.0, 7.0/8.0, 1.0, 99.005 which is correct. Any better ideas?
I think what you are looking for is a number which has a fractional portion which is the sum of a sequence of negative powers of 2 (aka: 1 over a power of 2). I believe this should always be able to be represented exactly in IEEE floats/doubles. For example: 0.375 = (1/4 + 1/8) which should have an exact representation. If you want to generate these. You could try do something like this: ``` #include <iostream> #include <cstdlib> int main() { srand(time(0)); double value = 0.0; for(int i = 1; i < 256; i *= 2) { // doesn't matter, some random probability of including this // fraction in our sequence.. if((rand() % 3) == 0) { value += (1.0 / static_cast<double>(i)); } } std::cout << value << std::endl; } ``` EDIT: I believe your function has a broken interface. It would be better if you had this: ``` bool canBeRepresentedExactly(int numerator, int denominator); ``` because not all fractions have exact representations, but the moment you shove it into a double, you've chosen a representation in binary... defeating the purpose of the test.
If you're checking to see if it's binary, it will always return true. If your method takes a `double` as the parameter, the number is already represented in binary (`double` is a binary type, usually 64 bits). Looking at your code, I think you're actually trying to see if it can be represented exactly as an integer, in which case why can't you just cast to `int`, then back to `double` and compare to the original. Any integer stored in a double that's within the range representable by an `int` should be exact, IIRC, because a 64 bit `double` has 53 bits of mantissa (and I'm assuming a 32 bit int). That means if they're equal, it's an integer.
How to detect if a base 10 decimal can be represented exactly in base 2
[ "", "c++", "" ]
What's the best way to debug Javascript on Internet Explorer?
Depends on what tools you have available to you. If you have a copy of Visual Studio, I'd use the [Visual Studio debugger](http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/). It works pretty well. You'll need to try following the instructions in that link if you don't have a full copy of Visual Studio, otherwise it's built in to the IDE and is pretty simple to use. Another option is [Firebug Lite](http://getfirebug.com/lite.html), which is pretty good for most situations, but you need to add a script reference to every page you want to debug in order for it to work.
Using Microsoft Script Editor is an option too: See my answer [here.](https://stackoverflow.com/questions/8398/how-do-i-debug-javascript-in-visual-studio-2005#16855)
What's the best way to debug Javascript on IE?
[ "", "javascript", "internet-explorer", "debugging", "" ]
I need to generate a list of sequential numbers. I know Ruby you can do 1..10 or PHP you can do range(1, 10). Anything like that in .Net already, or do I have to write it? Thanks.
In C# (with .NET 3.0 or higher) this should do the job: ``` IEnumerable<int> myRange = Enumerable.Range(1, 10); ```
Would this work for you? ``` public List<int> Range(int start, int finish) { List<int> retList = new List<int>(); for(int i = start; i <= finish; i++) { retList.Add(i); } return retList; } ```
PHP range() function in .NET?
[ "", ".net", "php", "range", "" ]
Have you used the [OpenAccess ORM from Telerik](http://www.telerik.com/products/orm.aspx)? How does it compare to NHibernate? When should I consider using it over NHibernate?
I'm wondering the same thing myself. On one hand, there's NH with its free, open-source self, but with limited support options. On the other, a fairly new addition to a well-known tool provider's box, OA. OA costs money, but you get support. NH is free, but support has been known at least in my brief experience to be limited and slow in coming. I think both are likely fine products. I've decided to give OA a try since I am already a user of Telerik's tools. OA and its support are being paid for anyway. NH uses plain classes and object with no decorations on the class properties whatsoever. OA requires decorations (nicely generated by the OA Visual Studio GUI). NH requires a "session" in which to do a unit of work with the database; OA calls it "scope". Both use "transaction". OA has integration with Visual Studio and can both forward- and reverse-map to and from a database. Forward mapping is so you can design your classes and then "push" those into the database for persistence. The "reverse" is for you "domain model" developers which is what I prefer. OA is definitely undergoing some major updates as Telerik plays "catch up" per its recent acquisition and release of OpenAccess, formerly owned by Vanatec (out of Germany). As far as an "ease of use" and "performance / scalability" standpoint, I wish I knew where each stood. I'm sure someone out there could put together an honest test between the two and make those determinations. One thing I like about NH is the available templates to generate the needed code not just for the "dumb" business objects (which is all OA generates now), but for a BLL and DLL. After much conversation with Telerik, I have the impression they plan for more code-generating options so OA is more useful out of the box. Hope this helps! Someone please try to get some stats on the performance issues.
I've not used it but one benefit obvious to me, is OpenAccess is supported by Telerik, where as nHibernate is supported by the community. Depending on your company this can be a deciding factor if your ready to embrace open source solutions with no guarentee of support. # Edit For the record I am a big supporter of nHibernate, and open source in general. I have been using nHibernate for the last six months, using it for all new work in our web application. For my current company it is a good fit (Startups love free). However, my previous employeer, would have had a very difficult time accepting a community supported component as a core piece of their infrastructure. This is perfectly reasonable as these companies' web sites are their sole source of revenue. Would you want to stake your entire business on software that has no accountability associated with it? Some people wouldn't want to take that risk on. Personally I have found the support for nHibernate to be on par and even better with some commercial vendors. My point is not to bash OSS, but to highlight one benefit of using software that has a coporate backing, with a fully staffed and dedicated support channel.
Compare and Contrast NHibernate and OpenAccess from Telerik
[ "", "c#", ".net", "nhibernate", "orm", "openaccess", "" ]
How do I write a query that outputs the row number as a column? This is DB2 SQL on an iSeries. eg if I have table Beatles: ``` John Paul George Ringo ``` and I want to write a statement, without writing a procedure or view if possible, that gives me ``` 1 John 2 Paul 3 George 4 Ringo ```
``` SELECT ROW_NUMBER() OVER (ORDER BY beatle_name ASC) AS ROWID, * FROM beatles ```
Check out the row\_number() function; you should be able to do this in DB2 via: ``` SELECT row_number(), first_name FROM beatles ``` I'm almost certain this is not part of the SQL standard though, so it is not likely to be portable should that ever be an issue.
How do I write a query that outputs the row number as a column?
[ "", "sql", "db2", "" ]
How can I garble JavaScript code before sending it to client-side? I don't want to expose functionalities. The code is already compressed using `jsmin`.
You could try some online obfuscator like this: <http://www.javascriptobfuscator.com/Default.aspx>
You need an obfuscator, [see this](http://www.javascriptobfuscator.com/Default.aspx) for an example. Anyone [determined](http://isc.sans.org/diary.html?storyid=1519) enough can always reverse it though, and tools [like this](https://addons.mozilla.org/en-US/firefox/addon/10345) can help.
Garble JavaScript code before sending to client-side
[ "", "javascript", "compression", "code-generation", "" ]
So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys. ``` {% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} ``` this is the dict I pass in as numvec: ``` numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), ``` "TEST3":Decimal("0.255")} the number field was defined as having these choices in my model: ``` BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) ``` The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals?
According to [this](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal), it seems you can only compare strings. I'd make my own [template tag](http://www.mechanicalgirl.com/view/custom-template-tags-in-django/) if I were you.
It is not a bug and **it is possible** to achieve what you're trying to do. However, first of all few remarks about your code: * There is no "ifequals/endifequals" operator. You either use ["ifequal/endifequal"](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal) or ["if/endif"](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#operator). * Second thing. Your code `{% ifequal item.number {{key}} %}` would cause TemplateSyntaxError Exception if you leave double curly brackets inside the "ifequal" or "if" operator. **Now the solution**: 1. Just simply use ["stringformat"](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat) filter to convert your decimal values to string. 2. Skip curly brackets when you use variables inside operators. 3. Don't forget that variable inside an "if" or "ifequal" operator is always represented as a string. Here is an *example*: ``` {% for item in decimals %} {% if item|stringformat:"s" == variable %} {{ variable }} {% endif %} {% endfor %} ```
Django template ifequal comparison of decimals
[ "", "python", "django", "django-templates", "" ]
I'm working on a project and I'm just starting to do all the work necessary to globalize the application. One thing that comes up quite often is whether to globalize the exception messages, but ensuring that string.Format uses CultureInfo.CurrentCulture instead of CultureInfo.InvariantCulture. Additionally this would mean that exception messages would be stored in resource files that can be marked as culture-specific. So the question is, should exception messages be globalized or should be be left in either the InvariantCulture or the author's country; in my case en-US.
Exception messages should rarely be displayed directly to the user. You need to think of the consumer for each string. Obviously pieces of text in the user interface need internationalizing, but if an exception message is *only* going to be seen by support (or is going to be visible to the user and then emailed to support when they click a button) then where's the benefit of translating it? If you go too far, you could not only waste time and effort (and i18n can take a *lot* of effort) but you'll also make your support life harder as well. You really don't want to have to read log files written in a foreign language and translate them back to your native tongue. It makes sense for Microsoft to internationalize *their* exception messages, because they will be read by *developers* from all over the world - but unless you're multinational with developers in multiple countries who don't share a common language, I wouldn't translate message which are really meant for dev/support.
typically, I don't. Globalize strings that may be seen by a user, and you don't let your exception messages percolate up to the UI, right? Right? :)
Should Exception Messages be Globalized
[ "", "c#", "exception", "globalization", "" ]
I have an array in the form of '`int[][]`' that represents the co-ordinates of a small grid. Each co-ordinate has been assigned its own value. eg `array[0][4] = 28`...... I have two questions. Firstly, how do I iterate through all the stored values. Secondly, I want to be able to input a value and have its specific co-ordinates in the grid returned. What would be the best way to approach this? Thank you for any help!
You can iterate with either for loops or enhanced for loops: ``` for (int row=0; row < grid.length; row++) { for (int col=0; col < grid[row].length; col++) { int value = grid[row][col]; // Do stuff } } ``` or ``` // Note the different use of "row" as a variable name! This // is the *whole* row, not the row *number*. for (int[] row : grid) { for (int value : row) { // Do stuff } } ``` The first version would be the easiest solution to the "find the co-ordinates" question - just check whether the value in the inner loop is correct.
to iterate over the values use loops: ``` int[][] matrix //... for(int row[] : matrix) for(int cell : row){ //do something with cell } ``` to access the coordinates based on the value you would need some sort of double hashmap (look a at java.util.HashMap) but i am aware of nothing that does so directly
Java int[][] array - iterating and finding value
[ "", "java", "arrays", "iteration", "" ]
Is there a pattern where in WPF, I can build a simple UI form from an XML like definition file pulled from a database? It would allow the user to enter data into this form, and submit it back. The data would be sent back in an XML structure that would closely/exactly mimic the UI definition. The definition should include the data-type, and if it was a required value or not. I would then like to map these data-types and required values to Data Validation Rules, so the form could not be submitted unless it passes the check. It should also handle the ability to have lists of repeating data. I am in the planning stages of this project and have fairly good flexibility in the design at this point, though I am pretty sure I need to stick to the desktop, not web since I may be doing some Office Inter-op stuff as well. What technology stack would you recommend? I think XMAL and WPF may be close to the answer. I have also looked at [XUL](http://www.mozilla.org/projects/xul), but it doesn't seem ready or useful for C#. (Found this [article](http://msdn.microsoft.com/en-us/magazine/cc188912.aspx) from MSDN in 2002) Thank you, Keith
Model View Presenter seems to suit WPF quite well, if you've not heard of it before check out the [Supervisor Controller](http://martinfowler.com/eaaDev/SupervisingPresenter.html) pattern, which is a subset of MVP (the author has renamed it to [Supervisor Controller](http://martinfowler.com/eaaDev/SupervisingPresenter.html) and [Passive View](http://martinfowler.com/eaaDev/PassiveScreen.html) as two different flavours of MVP). It is a design principal that will help you promote the separation of concerns and works much better than MVC when you don't have a framework to physically enforce it. You could always try to create a view engine for ASP.NET MVC that works with WPF though, that would be nice.
Well if you wanted to roll something yourself, you can load and render dynamic XAML pretty easily. Rather than have users create XAML directly you could have a subset of it "mapped" to an XML format of your choosing that you XSL into valid XAML: ``` XmlReader tXml = XmlReader.Create(myXamlString); UIElement MyElement = (UIElement)XamlReader.Load(tXml); ```
Is there a MVC pattern for C# in WPF
[ "", "c#", "xml", "user-interface", "design-patterns", "project-planning", "" ]
Why would SDL\_Mixer not play music for certain mp3s? I am utilizing SDL\_Mixer for music playback in an application I am creating. On certain songs (entire albums actually), the music will simply not play without returning any errors. The music data loads successfully using Mix\_LoadMUS and when executing Mix\_PlayMusic with that data, it oddly enough returns 0 for success but plays no music. I have also tried reading Mix\_GetError() and SDL\_GetError() (I believe they're the same) to see if it raises an error, but no such luck. My question is, what other reasons would SDL\_mixer not be able to play a particular mp3? I know the mp3's are functional since I can play them in other music players. I also know for a fact that they are not playing (as opposed to perhaps the volume being turned down) since Mix\_PlayingMusic returns 0. Thanks everyone!
This actually wound up being a sound issue with that particular computer. Upon trying the same tests on another machine, the sound worked flawlessly. Just a quick note in case someone else encounters this issue.
Different implementations of the MP3 algorithm tolerate different levels of conformance to the format. Most of the music players are pretty tolerant, because most users would rather hear something choppy than nothing at all, but the playback libraries that are common tolerate much less. I'd recommend opening the offending (Or all) mp3's in an audio sample editor, such as [Audacity](http://audacity.sourceforge.net/), and reexporting the mp3. You might lose just a little bit of quality since the mp3 compression is by it's nature lossy, but it's likely to fix the playback problem.
Why would SDL_Mixer not play music for certain mp3s?
[ "", "c++", "audio", "sdl", "sdl-mixer", "" ]
Got a bit of a mind freeze at the moment. I have the following syntax:- ``` string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\'); ``` and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter? Cheers
Use ``` Split('\\') ``` "\" is an [escape character](http://en.wikipedia.org/wiki/Escape_character).
\ is an excape character in C#. You need to do one of the following: ``` Split('\\'); ``` or ``` Split(@'\'); ```
string split based on char \
[ "", "c#", "c#-3.0", "c#-2.0", "" ]
Here is the scenario: I have two asp pages. a.aspx is layout and b.aspx is content. I want to display the contents of b.aspx inside a `<div>` on a.aspx. I know with PHP you can do it like so: ``` //a.php <html> <head> <title>test</title> </head> <body> <?PHP include "b.php"; ?> </body> </html> //b.php <?PHP echo "Content String"; ?> //result <html> <head> <title>test</title> </head> <body> Content String </body> </html> ``` Thanks!
Probably `Server.Execute` will help. ``` //a.aspx <html> <head> <title>test</title> </head> <body> <% Server.Execute("b.aspx"); %> </body> </html> //b.aspx Content String //result <html> <head> <title>test</title> </head> <body> Content String </body> </html> ``` By the way, I do **not** recommend this approach. It's just to show it can be done. Master pages and user controls are normally the way to go.
This scenario is handled by masterpages and or composing the page out of (user)controls in ASP.NET. As described at for instance [here](http://www.asp.net/Learn/master-pages/).
Is it possible to write the contents of b.aspx on a.aspx?
[ "", "php", "asp.net", "vb.net", "" ]
I am using this php code: ``` exec("unrar e file.rar",$ret,$code); ``` and getting an error code of illegal command ie 127 ... but when I am using this command through ssh its working ... because unrar is installed on the server ... so can anyone guess why exec is not doing the right stuff?
Try using the direct path of the application (/usr/bin/unrar of whatever), it sounds like php can't find the application.
If you have chrooted apache and php, you will also want to put /bin/sh into the chrooted environment. Otherwise, the exec() or passthru() will not function properly, and will produce error code 127, file not found.
illegal command error code 127 in php exec function
[ "", "php", "exec", "" ]
I created a utility function to return the expected single item from an generator expression ``` print one(name for name in ('bob','fred') if name=='bob') ``` Is this a good way to go about it? ``` def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: raise Exception('Too many values') except StopIteration: raise Exception('No values') ```
A simpler solution is to use tuple unpacking. This will already do everything you want, including checking that it contains exactly one item. Single item: ``` >>> name, = (name for name in ('bob','fred') if name=='bob') >>> name 'bob' ``` Too many items: ``` >>> name, = (name for name in ('bob','bob') if name=='bob') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack ``` No items: ``` >>> name, = (name for name in ('fred','joe') if name=='bob') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 0 values to unpack ```
For those using or interested in a third-party library, [`more_itertools`](https://github.com/erikrose/more-itertools) implements such a tool with native error handling: ``` > pip install more_itertools ``` **Code** ``` import more_itertools as mit mit.one(name for name in ("bob", "fred") if name == "bob") # 'bob' mit.one(name for name in ("bob", "fred", "bob") if name == "bob") # ValueError: ... mit.one(name for name in () if name == "bob") # ValueError: ... ``` See [`more_itertools` docs](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.one) for details. The [underlying source code](https://github.com/erikrose/more-itertools/blob/90a27b0e090b52bec0d32b24d631b090aea67847/more_itertools/more.py#L480) is similar to the accepted answer.
select single item from a collection : Python
[ "", "python", "iterator", "generator", "" ]
I'm using this code to reset the identity on a table: ``` DBCC CHECKIDENT('TableName', RESEED, 0) ``` This works fine most of the time, with the first insert I do inserting 1 into the Id column. However, if I drop the DB and recreate it (using scripts I've written) and then call DBCC CHECKIDENT, the first item inserted will have an ID of 0. Any ideas? **EDIT:** After researching I found out I didn't read the [documentation](http://msdn.microsoft.com/en-us/library/aa258817(SQL.80).aspx) properly - "The current identity value is set to the new\_reseed\_value. If no rows have been inserted to the table since it was created, the first row inserted after executing DBCC CHECKIDENT will use new\_reseed\_value as the identity. Otherwise, the next row inserted will use new\_reseed\_value + 1. "
As you pointed out in your question it is a [documented behavior](http://msdn.microsoft.com/en-us/library/aa258817(SQL.80).aspx). I still find it strange though. I use to repopulate the test database and even though I do not rely on the values of identity fields it was a bit of annoying to have different values when populating the database for the first time from scratch and after removing all data and populating again. A possible solution is to use **truncate** to clean the table instead of delete. But then you need to drop all the constraints and recreate them afterwards In that way it always behaves as a newly created table and there is no need to call DBCC CHECKIDENT. The first identity value will be the one specified in the table definition and it will be the same no matter if you insert the data for the first time or for the N-th
You are right in what you write in the edit of your question. After running `DBCC CHECKIDENT('TableName', RESEED, 0)`: - Newly created tables will start with identity 0 - Existing tables will continue with identity 1 The solution is in the script below, it's sort of a poor-mans-truncate :) ``` -- Remove all records from the Table DELETE FROM TableName -- Use sys.identity_columns to see if there was a last known identity value -- for the Table. If there was one, the Table is not new and needs a reset IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'TableName' AND last_value IS NOT NULL) DBCC CHECKIDENT (TableName, RESEED, 0); ```
DBCC CHECKIDENT Sets Identity to 0
[ "", "sql", "sql-server", "" ]
What is meant by "object serialization"? Can you please explain it with some examples?
Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.
You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation). It is very useful when you want to transmit one object data across the network, for instance from one JVM to another. In Java, the serialization mechanism is built into the platform, but you need to implement the *Serializable* interface to make an object serializable. You can also prevent some data in your object from being serialized by marking the attribute as *transient*. Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases. To do this, you use one of the [hidden features in java](https://stackoverflow.com/questions/15496/hidden-features-of-java/142676#142676). It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized. Here is a very basic sample with comments to facilitate its reading: ``` import java.io.*; import java.util.*; // This class implements "Serializable" to let the system know // it's ok to do it. You as programmer are aware of that. public class SerializationSample implements Serializable { // These attributes conform the "value" of the object. // These two will be serialized; private String aString = "The value of that string"; private int someInteger = 0; // But this won't since it is marked as transient. private transient List<File> unInterestingLongLongList; // Main method to test. public static void main( String [] args ) throws IOException { // Create a sample object, that contains the default values. SerializationSample instance = new SerializationSample(); // The "ObjectOutputStream" class has the default // definition to serialize an object. ObjectOutputStream oos = new ObjectOutputStream( // By using "FileOutputStream" we will // Write it to a File in the file system // It could have been a Socket to another // machine, a database, an in memory array, etc. new FileOutputStream(new File("o.ser"))); // do the magic oos.writeObject( instance ); // close the writing. oos.close(); } } ``` When we run this program, the file "o.ser" is created and we can see what happened behind. If we change the value of: **someInteger** to, for example **Integer.MAX\_VALUE**, we may compare the output to see what the difference is. Here's a screenshot showing precisely that difference: ![alt text](https://i.stack.imgur.com/oIVA5.png) *Can you spot the differences? ;)* There is an additional relevant field in Java serialization: The [serialversionUID](http://www.google.com/search?q=serialversionUID) but I guess this is already too long to cover it.
What is object serialization?
[ "", "java", "serialization", "object-serialization", "" ]
I am wondering how I can define an object in C whose reference will be null? ``` // definition of foo ... void * bar = &foo; // bar must be null ``` There is some ways I could find to do it, but none fit my needs. ``` __attribute__((weak)) extern int foo; //not working with cygwin/gcc 3.4 __attribute__((at(0))) int foo; //only with rvds #define foo (*(int*) 0) //cannot be embedded in a macro ``` Actually, I would prefer a standard compliant solution (c99), but anything working will be ok. --- Edited: The reason to do this is that bar will not always be null. Here is a more relevant example: ``` // macro that will define foo to a real object or to *null DECL(foo); int * bar = &foo; if(bar) { // we can call func func(bar); } else { // bar undefined exit(-1); } ``` Of course this is still not very relevant, because I can use #if in my condition. The project involves in fact big structures, a lot of files, a few compilers, some cpu targets, and many programmers who generate bugs with a probability exponential to the complexity of the syntax they use. It is why I would like a simple macro to declare my foo object.
You are trying to create a symbol with an address of zero. Your last example is probably the only way of doing this within the C compiler / language. The approach that is most likely to solve your problem is to look at the input file to the linker program. Most linkers allow you to define the label foo as zero. In a unix ld script this is just: foo = 0 ;
I've got to be missing something, but what doesn't work about `void * bar = NULL`?
How to define an object whose address is null?
[ "", "c++", "c", "linker", "weak-references", "" ]
Consider these 3 table structures. Which will perform these queries the best. ## Structure 1 - TagID as int with a join table ``` Article ------- ArticleID int Article_Tag ------------ ArticleTagID int ArticleID int TagID int Tag --- TagID int TagText varchar(50) ``` ## Structure 2 - Tags only in Join table as string ``` Article ------- articleID int Article_Tag ----------- articleTagID int articleID int tag varchar(50) ``` ## Structure 3 - Tag as text as the PK ``` Article ------- ArticleID int Article_Tag ------------ ArticleTagID int ArticleID int Tag varchar(50) Tag --- Tag varchar(50) ``` Sample queries: ``` Select articleID from Article a inner join Article_tag at on a.articleID = at.articleID and tag = 'apple' Select tag from Tags -- or, for structure 2 Select distinct tag from article_tag ```
It depends if you ever want to be able to change the tag-text globally. You could, of course, issue a wide `UPDATE` on `Article_Tag`, but if you need to be able to do this, then being able to just update the value in `Tag` would be simpler. Some servers offer automatic updates (such as `ON UPDATE CASCADE` in SQL Server), but these aren't necessarily cheap (it still has to `UPDATE` a lot of rows and any indexes defined). But if you **don't** need this, then it should be a bit quicker with the literal in `Article_Tag`, as it can remove a join - a lot of times. Obviously, index it etc. The additional space required for the repeated literal is a factor, but disk space is usually cheaper than a faster server. As for being a primary key; unless you have other data to store, why would you even need the table any more? You could use `DISTINCT` on `Article_Tag` just as easily, especially as `Tag` should be indexed (so this should be pretty cheap). (**edit** Bill Karwin correctly points out the merits of being able to keep *eligible* tags, not just *current* tags).
Using `TagText` as the primary key would have the advantage that you could get an articles tags with fewer joins: ``` SELECT * FROM Article_Tag WHERE Article_ID = ? ``` It would have the disadvantage that tag strings take more space than integers, so the storage for `Article_Tag` and its indexes would be larger. This occupies more space on disk and also requires more memory for caching the index.
Optimized Table structure for Tags table
[ "", "sql", "" ]
In C++, `sizeof('a') == sizeof(char) == 1`. This makes intuitive sense, since `'a'` is a character literal, and `sizeof(char) == 1` as defined by the standard. In C however, `sizeof('a') == sizeof(int)`. That is, it appears that C character literals are actually integers. Does anyone know why? I can find plenty of mentions of this C quirk but no explanation for why it exists.
Discussion on [same subject](http://bytes.com/groups/c/222894-sizeof-x-c-c) > "More specifically the integral promotions. In K&R C it was virtually (?) > impossible to use a character value without it being promoted to int first, > so making character constant int in the first place eliminated that step. > There were and still are multi character constants such as 'abcd' or however > many will fit in an int."
The original question is "why?" The reason is that the definition of a literal character has evolved and changed, while trying to remain backwards compatible with existing code. In the dark days of early C there were no types at all. By the time I first learnt to program in C, types had been introduced, but functions didn't have prototypes to tell the caller what the argument types were. Instead it was standardised that everything passed as a parameter would either be the size of an int (this included all pointers) or it would be a double. This meant that when you were writing the function, all the parameters that weren't double were stored on the stack as ints, no matter how you declared them, and the compiler put code in the function to handle this for you. This made things somewhat inconsistent, so when K&R wrote their famous book, they put in the rule that a character literal would always be promoted to an int in any expression, not just a function parameter. When the ANSI committee first standardised C, they changed this rule so that a character literal would simply be an int, since this seemed a simpler way of achieving the same thing. When C++ was being designed, all functions were required to have full prototypes (this is still not required in C, although it is universally accepted as good practice). Because of this, it was decided that a character literal could be stored in a char. The advantage of this in C++ is that a function with a char parameter and a function with an int parameter have different signatures. This advantage is not the case in C. This is why they are different. Evolution...
Why are C character literals ints instead of chars?
[ "", "c++", "c", "char", "sizeof", "language-design", "" ]
Pretty self explanatory question. Is there any reason to use one or the other?
Count(\*) counts all records, including nulls, whereas Count(fieldname) does not include nulls.
Select count(\*) selects any row, select count(field) selects rows where this field is not null.
In SQL is there a difference between count(*) and count(<fieldname>)
[ "", "sql", "" ]
Given an example of calling two web services methods from a session bean, what if an exception is thrown between the calls to two methods? In the case of not calling the web services the transaction will rollback and no harm done. However, the web service will not rollback. Of course, even with a single web service there is a problem. While this is a generic question I am interested in solutions having to do with EJB session beans. An easy and customized answer would be to add a special "rollback method" to the web service for each "real functionality" method. What I am asking for is some standardized way to do so.
A number of techniques are evolving, but the problem is still sufficiently cutting edge that the standardization process has not yet provided us with a totally portable solution. Option one, you can make the web services transaction aware. This of course assumes you have control over them, although writing a transaction aware proxy for non-transactional services is also an option in some cases. The WS-AT and WS-BA protocols are the leading standards for transactional web services. Unfortunately they specify the protocol only, not the language bindings. In other words, there is no standard API at the programming language level. For Java the nearest thing is JSR-156, but it's not ready yet. Then the problem becomes: how to tie the EJB (i.e. JTA/XA) transaction to the WS one. Since the models used by the WS-AT and XA protocols are closely related, this can be achieved by means of a protocol bridge. Several app servers provide something alone these lines. JBoss presented theirs at JavaOne - see <http://anonsvn.jboss.org/repos/labs/labs/jbosstm/workspace/jhalliday/txbridge/BOF-4182.odp> Note that the protocol bridging technique can also be used the other way around, to allow an EJB that uses e.g. an XA database backend, to be exposed as a transactional web service. However, the locking model used by two phase commit transactions is really only suitable for short lived transactions in the same domain of control. If your services run in the same company datacenter you'll probably get away with it. For wider distribution, be it geographical or administrative, you probably want to look at WS-BA, a web service transactions protocol specifically designed for such use. WS-BA uses a compensation based model that is harder to program. It's essentially based on the technique you mention: the effect of service methods is undone by calling a compensation method. This can be tricky to get right, but a JBoss intern did a rather nice annotation framework that allows you to define compensation methods with minimal effort and have them driven automatically. It's not standardized, but well worth checking out if you choose this approach: [http://www.jboss.org/jbosstm/baframework](http://www.jboss.org/jbosstm/baframework/index.html)
Web Services-Coordination (WS-C) and Web Services-Transaction (WS-T) specifications developed by Microsoft, BEA Systems and IBM are used in such cases as I know. You can start from reading [Web services transactions](http://www-128.ibm.com/developerworks/xml/library/x-transws/) and [A comparison of Web services transaction protocols](http://www.ibm.com/developerworks/webservices/library/ws-comproto/) articles provided by IBM to make it clear.
Transaction rollback and web services
[ "", "java", "web-services", "transactions", "ejb", "rollback", "" ]
I recently started to learn about LINQ and came across the `OrderBy` extension method. This initially excited me because the syntax seemed much nicer than the `Sort` method that we use all over the place for Generic Lists. For example, when sorting a list of languages, we normally do something like: ``` neutralCultures.Sort((x, y) => x.EnglishName.CompareTo(y.EnglishName)); ``` This works well, but I prefer the syntax of `OrderBy`, which only requires that you pass in the property that you wish to sort by, like so: ``` neutralCultures.OrderBy(ci => ci.EnglishName); ``` The problem is that `OrderBy` returns `IOrderedEnumerable`, but I need `List<T>`. So, I set out to extend the `Sort` method for `List<T>` using the same signature that is used for `OrderBy`. ``` public static void Sort<TSource, TKey>(this List<TSource list, Func<TSource, TKey> keySelector) { list = list.OrderBy(keySelector).ToList<TSource>(); } ``` This would be called like: ``` neutralCultures.Sort(ci => ci.EnglishName); ``` Maybe I'm overlooking a simple implementation detail, but this code doesn't work. It compiles, but doesn't return an ordered list. I'm sure I can refactor this to make it work, but I was just wondering why setting `list` within the extension method doesn't work.
That's the behaviour I would expect. Imagine if such a thing were possible: ``` var c = myCustomer; myCustomer.DoStuff(); if (c == myCustomer) // returns false!!! ``` Simply calling a method on an object (which is what an extension method looks like to the user of your framework) shouldn't change which instance the reference points to. For your example, I would stick with Sort.
I've written Sort variants using a selector before - it isn't hard... something like: ``` using System; using System.Collections.Generic; class Foo { public string Bar { get; set; } } static class Program { static void Main() { var data = new List<Foo> { new Foo {Bar = "def"}, new Foo {Bar = "ghi"}, new Foo {Bar = "abc"}, new Foo {Bar = "jkl"} }; data.Sort(x => x.Bar); foreach (var item in data) { Console.WriteLine(item.Bar); } } static void Sort<TSource, TValue>( this List<TSource> source, Func<TSource, TValue> selector) { var comparer = Comparer<TValue>.Default; source.Sort((x,y) => comparer.Compare(selector(x), selector(y))); } } ```
Extension method not updating object passed in
[ "", "c#", ".net", "linq", "" ]
I am writing some UI tests using Selenium and i have a JavaScript Tree control, using the Dojo toolkit. I have implemented a context menu for each node of the tree using the examples that Dojo provide, but I need the Selenium test to "invoke" the right click on the tree node, but I cannot get this to work. The tests simply do not simulate the right-click event through JavaScript, and the context menu does not show up. Has anyone had any experience in invoking the right click on a context menu using Dojo and Selenium? Or have any ideas as to how to do it?
try this instead, reason what things didn't quite work is that the context menu is in fact bound to the oncontextmenu event. ``` function contextMenuClick(element){ var evt = element.ownerDocument.createEvent('MouseEvents'); var RIGHT_CLICK_BUTTON_CODE = 2; // the same for FF and IE evt.initMouseEvent('contextmenu', true, true, element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null); if (document.createEventObject){ // dispatch for IE return element.fireEvent('onclick', evt) } else{ // dispatch for firefox + others return !element.dispatchEvent(evt); } } ```
Just for good measure, here is a bit of doco on the parameters: ``` var myEvt = document.createEvent('MouseEvents'); myEvt.initMouseEvent( 'click' // event type ,true // can bubble? ,true // cancelable? ,window // the event's abstract view (should always be window) ,1 // mouse click count (or event "detail") ,100 // event's screen x coordinate ,200 // event's screen y coordinate ,100 // event's client x coordinate ,200 // event's client y coordinate ,false // whether or not CTRL was pressed during event ,false // whether or not ALT was pressed during event ,false // whether or not SHIFT was pressed during event ,false // whether or not the meta key was pressed during event ,1 // indicates which button (if any) caused the mouse event (1 = primary button) ,null // relatedTarget (only applicable for mouseover/mouseout events) ); ```
JavaScript simulate right click through code
[ "", "javascript", "selenium", "dojo", "mouseevent", "" ]
What would be the best way to write a generic copy constructor function for my c# classes? They all inherit from an abstract base class so I could use reflection to map the properties, but I'm wondering if there's a better way?
You can create a shallow copy **efficiently** with reflection by pre-compiling it, for example with `Expression`. For example, [like so](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/d9722a51b04300a/0edae91abc1c0f1a#0edae91abc1c0f1a). For deep copies, serialization is the most reliable approach.
A copy constructor basically means you have a single parameter, which is the object you're going to copy. Also, do a deep copy, not a shallow copy. If you don't know what deep and shallow copies are, then here's the deal: Suppose you're copying a class that has a single row of integers as field. A shallow copy would be: ``` public class Myclass() { private int[] row; public MyClass(MyClass class) { this.row = class.row } } ``` deep copy is: ``` public class Myclass() { private int[] row; public MyClass(MyClass class) { for(int i = 0; i<class.row.Length;i++) { this.row[i] = class.row[i]; } } } ``` A deep copy really gets the actuall values and puts them in a new field of the new object, whilst a shallow copy only copies the pointers. With the shallow copy, if you set: ``` row[3] = 5; ``` And then print both rows, both prints will have 5 as value of the 4th number. With a deep copy however, only the first print will have this, since the rows don't have the same pointers.
Generic C# Copy Constructor
[ "", "c#", "constructor", "copy", "" ]
I am querying information from [Active Directory](http://en.wikipedia.org/wiki/Active_Directory). I have code that works, but it's really slow. This is the code I currently use: ``` static void Main(string[] args) { SearchResultCollection sResults = null; try { //modify this line to include your domain name string path = "LDAP://EXTECH"; //init a directory entry DirectoryEntry dEntry = new DirectoryEntry(path); //init a directory searcher DirectorySearcher dSearcher = new DirectorySearcher(dEntry); //This line applies a filter to the search specifying a username to search for //modify this line to specify a user name. if you want to search for all //users who start with k - set SearchString to "k" dSearcher.Filter = "(&(objectClass=user))"; //perform search on active directory sResults = dSearcher.FindAll(); //loop through results of search foreach (SearchResult searchResult in sResults) { if (searchResult.Properties["CN"][0].ToString() == "Adit") { ////loop through the ad properties //foreach (string propertyKey in //searchResult.Properties["st"]) //{ //pull the collection of objects with this key name ResultPropertyValueCollection valueCollection = searchResult.Properties["manager"]; foreach (Object propertyValue in valueCollection) { //loop through the values that have a specific name //an example of a property that would have multiple //collections for the same name would be memberof //Console.WriteLine("Property Name: " + valueCollection..ToString()); Console.WriteLine("Property Value: " + (string)propertyValue.ToString()); //["sAMAccountName"][0].ToString(); } //} Console.WriteLine(" "); } } } catch (InvalidOperationException iOe) { // } catch (NotSupportedException nSe) { // } finally { // dispose of objects used if (sResults != null) sResults.Dispose(); } Console.ReadLine(); } ``` What would faster code look like to get user information from AD?
The reason why your code is slow is that your [LDAP](http://en.wikipedia.org/wiki/LDAP) query retrieves every single user object in your domain even though you're only interested in one user with a common name of "Adit": ``` dSearcher.Filter = "(&(objectClass=user))"; ``` So to optimize, you need to narrow your LDAP query to just the user you are interested in. Try something like: ``` dSearcher.Filter = "(&(objectClass=user)(cn=Adit))"; ``` In addition, don't forget to dispose these objects when done: * DirectoryEntry `dEntry` * DirectorySearcher `dSearcher`
You can call [`UserPrincipal.FindByIdentity`](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.userprincipal.findbyidentity?view=netframework-4.8) inside `System.DirectoryServices.AccountManagement`: ``` using System.DirectoryServices.AccountManagement; using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName")) { var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName); } ```
How can I retrieve Active Directory users by Common Name more quickly?
[ "", "c#", "active-directory", "" ]
In the past, I have not really used namespaces, but in this project I am using SourceSafe which requires a project, which puts everything in namespaces... In the past, I have just been able to make a public static class in the App\_Code folder and access it frorm anywhere in my application, but now I cant seem to do that. For example, my default.aspx.cs looks like this: ``` namespace Personnel_Database { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { utils.someFunction();//this does not work ``` and my utils.cs class looks like this: ``` namespace Personnel_Database.App_Code { public static class utils { ``` How can I have it so I can call **util.someMethod()** inside of my default? Am I wrong assuming it is a namespace problem? I just want **utils.cs** to be available globally inside namespace **Personnel\_Database**
Either you include the namespace with a using directive: ``` using Personnel_Database.App_Code; // now you can use everything that is inside the Personnel_Database.App_Code namespace namespace Personnel_Database { ... ``` Or you use the fully quallified name of the utils class (including its namespace), e.g: ``` protected void Page_Load(object sender, EventArgs e) { Personnel_Database.App_Code.utils.someFunction(); ... ```
You just need to add: ``` using Personnel_Database.App_Code; ``` to the top of your code-behind file. If you need access to it in the markup you can import it using: ``` <%@ Import Namespace="Personnel_Database.App_Code" %> ```
using a public static class in a 'Project' with defined namespaces
[ "", "c#", "asp.net", "static", "" ]
One of Steve McConnell's checklist items is that [you should not monkey with the loop index](http://www.matthewjmiller.net/files/cc2e_checklists.pdf) (Chapter 16, page 25, *Loop Indexes*, PDF format). This makes intuitive sense and is a practice I've always followed except maybe as I learned how to program back in the day. In a recent code review I found this awkward loop and immediately flagged it as suspect. ``` for ( int i=0 ; i < this.MyControl.TabPages.Count ; i++ ) { this.MyControl.TabPages.Remove ( this.MyControl.TabPages[i] ); i--; } ``` It's almost amusing since it manages to work by keeping the index at zero until all TabPages are removed. This loop could have been written as ``` while(MyControl.TabPages.Count > 0) MyControl.TabPages.RemoveAt(0); ``` And since the control was in fact written at about the same time as the loop it could even have been written as ``` MyControl.TabPages.Clear(); ``` I've since been challenged about the code-review issue and found that my articulation of **why** it is bad practice was not as strong as I'd have liked. I said it was harder to understand the flow of the loop and therefore harder to maintain and debug and ultimately more expensive over the lifetime of the code. Is there a better articulation of why this is bad practice?
I think your articulation is great. Maybe it can be worded like so: > Since the logic can be expressed much > clearer, it should.
Well, this adds confusion for little purpose - you could just as easily write: ``` while(MyControl.TabPages.Count > 0) { MyControl.TabPages.Remove(MyControl.TabPages[0]); } ``` or (simpler) ``` while(MyControl.TabPages.Count > 0) { MyControl.TabPages.RemoveAt(0); } ``` or (simplest) ``` MyControl.TabPages.Clear(); ``` In all of the above, I don't have to squint and think about any edge-cases; it is pretty clear what happens when. If you are modifying the loop index, you can quickly make it quite hard to understand at a glance.
Why is it bad to "monkey with the loop index"?
[ "", "c#", "for-loop", "" ]
I need to format a decimal value into a string where I always display at lease 2 decimals and at most 4. So for example ``` "34.49596" would be "34.4959" "49.3" would be "49.30" ``` Can this be done using the String.format command? Or is there an easier/better way to do this in Java.
You want java.text.DecimalFormat. ``` DecimalFormat df = new DecimalFormat("0.00##"); String result = df.format(34.4959); ```
Yes you can do it with `String.format`: ``` String result = String.format("%.2f", 10.0 / 3.0); // result: "3.33" result = String.format("%.3f", 2.5); // result: "2.500" ```
Java decimal formatting using String.format?
[ "", "java", "formatting", "decimal", "" ]
Parameters are used to protect you from malicious user input. But if the parameter expects a string, is it possible to write input that will be interpreted as sql, so malicious users can use things like 'DROP', 'TRUNCATE', etc...? Are there differences in protection between parameters in asp, asp.net, java and others? --- See also: [Are parameters really enough to prevent SQL injections?](https://stackoverflow.com/questions/306668/are-parameters-really-enough-to-prevent-sql-injections)
Parameterized queries generally quote the parameter if it is a string behind the scene so that the normal SQL operators are not interpreted as such. This means that even if a user enters potentially malicious data it is simply treated as a string input and not interpreted as SQL operators/commands. There may be technical differences in how it is implemented in the various frameworks, but the basic idea (and result) is the same.
You need to be careful with your definitions. 'Parameters' can mean a number of things; parameters to a stored procedure, for example, don't protect you at all in and of themselves. To use Java as an example: ``` sql = "exec proc_SearchForUser '" + userNameToSearch + "'"; ``` is no better or worse than the raw ``` sql = "SELECT * FROM Users WHERE userName = '" + userNameToSearch + "'"; ``` and is just as susceptible to the username ``` ';DROP TABLE users;-- ``` Parameterized queries, on the other hand, ARE safe. They might look like ``` PreparedStatement statement = con.prepareStatement("SELECT * FROM Users WHERE userName = ?"); ``` or indeed ``` PreparedStatement statement = con.prepareStatement("exec proc_SearchForUser ?"); ``` The reason this is safe is because when you fill in the value... using, say, ``` statement.setString(1, userName); ``` then the string -- even one like "';DROP TABLE users;--" -- will be properly escaped by the DB engine and rendered innocuous. It's still possible to screw it up -- for example, if your stored procedure just builds a SQL string internally and executes it, trusting the input -- but prepared statements with parameters mean that no unescaped data will ever get to the DB server, completely cutting off that attack vector.
From what do sql parameters protect you?
[ "", "sql", "database", "security", "parameters", "" ]
Here is the code to add a pfx to the Cert store. ``` X509Store store = new X509Store( StoreName.My, StoreLocation.LocalMachine ); store.Open( OpenFlags.ReadWrite ); X509Certificate2 cert = new X509Certificate2( "test.pfx", "password" ); store.Add( cert ); store.Close(); ``` However, I couldn't find a way to set permission for NetworkService to access the private key. Can anyone shed some light? Thanks in advance.
To do it programmatically, you have to do three things: 1. Get the path of the private key folder. 2. Get the file name of the private key within that folder. 3. Add the permission to that file. See [this post](http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2062983) for some example code that does all three (specifically look at the "AddAccessToCertificate" method).
This answer is late but I wanted to post it for anybody else that comes searching in here: I found an MSDN blog article that gave a solution using CryptoKeySecurity [here](http://blogs.msdn.com/b/cagatay/archive/2009/02/08/removing-acls-from-csp-key-containers.aspx), and here is an example of a solution in C#: ``` var rsa = certificate.PrivateKey as RSACryptoServiceProvider; if (rsa != null) { // Modifying the CryptoKeySecurity of a new CspParameters and then instantiating // a new RSACryptoServiceProvider seems to be the trick to persist the access rule. // cf. http://blogs.msdn.com/b/cagatay/archive/2009/02/08/removing-acls-from-csp-key-containers.aspx var cspParams = new CspParameters(rsa.CspKeyContainerInfo.ProviderType, rsa.CspKeyContainerInfo.ProviderName, rsa.CspKeyContainerInfo.KeyContainerName) { Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore, CryptoKeySecurity = rsa.CspKeyContainerInfo.CryptoKeySecurity }; cspParams.CryptoKeySecurity.AddAccessRule(new CryptoKeyAccessRule(sid, CryptoKeyRights.GenericRead, AccessControlType.Allow)); using (var rsa2 = new RSACryptoServiceProvider(cspParams)) { // Only created to persist the rule change in the CryptoKeySecurity } } ``` I'm using a SecurityIdentifier to identify the account but an NTAccount would work just as well.
How to set read permission on the private key file of X.509 certificate from .NET
[ "", "c#", ".net", "ssl", "ssl-certificate", "" ]
I'm beginning a new project in PHP and I'd love to get some feedback from other developers on their preferred strategy for PHP deployment. I'd love to automate things a bit so that once changes are committed they can be quickly migrated to a development or production server. I have experience with deployments using Capistrano with Ruby as well as some basic shell scripting. Before I dive head first on my own it would be great to hear how others have approached this in their projects. ## Further information Currently developers work on local installations of the site and commit changes to a subversion repository. Initial deployments are made by exporting a tagged release from svn and uploading that to the server. Additional changes are typically made piecemeal by manually uploading changed files.
For PHP, SVN with [Phing](http://phing.info/) build scripts are the way to go. Phing is similar to [ANT](http://ant.apache.org/) but is written in PHP, which makes it much easier for PHP developers to modify for their needs. Our deployment routine is as follows: * Everyone develops on the same local server at work, every developer has a checkout on his machine back home as well. * Commits trigger a post-commit hook which updates a staging server. * Tests are ran on staging server, if they pass - continue. * Phing build script is ran: * Takes down production server, switching the domain to an "Under construction" page * Runs SVN update on production checkout * Runs schema deltas script * Runs tests * If tests fail - run rollback script * If tests pass, server routes back to production checkout There's also [phpUnderControl](http://www.phpundercontrol.org/about.html), which is a Continuous Integration server. I didn't find it very useful for web projects to be honest.
I'm currently deploying PHP [using Git](https://stackoverflow.com/questions/279169/deploy-php-using-git#327315). A simple git push production is all that's needed to update my production server with the latest copy from Git. It's easy and fast because Git's smart enough to only send the diffs and not the whole project over again. It also helps keep a redundant copy of the repository on the web server in case of hardware failure on my end (though I also push to GitHub to be safe).
What is your preferred php deployment strategy?
[ "", "php", "deployment", "capistrano", "" ]
I really like the format and type of links from [RubyFlow](http://rubyflow.com) for Ruby related topics. Is there an equivalent for Python that's active? There is a [PythonFlow](http://pythonflow.com), but I think it's pretty much dead. I don't really like <http://planet.python.org/> because there's lots of non-Python stuff on there and there's very little summarization of posts.
<http://www.reddit.com/r/Python> is my favorite source for Python news.
Possibly <http://www.planetpython.org/> or <http://planet.python.org/>.
Is there a Python news site that's the near equivalent of RubyFlow?
[ "", "python", "" ]
Having a friendly debate with a co-worker about this. We have some thoughts about this, but wondering what the SO crowd thinks about this?
One reason is there is no CLR support for a readonly local. Readonly is translated into the CLR/CLI initonly opcode. This flag can only be applied to fields and has no meaning for a local. In fact, applying it to a local will likely produce unverifiable code. This doesn't mean that C# couldn't do this. But it would give two different meanings to the same language construct. The version for locals would have no CLR equivalent mapping.
I think it's a poor judgement on part of C# architects. readonly modifier on local variables helps maintain program correctness (just like asserts) and can potentially help the compiler optimize code (at least in the case of other languages). The fact that it's disallowed in C# right now, is another argument that some of the "features" of C# are merely an enforcement of personal coding style of its creators.
Why does C# disallow readonly local variables?
[ "", "c#", "immutability", "language-design", "readonly", "" ]
``` #include <iostream> using namespace std; class Base { public: Base(){cout <<"Base"<<endl;} virtual ~Base(){cout<<"~Base"<<endl;} virtual void foo(){ cout<<"foo base"<<endl;} }; class Derived: private Base { public: Derived(){cout<<"Derived"<<endl;} virtual ~Derived(){cout<<"~Derived"<<endl;} virtual void foo(){ cout<<"foo dervied"<<endl;} }; int main(int argc, char *argv[]) { Base *pb = new Derived; Derived d; d.foo(); return 0; } ``` when I execute the above sample program I get following error: protected.cpp: In function ‘int main(int, char\*\*)’: protected.cpp:26: error: ‘Base’ is an inaccessible base of ‘Derived’ Why its not possible to create Derived object with base pointer???? --- So I can create an instanse of Derived class like ``` Derived d Derived d1= new Derived; ``` But creating instance from Base class pointer like ``` Base * b = new derived ``` will fail. This is because Derived is not actaully a derived class from Base when derived procted and privately?? Is this correct?????
> Why its not possible to create Derived object with base pointer???? Because the base is `private`. This explicitly forbids treating your class as a `Base` instance from the outside. Seen from the outside, your class `Derived` is *not* a subclass of `Base`, only from inside the class itself. The same counts for `protected` inheritance, with the only difference that the base class now isn't private to the own class any more but rather to any derived class as well. To the outside though, it behaves just like private inheritance.
You might want to take a look at [this faq](http://www.parashift.com/c++-faq-lite/private-inheritance.html) on c++ and inheritance. Sections [24.5](http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.5) and [24.6](http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.6) in particular.
Protected derived class
[ "", "c++", "inheritance", "" ]
Consider the tables: (`->` denotes a SQL defined relationship) ``` USER (userid, username, imageid->IMAGE.imageid) EVENT (eventid, userid->USER.userid, description) IMAGE (imageid, location) ``` Say I have a view (let's call it `vw_UserInfo`) defined as the following query. ``` SELECT u.*, i.* FROM users u INNER JOIN images i ON i.imageid = u.imageid ``` Is SQL aware of the relationship between **`EVENT.userid`** and `vw_UserInfo.userid`? I mean, will the performance benefit of a `JOIN` operation on related fields still apply? I suppose this could vary depending on which SQL DB you're using. --- EDIT: In an attempt to be a bit clearer. I'm asking will ``` SELECT ui.*, e.* FROM vw_UserInfo ui INNER JOIN events e ON ui.userid = e.userid ``` Benefit from the foreign key defined just as much as ``` SELECT u.*, i.*, e.* FROM users u INNER JOIN images i ON i.imageid = u.imageid INNER JOIN events e ON e.userid = u.userid ``` would?
No, because views (at least in SQL Server) are not really part of the constraints system (the existence or non-existence of a view should not affect the performance of any query not referencing the view). Indexed views (materialized views), however, might be able to contribute to performance. I'm not sure which, if any, optimizers would use them in execution plans if they aren't explicitly referenced, though. If you read [this article by Celko](http://www.simple-talk.com/sql/t-sql-programming/constraint-yourself!/), you can see that the more metadata you give the database about the constraints and foreign-key relationships between your tables, this can improve the performance of queries.
Relationships enforce data integrity, they have nothing to do with quick selection of data. That is the realm of indexes. In general, relationships (especially on tables with many of them) *slow down* data access (especially writes).
Do SQL Views retain relationship information in terms of performance?
[ "", "sql", "performance", "" ]
Hey stackoverflow community! I'm having an issue where a highly involved algorithmic program is using TOO LITTLE cpu utilization: somewhere between 3 and 4%. It is taking very long to return results, and I believe it's just not working hard enough. Do any of you geniuses have any ideas why this would occur - if anything I would expect 100% utilization. One additional detail is that the program makes inserts into a sqlite3 database, and thus yes, there are a lot of JNI calls via the sqlite3jdbc library I believe. (Note that I wanted to defer these inserts with a PreparedQuery batch earlier, but this caused major memory problems - there's a lot of data). Thanks in advance UPDATE: Fixed. Yeah, I was just being a doofus, but I didn't expect that sqlite would start a new transaction and do so much overhead. I now use a PreparedStatement and queue 32768 entries before insert - seemed like a good enough number to me.
Obviously the database calls are causing delays. Isn't it an option to create smaller batches and test if that helps?? Maybe you could parallelize the algorithm as well to have a queue somewhere taking results and another thread cleaning out that queue? edit: There are also some other problem areas: * Database optimalization (model) * Database server configuration * Disk speed All these factors should be taken into account
I would never recommend that someone use a JDBC driver with JNI if a type IV, 100% Java version is available. Google found [this](http://zentus.com/sqlitejdbc/) one. With that aside, I can't tell anything without more info. Are the app and the database running on the same hardware? What is so "intensive" about INSERTs? I'd recommend profiling and getting some real data rather than guessing. Faith-based computing never works for me.
Too Little CPU Utilization in Java
[ "", "java", "cpu", "utilization", "" ]
``` string strLine;//not constant int index = 0; while(index < strLine.length()){//strLine is not modified}; ``` how many times `strLine.length()` is evaluated do we need to put use `nLength` with `nLength` assigned to `strLine.length()` just before loop
`length` will be evaluated every time you go via the loop, however since `length` is constant time (`O(1)`) it doesn't make much difference and adding a variable for storing this value will probably have a negligible effect with a small hit on code readability (as well as breaking the code if the string is ever changed).
length() is defined in headers which are included in your source file, so it can be inlined by compiler, it's internal calls also could be inlined, so if compiler would be able to detect that your string instance isn't changed in the loop then it can optimize access to length of a string, so it will be evaluated only once. In any case I don't think that storing value of string's length is really necessary. Maybe it can save you some nanosecs, but your code will be bigger and there will be some risk when you will decide to change that string inside loop.
Condition evaluation in loops?
[ "", "c++", "loops", "evaluation", "conditional-statements", "" ]
I know I've seen this done before but I can't find the information anywhere. I need to be able to route with .html extensions in the Zend Framework. I.E. /controller/action.html should route to the appropriate controller / action. We have an idea to throw away the .html extension with our .htaccess file but I think changing the route config would be the better solution. Any advice is welcome.
A quick search on google yielded the following tutorials: [Extending Zend Framework Route and Router for custom routing](http://my.opera.com/zomg/blog/2007/09/19/extending-zend-framework-route-and-router-for-custom-routing) [Routing and complex URLs in Zend Framework](http://codeutopia.net/blog/2007/11/16/routing-and-complex-urls-in-zend-framework/)
This is the plugin I've used in several applications: ``` /** * Removes .html extension from URI, if present. */ class Application_Plugin_RemoveHtmlExtension extends Zend_Controller_Plugin_Abstract { public function routeStartup(Zend_Controller_Request_Abstract $request) { // remove ".html" from the end of the URI $url = preg_replace('#\.html$#i', '', $request->getRequestUri()); $request->setRequestUri($url); } } ```
Zend Framework Routing: .html extension
[ "", "php", "zend-framework", "url", "url-routing", "" ]
I'm looking to make calls out to a subversion repository, but I would like to write it in C#. Does anyone know of any good libraries?
Have a look at [SharpSVN](http://sharpsvn.open.collab.net/). This is an open-source binding of the Subversion Client API for .Net 2.0 applications. For example, this library is used by the [AnkhSVN](http://ankhsvn.open.collab.net/) Visual Studio Add-In.
I recommend you look at the [Tortoise SVN source code](http://code.google.com/p/tortoisesvn/source/browse/). It is mostly in C++, but since it is all done in VS, it should be easy to wrap up and use much of the code again. You can also try [SubversionSharp](http://www.softec.st/en/OpenSource/ClrProjects/SubversionSharp/SubversionSharp.html) if you want less heavy lifting (however it is not yet a stable release, so be cautious).
Does anyone know of a good C# API for Subversion?
[ "", "c#", ".net", "svn", "sharpsvn", "" ]
I was sitting here wondering if it's possible to write a greasemonkey script that would detect sites like payperclick and mute the audio so the ad isn't heard. I realize that I could accomplish the same thing in a better fashion by simply removing the ad text through a greasemonkey script but for purposes of curiousity, I wondered if you can disable the audio through javascript.
The only way **I** can see this being possible is if: 1)the ad has its own "mute button" which called a javascript function...in which case you could just call that function yourself. 2) The plugin the ad is using for audio has a javascript API (same as 1) 3) IE only: some bizarre IE ActiveX thing that could probably do it...by accessing stuff that it probably shouldn't. All of these I consider extremely doubtful Any other possibility would be too low level for javascript to have access to (or at least I seriously hope that is the case). A browser by itself has no volume controls....all multimedia are done by plugins.
Other than completely stripping the <embed> element, it's a no-go; JavaScript simply doesn't have the power to access the volume controls of Flash media... yet. : )
Mute Audio from Javascript?
[ "", "javascript", "audio", "mute", "" ]
When embedding a flash object, is there a way to determine when it's fully loaded? That's my basic question, but for anyone interested in the details behind it: I am using the ([DOMWindow](http://swip.codylindley.com/DOMWindowDemo.html)) jQuery plugin. For those not familiar, it's a basic overlay the appears centered on the page, above all other content which is dimmed. Inside of the DOMWindow, I am embedded a YouTube video. The markup used to embed the video is AJAX injected. The DOMWindow has a built in loading graphic, but the problem I am having is that the AJAX GET request is completed almost instantly, and for 3-5 seconds, I'm stuck looking at a white rectangle while waiting for the YouTube video to load. If I could figure out how to determine when it's finished loading, I could code a more graceful loading scheme (using a animated spinner) inside of the DOMWindow.
You should take a look at this page [Youtube Player Javascript API](http://code.google.com/apis/youtube/js_api_reference.html). Subscribing to the onStateChange Event and looking for it to return 5 appears to be what you want to do. I'll leave my original answer, in case it might still be handy. It is below. You may want to look at this [blog entry](http://coderaptor.wordpress.com/2007/09/10/using-javascript-to-handle-flash-actionscript-events/). He is passing Flash events to javascript to monitor a video. He specifically mentions waiting for the movie to dl and attach to the player. I'm not sure these techniques work with the youtube player.
It you're looking for a more general Flash reference, Flash makes available OnProgress, OnReadyStateChange and PercentLoaded as Javascript properties of the OBJECT or EMBED element. <http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html>
How to determine when an embedded flash object is loaded?
[ "", "javascript", "jquery", "flash", "" ]
EDIT: now the question becomes, how do I tell Sajax to use POST instead of GET? I've tried some examples from google but they are sketchy, and as I said, they didn't work. I know, we're all jQuery nuts around here. I've used the following code to try and find a limit to the amount of data that can be sent to the server via an ajax call. We use Sajax, obviously. In IE, after somewhere around 1900 characters, the data doesn't get through and we get an error. In Firefox, the limit is somewhere around 6100, but seems to vary a bit on each call. Is this browser-dependent? Also tried to use POST instead of the default get and telling Sajax to use POST didn't work at all. Is there a limit to the data stream size sent in AJAX defined anywhere? How about from experience? ``` <? require('sites/includes/Sajax.inc.php'); function str_length_test($str){ return strlen($str); } sajax_init(); sajax_export('str_length_test'); sajax_handle_client_request(); ?> <html> <head> <title>Multiplier</title> <script> <? sajax_show_javascript(); ?> function do_str_length_test_cb(pwd) { document.getElementById('str_length').value = pwd; } function do_str_length_test() { sample_field = document.getElementById('sample').value; x_str_length_test(sample_field, do_str_length_test_cb); } </script> </head> <body> <textarea id="sample" name="sample" rows=20 cols=60 onblur="do_str_length_test(); return false;"></textarea> Size: <input type="text" id="str_length" name="str_length" value="" size=10> </body> </html> ```
GET is limited in IE to 2083 chars see <http://support.microsoft.com/kb/208427> See [here](https://stackoverflow.com/questions/179264/what-is-the-optimum-limit-for-url-length-100-200) for url length for discussion.
I see this on the sajax examples: ``` $sajax_request_type = "GET"; sajax_init(); sajax_export("add_line", "refresh"); sajax_handle_client_request(); ``` I'm guessing you just change the GET to POST. ``` $sajax_request_type = "POST"; ```
AJAX browser-dependent limit on length of data sent? (SAJAX)
[ "", "php", "ajax", "xmlhttprequest", "cross-browser", "sajax", "" ]
Suppose I have a class ``` public class MyClass { private Set<String> set = new HashSet<String>(); //and many methods here } ``` is there a possibility to make an eclipse debugger stop at every line where set member is used?
I haven't used Eclipse for a while, but from what I remember this was possible in the Callisto release at least. If you set a breakpoint on the line containing the declaration, and then go into the advanced properties for that breakpoint, I believe you can set options for *modification* and *access* of that variable. *Edit*: I just checked with Eclipse Europa. It does work broadly as I thought; the breakpoint is called a *watch*point when you set it on a variable; and in the "Breakpoint Properties" page (accessible by right-clicking on the breakpoint's bauble in the margin, and possibly in other ways) you can determine whether the debugger should stop on "Field access" and "Field Modification". In your case, you want the first one selected.
Yes. You can put a breakpoint at the expression ``` private String propString; ``` The breakpoint gets another symbol and shows the tool tip "Watchpoint [Acess and modification] " Whith Shift+Ctrl+I you can watch the value of a selected variable name when the debugger is in step mode. You also can change variable values at runtime when the debugger is in step mode. The eclipse debugger is a very useful and powerful tool.
Is there a possibility to break on every object reference in eclipse debugger?
[ "", "java", "eclipse", "debugging", "" ]
Visual Studio complains: **Warning 1 The designer must create an instance of type 'RentalEase.CustomBindingNavForm' but it cannot because the type is declared as abstract.** Visual Studio won't let me access the Designer for the form. The class already implements all abstract methods from the CustomBindingNavForm. CustomBindingNavForm provides some functions concrete and abstract. Is there a way around this? Here is the class: ``` public abstract class CustomBindingNavForm : SingleInstanceForm { //Flags for managing BindingSource protected bool isNew = false; protected bool isUpdating = false; /// <summary> /// This is so that when a new item is added, it sets isNew and firstPass to true. The Position Changed Event will look for /// firstPass and if it is true set it to false. Then on the next pass, it will see it's false and set isNew to false. /// This is needed because the Position Changed Event will fire when a new item is added. /// </summary> protected bool firstPass = false; protected abstract bool validateInput(); protected abstract void saveToDatabase(); //manipulating binding protected abstract void bindingSourceCancelResetCurrent(); protected abstract void bindingSourceRemoveCurrent(); protected abstract void bindingSourceMoveFirst(); protected abstract void bindingSourceMoveNext(); protected abstract void bindingSourceMoveLast(); protected abstract void bindingSourceMovePrevious(); protected abstract void bindingSourceAddNew(); public void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e) { if (validateInput()) { bindingSourceMovePrevious(); } else { DialogResult cont = MessageBox.Show(null, "There are errors in your data. Click Cancel to go back and fix them, or ok to continue. If you continue, changes will not be saved.", "Continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (cont == DialogResult.OK) { if (isNew) { bindingSourceRemoveCurrent(); isNew = false; } else { bindingSourceCancelResetCurrent(); bindingSourceMovePrevious(); } } } } public void bindingNavigatorAddNewItem_Click(object sender, EventArgs e) { if (validateInput()) { saveToDatabase(); bool temp = isUpdating; isUpdating = true; bindingSourceAddNew(); isUpdating = temp; isNew = true; firstPass = true; } else { DialogResult cont = MessageBox.Show(null, "There are errors in your data. Click Cancel to go back and fix them, or ok to continue. If you continue, changes will not be saved.", "Continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (cont == DialogResult.OK) { if (isNew) { bindingSourceRemoveCurrent(); isNew = false; } else { bindingSourceCancelResetCurrent(); } bool temp = isUpdating; isUpdating = true; bindingSourceAddNew(); isUpdating = temp; isNew = true; firstPass = true; } } } public void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e) { if (validateInput()) { bindingSourceMoveFirst(); } else { DialogResult cont = MessageBox.Show(null, "There are errors in your data. Click Cancel to go back and fix them, or ok to continue. If you continue, changes will not be saved.", "Continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (cont == DialogResult.OK) { if (isNew) { bindingSourceRemoveCurrent(); isNew = false; } else { bindingSourceCancelResetCurrent(); } bindingSourceMoveFirst(); } } } public void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e) { if (validateInput()) { bindingSourceMoveNext(); } else { DialogResult cont = MessageBox.Show(null, "There are errors in your data. Click Cancel to go back and fix them, or ok to continue. If you continue, changes will not be saved.", "Continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (cont == DialogResult.OK) { if (isNew) { bindingSourceRemoveCurrent(); isNew = false; } else { bindingSourceCancelResetCurrent(); } bindingSourceMoveNext(); } } } } ```
I haven't seen the content at urban potato (its down) but Me and [Smelch](https://stackoverflow.com/users/245808/smelch) came up with a solution. **`Form` itself inherits from an abstract class, so** what they dont tell you is that **its only the 1st level of inheritance that can't be abstract, the 2nd on down can.** From there its simply a matter of having an empty class in the middle and wrapping an `#if debug` around the forms declaration and you're good to go. Just be sure to release in release mode and design in debug mode (which is very typical). You'll get full designer support and a real abstract base class at design (debug) and build (release) time because each time it ends up using your abstract base class. [The full explanation and answer is here](https://stackoverflow.com/questions/1620847/how-can-i-get-vs2008-winforms-designer-to-render-a-form-that-implements-an-abstra/2406058#2406058)
You can solve this using an attribute on your abstract class like the following ``` [TypeDescriptionProvider(typeof(AbstractControlDescriptionProvider<MyBaseFormEf, Form>))] ``` This will work for every case where you need it. The AbstractControlDescriptionProvider is below ``` public class AbstractControlDescriptionProvider<TAbstract, TBase> : TypeDescriptionProvider { public AbstractControlDescriptionProvider() : base(TypeDescriptor.GetProvider(typeof(TAbstract))) { } public override Type GetReflectionType(Type objectType, object instance) { if (objectType == typeof(TAbstract)) return typeof(TBase); return base.GetReflectionType(objectType, instance); } public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { if (objectType == typeof(TAbstract)) objectType = typeof(TBase); return base.CreateInstance(provider, objectType, argTypes, args); } } ```
The designer must create an instance of...cannot because the type is declared abstract
[ "", "c#", ".net", "winforms", "abstract", "" ]
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well. ``` public class Main { public interface Visitor{ int doJob(int a, int b); } public static void main(String[] args) { Visitor adder = new Visitor(){ public int doJob(int a, int b) { return a + b; } }; Visitor multiplier = new Visitor(){ public int doJob(int a, int b) { return a*b; } }; System.out.println(adder.doJob(10, 20)); System.out.println(multiplier.doJob(10, 20)); } } ```
Since Java 8, there are lambda and method references: * [Oracle Docs: Lambda Expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) * [Oracle Docs: Method References](http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) For example, if you want a functional interface `A -> B`, you can use: ``` import java.util.function.Function; public MyClass { public static String applyFunction(String name, Function<String,String> function){ return function.apply(name); } } ``` And here is how you can call it: ``` MyClass.applyFunction("42", str -> "the answer is: " + str); // returns "the answer is: 42" ``` Also you can pass class method. For example: ``` @Value // lombok public class PrefixAppender { private String prefix; public String addPrefix(String suffix){ return prefix +":"+suffix; } } ``` Then you can do: ``` PrefixAppender prefixAppender= new PrefixAppender("prefix"); MyClass.applyFunction("some text", prefixAppender::addPrefix); // returns "prefix:some text" ``` **Note**: Here I used the functional interface `Function<A,B>`, but there are many others in the package `java.util.function`. Most notable ones are * `Supplier`: `void -> A` * `Consumer`: `A -> void` * `BiConsumer`: `(A,B) -> void` * `Function`: `A -> B` * `BiFunction`: `(A,B) -> C` and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own `FunctionalInterface`: ``` @FunctionalInterface interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out public Out apply(In1 in1, In2 in2, In3 in3); } ``` Example of use: ``` String computeAnswer(Function3<String, Integer, Integer, String> f){ return f.apply("6x9=", 6, 9); } computeAnswer((question, a, b) -> question + "42"); // "6*9=42" ``` And you can also do that with thrown exception: ``` @FunctionalInterface interface FallibleFunction<In, Out, Ex extends Exception> { Out get(In input) throws Ex; } public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex { return f.get(42); } ```
Callback functions in Java
[ "", "java", "callback", "function-pointers", "" ]
In my C# application, I have a large struct (176 bytes) that is passed potentially a hundred thousand times per second to a function. This function then simply takes a pointer to the struct and passes the pointer to unmanaged code. Neither the function nor the unmanaged code will make any modifications to the struct. My question is, should I pass the struct to the function by value or by reference? In this particular case, my guess is that passing by reference would be much faster than pushing 176 bytes onto the call stack, unless the JIT happens to recognize that the struct is never modified (my guess is it can't recognize this since the struct's address is passed to unmanaged code) and optimizes the code. Since we're at it, let's also answer the more general case where the function does *not* pass the struct's pointer to unmanaged code, but instead performs some read-only operation on the contents of the struct. Would it be faster to pass the struct by reference? Would in this case the JIT recognize that the struct is never modified and thus optimize? Presumably it is *not* more efficient to pass a 1-byte struct by reference, but at what struct size does it become better to pass a struct by reference, if ever? Thanks. EDIT: As pointed out below, it's also possible to create an "equivalent" class for regular use, and then use a struct when passing to unmanaged code. I see two options here: 1) Create a "wrapper" class that simply contains the struct, and then pin and pass a pointer to the struct to the unmanaged code when necessary. A potential issue I see is that pinning has its own performance consequences. 2) Create an equivalent class whose fields are copied to the struct when the struct is needed. But copying would take a lot of time and seems to me to defeat the point of passing by reference in the first place. EDIT: As mentioned a couple times below, I could certainly just measure the performance of each of these methods. I *will* do this and post the results. However, I am still interested in seeing people's answers and reasonings from an intellectual perspective.
I did some very informal profiling, and the results indicate that, for my particular application, there is a modest performance gain for passing by reference. For by-value I got about 10,050,000 calls per second, whereas for by-reference I got about 11,200,000 calls per second. Your mileage may vary.
Before you ask whether or not you should pass the struct by reference, you should ask yourself why you've got such an enormous struct in the first place. Does it *really* need to be a struct? If you need to use a struct at some point for P/Invoke, would it be worth having a struct *just* for that, and then the equivalent class elsewhere? A struct that big is very, very unusual... See the [Design Guidelines for Developing Class Libraries](http://msdn.microsoft.com/en-us/library/ms229042.aspx) section on [Choosing Between Classes and Structures](http://msdn.microsoft.com/en-us/library/ms229017.aspx) for more guidance on this.
In .Net, when if ever should I pass structs by reference for performance reasons?
[ "", "c#", ".net", "optimization", "" ]
**Note: solution at the end** If I attempt to do a HTTP POST of over 1024 characters, it fails. Why? Here is a minimal example: recipient.php: ``` <?php if (strlen(file_get_contents('php://input')) > 1000 || strlen($HTTP_RAW_POST_DATA) > 1000) { echo "This was a triumph."; } ?> ``` sender.php: ``` <?php function try_to_post($char_count) { $url = 'http://gpx3quaa.joyent.us/test/recipient.php'; $post_data = str_repeat('x', $char_count); $c = curl_init(); curl_setopt_array($c, array( CURLOPT_URL => $url, CURLOPT_HEADER => false, CURLOPT_CONNECTTIMEOUT => 999, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $post_data ) ); $result = curl_exec($c); echo "{$result}\n"; curl_close($c); } for ($i=1020;$i<1030;$i++) { echo "Trying {$i} - "; try_to_post($i); } ?> ``` output: ``` Trying 1020 - This was a triumph. Trying 1021 - This was a triumph. Trying 1022 - This was a triumph. Trying 1023 - This was a triumph. Trying 1024 - This was a triumph. Trying 1025 - Trying 1026 - Trying 1027 - Trying 1028 - Trying 1029 - ``` configuration: ``` PHP Version 5.2.6 libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3 libidn/1.8 lighttpd-1.4.19 ``` **Solution** Add the following option for cURL: ``` curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:")); ``` The reason seems to be that any POST over 1024 character causes the "Expect: 100-continue" HTTP header to be sent, and Lighttpd 1.4.\* does not support it. I found a ticket for it: <http://redmine.lighttpd.net/issues/show/1017> They say it works in 1.5.
You can convince PHP's curl backend to stop doing the 100-continue-thing by setting an explicit request header: ``` curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); ``` This way you can post a request however long you would ever want and curl will not do the dual phase post. I've [blogged about this](http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/) nearly two years ago.
## First thoughts... The manual page for [curl\_setopt](http://php.net/curl_setopt) says of CURLOPT\_POSTFIELDS > "The full data to post in a HTTP "POST" > operation. To post a file, prepend a > filename with @ and use the full path. > This can either be passed as a > urlencoded string like > 'para1=val1&para2=val2&...' or as an > array with the field name as key and > field data as value." Could it be that your value is being treated as if it were urlencoded, and thus looks like a big long name with no value. Something somewhere is deciding to truncate that name. Maybe you could alter it to something like ``` $post_data = "data=".str_repeat('x', $char_count); ``` Turns out this was too easy, and the problem was a little deeper. So, how to debug? ## Find out exactly what CURL sends to the server Another debugging tactic might be to formulate a curl command line which achieves the same thing, and have it output the HTTP request details as it makes them. ## Testing the server by hand You can eliminate the server from the equation by perform a request by hand, e.g. telnetting to port 80 on your server and sending it a request >1024 chars ``` POST /test/recipient.php HTTP/1.0 Host: gpx3quaa.joyent.us Content-Length:1028 xxxxx(I put 1028 chars here, no point copying them all here!) ``` I got this response ``` HTTP/1.0 200 OK Connection: close Content-type: text/html; charset=UTF-8 Content-Length: 19 Date: Tue, 20 Jan 2009 21:35:16 GMT Server: lighttpd/1.4.19 This was a triumph.Connection closed by foreign host. ``` So at least you now know it's all on the client side, possible some CURL option or configuration setting somewhere :( ## Final Answer! The problem intrigued me so I dug deeper If you use `CURLOPT_VERBOSE=>true`, you'll see that CURL sends an extra header on the bigger posts:`Expect: 100-Continue`. Your lighttpd server doesn't like this, it would seem. You can stop CURL from doing this by forcing it to use HTTP/1.0 with `CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0` in your curl\_setopt options array.
PHP HTTP POST fails when cURL data > 1024
[ "", "php", "http", "post", "curl", "" ]
I've been trying to grok the org.apache.commons.beanutils library for a method/idiom to evaluate for equality *all* properties between 2 instances i.e. a generic equals() method for beans. Is there a simple way to do this usnig this library? Or am I going about this the wrong way? Thanks.
Try [EqualsBuilder.reflectionEquals()](https://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/builder/EqualsBuilder.html#reflectionEquals%28java.lang.Object,%20java.lang.Object,%20boolean%29) of [commons-lang](http://commons.apache.org/lang/). EqualsBuilder has a set of methods to include all fields, all non-transient fields and all but certain fields. If all else fails, the code could serve as a good example how to implement this.
To answer your question directly, you could use reflection to do equality checking of beans. There are a few snags you need to be aware of. There are rules regarding the behaviour of equals() and hashcode(). These rules talk about symmetry, consitency and reflexiveness which may be hard to do when your equals method behaves dynamically based on the other object you're passing in. Interesting read: <http://www.geocities.com/technofundo/tech/java/equalhash.html> Generally speaking, I think you are better off creating your own hashcode and equals methods. There are a fwe good plugins which can automatically generate that code for you based on the class properties. Having said all this, here are some (old style) methods for getting getters, setters and properties I wrote a long time ago: ``` private Map getPrivateFields(Class clazz, Map getters, Map setters) { Field[] fields = clazz.getDeclaredFields(); Map m = new HashMap(); for (int i = 0; i < fields.length; i++) { int modifiers = fields[i].getModifiers(); if (Modifier.isPrivate(modifiers) && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) { String propName = fields[i].getName(); if (getters.get(propName) != null && setters.get(propName) != null) { m.put(fields[i].getName(), fields[i]); } } } return m; } ``` The Getters: ``` private Map getGetters(Class clazz) { Method[] methods = clazz.getMethods(); Map m = new HashMap(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().startsWith("get")) { int modifiers = methods[i].getModifiers(); if (validAccessMethod(modifiers)) { m.put(getPropertyName(methods[i].getName()), methods[i]); } } } return m; } ``` And the Setters: ``` private Map getSetters(Class clazz, Map getters) { Method[] methods = clazz.getMethods(); Map m = new HashMap(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().startsWith("set")) { int modifiers = methods[i].getModifiers(); String propName = getPropertyName(methods[i].getName()); Method getter = (Method) getters.get(propName); if (validAccessMethod(modifiers) && getter != null) { Class returnType = getter.getReturnType(); Class setType = methods[i].getParameterTypes()[0]; int numTypes = methods[i].getParameterTypes().length; if (returnType.equals(setType) && numTypes == 1) { m.put(propName, methods[i]); } } } } return m; } ``` Maybe you can use this to roll your own. **Edit:** Ofcourse the [reflectionbuilder](http://commons.apache.org/lang/api/org/apache/commons/lang/builder/EqualsBuilder.html#reflectionEquals(java.lang.Object,%20java.lang.Object)) in [Aaron Digulla's answer](https://stackoverflow.com/questions/472626/how-to-generically-compare-entire-java-beans#472705) is much better than my handywork.
how to generically compare entire java beans?
[ "", "java", "javabeans", "" ]
I like to keep javascript debugging enabled in my browser so when I'm developing my own code I can instantly see when I've made an error. Of course this means I see errors on apple.com, microsoft.com, stackoverflow.com, cnn.com, facebook.com. Its quite fun sometimes to see just how much awful code there is out there being run by major sites but sometimes it gets really annoyed. I've wondered for YEARS how to change this but never really got around to it. Its particularly annoying today and I'd really like to know of any solutions. The only solution I have is : use a different browser for everyday browsing. I'm hopin theres some quick and easy plugin someone can direct me to where I can toggle it on and off based upon the domain i'm on. **Edit:** I generally use IE7 for everyday browsing
Firebug lets you enable/disable debugging for different domains.
Script Debugging in IE7 is controlled by a registry key. (An addon could probably toggle it. I just don't know of any.) So, how I handle this is to write a registry script to turn it on or off. Then, I put a link to those scripts on my windows quick-launch bar and change their icons to be more appropriate. Then, I can just click one of the links to turn on or off IE script debugging. **Turn Off:** ``` REGEDIT4 [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main] "Disable Script Debugger"="yes" "DisableScriptDebuggerIE"="yes" ``` **Turn ON:** ``` REGEDIT4 [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main] "Disable Script Debugger"="no" "DisableScriptDebuggerIE"="no" ```
How to suppress javascript errors for sites I'm not developing?
[ "", "javascript", "debugging", "internet-explorer", "" ]
So my 2009 new years resolution is to learn Java. I recently acquired "Java for Dummies" and have been following along with the demo code in the book by re-writing it using Eclipse. Anyway, every example in the book that uses a relative path does not seem to read the .txt file it's supposed to read from. Here is the sample code: ``` import java.util.Scanner; import java.io.File; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.GridLayout; class TeamFrame extends JFrame { public TeamFrame() throws IOException { PlayerPlus player; Scanner myScanner = new Scanner(new File("Hankees.txt")); for (int num = 1; num <= 9; num++) { player = new PlayerPlus(myScanner.nextLine(), myScanner.nextDouble()); myScanner.nextLine(); addPlayerInfo(player); } add(new JLabel()); add(new JLabel(" ------")); add(new JLabel("Team Batting Aberage:")); add(new JLabel(PlayerPlus.findTeamAverageString())); setTitle("The Hankees"); setLayout(new GridLayout(11,2)); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setVisible(true); } void addPlayerInfo(PlayerPlus player) { add(new JLabel(player.getName())); add(new JLabel(player.getAverageString())); } } ``` And you can see in the below screen shot I have included this file. *image no longer available* Also, I have verified that when I build the application that a copy of Hankees.txt is placed in the bin folder with the compiled .class files. Lastly, if I change line 12 to the following and place Hankees.txt in the root of my C:\ drive the program compiles and runs fine. ``` Scanner myScanner = new Scanner(new File("C:\\Hankees.txt")); ``` So basically, my question is what am I doing wrong? Or is Eclipse responsible for this in some way? Thanks for any and all help!
You need `"src/Hankees.txt"` Your file is in the source folder which is not counted as the working directory.\ Or you can move the file up to the root directory of your project and just use `"Hankees.txt"`
A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files. New run configurations default to using the project directory for the working directory, though this can also be changed. This code shows the difference between the working directory, and the location of where the class was loaded from: ``` public class TellMeMyWorkingDirectory { public static void main(String[] args) { System.out.println(new java.io.File("").getAbsolutePath()); System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath()); } } ``` The output is likely to be something like: ``` C:\your\project\directory /C:/your/project/directory/bin/ ```
How do relative file paths work in Eclipse?
[ "", "java", "eclipse", "file-io", "relative-path", "" ]
I've gotten a request to show a person's local time based on their phone number. I know our local GMT offset, so I can handle USA phones via a database table we have that links US zip\_code to GMT offset (e.g. -5). But I've no clue how to convert non-US phone numbers or country names (these people obviously don't have a zip code). If you care, my employer college wants to solicit our alumni for donations and do it during reasonable hours. Sorry to all that I didn't *clearly* state that I was considering **HOME** phone numbers. So roaming isn't an issue. I'm looking for some reference table or Oracle application I can source this info from.
Florida has two time zones, but many countries only have one. You need this table: <http://en.wikipedia.org/wiki/List_of_country_calling_codes> . Parse the country code out of the phone number by looking for the 1 and the area code for NANPA countries (those countries using the same 1+area code allocation as the USA), 7 for Russia or Kazakhstan. If that doesn't match check to see whether the number starts with one of the 2 digit calling prefixes, and then the 3-digit ones. Remember that the first few digits of the number may be the international dialing prefix, and are not properly part of the telephone number. For countries that span more than one time zone, see if you can get allocation information from their national telecom regulator. For the USA and other NANPA countries, check out <http://www.nanpa.com/> . Of course your results will be far from perfect, but hopefully you will wake fewer customers from their night's sleep.
Local time is one thing but, if you have worldwide customers, there are also local habits to take into account. People typically go to bed earlier in Norway than in Spain (and they are in the same time zone).
Calculating person's time zone (GMT offset) based on phone number?
[ "", "sql", "oracle", "timezone-offset", "" ]
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String. Getting the field names is fairly simple, here is what a co-worker came up with: ``` public static List initFieldArray(String className) throws ClassNotFoundException { Class c = Class.forName(className); Field field[] = c.getFields(); List<String> classFields = new ArrayList(field.length); for (int i = 0; i < field.length; i++) { String cf = field[i].toString(); classFields.add(cf.substring(cf.lastIndexOf(".") + 1)); } return classFields; } ``` Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive. Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
Apache commons-lang [ReflectionToStringBuilder](http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html) does this for you. ``` import org.apache.commons.lang3.builder.ReflectionToStringBuilder // your code goes here public String toString() { return ReflectionToStringBuilder.toString(this); } ```
Another option, if you are ok with JSON, is Google's GSON library. ``` public String toString() { return new GsonBuilder().setPrettyPrinting().create().toJson(this); } ``` It's going to do the reflection for you. This produces a nice, easy to read JSON file. Easy-to-read being relative, non tech folks might find the JSON intimidating. You could make the GSONBuilder a member variable too, if you don't want to new it up every time. If you have data that can't be printed (like a stream) or data you just don't want to print, you can just add @Expose tags to the attributes you want to print and then use the following line. ``` new GsonBuilder() .setPrettyPrinting() .excludeFieldsWithoutExposeAnnotation() .create() .toJson(this); ```
Java toString() using reflection?
[ "", "java", "performance", "reflection", "tostring", "" ]
I want to make sure a file path set via query string does not go outside of the desired subdirectory. Right now, I am checking that: 1. The path does not start with "`/`", to prevent the user from giving an absolute path. 2. The path does not contain "`..`", to prevent the user from giving a path that is outside of the desired subdirectory. 3. The path does not contain "`:`", to prevent the use of a url (i.e. "`http://`", "`ftp://`", etc.). Should I ever run this script on a Windows server (not likely), this will also prevent absolute paths beginning with a drive specifier (i.e. "`C:\`"). Note: I'm aware that a colon is a valid character in a Unix filenames, but I will never be using it in a filename. 4. The path does not start with "`\`". Just in case I change my mind about running on a Windows server, this prevents Windows network paths from being specified (i.e. "`\\someserver\someshare`"). Again, I'm aware that a backslash is a valid Unix filename character, but I also won't be using it in any filenames. Are these checks sufficient? **Background** I have a PHP script that takes (via query string) the path to a sample source file to be shown to a user. So I might give them a link like "`view_sample.php?path=accounting_app/report_view.php`" or "`view_sample.php?path=ajax_demo/get_info.js`". The script looks basically like this: ``` $path = $_GET['path']; if(path_is_valid($path) && is_file("sample/$path")) { header('Content-Type: text/plain'); readfile("sample/$path"); } ``` My concern is that a malicious user would see the url and try to do something like "`view_sample.php?path=../../database/connection_info.php`" and gain access to a file which is **not** in the "sample" directory. Are the four checks I defined above (which would be implemented in the `path_is_valid()` function) sufficient to lock out a malicious user? (Also, I think checks 1, 3, and 4 are basically irrelevant since I am prepending a relative path, but if I didn't do this would the checks be sufficient?)
Call ``` $path = realpath("sample/$path"); ``` Then check that the resulting path starts with the directory you're expecting.
``` <?php // Current path information $path = $_GET['path']; $vroot = "sample"; // Validate that the $path is a subfolder of $vroot $vroot = realpath($vroot); if(substr(realpath($path), 0, strlen($vroot)) != $vroot or !is_dir($path)) {lid! exit("Invalid path"); } else { echo "Ah, everything is alright!"; } ?> ```
How do I make sure a file path is within a given subdirectory?
[ "", "php", "security", "sanitization", "" ]
I have a file called **hellowf.cs** ``` class MyFirstApp { static void Main() { System.Windows.Forms.MessageBox.Show("Hello, Mono+WinForms!"); } } ``` On Ubuntu 8.10, I do the following ``` gmcs hellowf.cs -r:System.Drawing.dll -r:System.Windows.Forms.dll mono hellowf.exe ``` ... and it looks like this: [alt text http://img136.imageshack.us/img136/4674/helloproblemuk5.png](http://img136.imageshack.us/img136/4674/helloproblemuk5.png) --- The second part of the message is missing. Why is this happening? The same binary - **hellowf.exe** - works fine on Windows. --- Update: This is really annoying. Here are the mono versions I have had and tried to make this work on so far: ``` 1.9.1 (from official ubuntu repo) 2.0.1 (from some some 3rd party repo) 2.2 (wiped every mono pkg and compiled myself) ``` My Current mono version: ``` mono --version Mono JIT compiler version 2.2 (tarball Wed Jan 14 22:58:21 CET 2009) Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com TLS: __thread GC: Included Boehm (with typed GC) SIGSEGV: altstack Notifications: epoll Architecture: x86 Disabled: none gmcs --version Mono C# compiler version 2.2.0.0 ``` ... any clues?
Finally I have found a workaround. This seems to be a bug in Mono related to font rendering. It happens when "**Full**" hinting is turned on. I usually have it that way. Changing it to "**Slight**" or "**Medium**" in `System->Preferences->Appearance->Fonts->Details` fixes the problem. Thanks for the help!
Works OK on opensuse 11.0, mono 2.0.1. Please, edit your question and put the mono version you are using.
C# Mono+Winforms MessageBox problem
[ "", "c#", ".net", "winforms", "mono", "" ]
Ugh ok I'm terrible at explaining things, so I'll just give you the quotes and links first: [Problem 4b](http://sqlzoo.net/3.htm) (near bottom): > 4b. List the film title and the leading actor for all of 'Julie Andrews' films. > > > movie(id, title, yr, score, votes, director) > > actor(id, name) > > casting(movieid, actorid, ord) > > *(Note: movie.id = casting.movieid, actor.id = casting.actorid)* My answer (doesn't work): `SELECT title, name       FROM casting JOIN movie               ON casting.movieid = movie.id       JOIN actor               ON casting.actorid = actor.id      WHERE name = 'Julie Andrews'        AND ord = 1` The problem here is that it wants the list of lead actors of movies with 'Julie Andrews' as an actor (who is not necessarily the lead actor), but all I'm doing with my answer is getting the movies where she is the lead (ord = 1). How do I specify the list of lead actors without 'Julie Andrews' being it? I suspect I have to do something with GROUP BY, but I can't figure out what at the moment... **Edit:** Do I need to use a nested SELECT?
There are wonderful ways of doing this with subqueries, but it appears that t this point in the tutorial you're only working with JOINs. The following is how you would do it with only JOINs: ``` SELECT movie.title, a2.name FROM actor AS a1 JOIN casting AS c1 ON (a1.id = c1.actorid) JOIN movie ON (c1.movieid = movie.id) JOIN casting AS c2 ON (movie.id = c2.movieid) JOIN actor AS a2 ON (c2.actorid = a2.id) WHERE a1.name = 'Julie Andrews' AND c2.ord = 1 ``` **EDIT (more descriptive):** This will give us a table containing all of the movies Julie Andrews acted in. I'm aliasing the actor and casting tables as a1 and c1 respectively because now that we've found a list of movies, we'll have to turn and match that against the casting table again. ``` SELECT movie.* FROM actor a1 JOIN casting c1 ON (a1.id = c1.actorid) JOIN movie ON (c1.movieid = movie.id) WHERE a1.name = 'Julie Andrews' ``` Now that we have a list of all movies she acted, we need to join that against the casting table (as c2) and that to the actor table (as a2) to get the list of leading roles for these films: ``` SELECT movie.title, -- we'll keep the movie title from our last query a2.name -- and select the actor's name (from a2, which is defined below) FROM actor a1 -- \ JOIN casting AS c1 ON (a1.id = c1.actorid) -- )- no changes here JOIN movie ON (c1.movieid = movie.id) -- / JOIN casting AS c2 ON (movie.id = c2.movieid) -- join list of JA movies to the cast JOIN actor AS a2 ON (c2.actorid = a2.id) -- join cast of JA movies to the actors WHERE a1.name = 'Julie Andrews' -- no changes AND c2.ord = 1 -- only select the star of the JA film ``` Edit: In aliasing, the 'AS' keyword is optional. I've inserted it above to help the query make more sense
You want to match movies to two potentially separate rows in the `casting` table: one row where Julie Andrews is the actor, and the second row which may or may not be Julie Andrews, but which is the lead actor for the film. > Julie <---> cast in <---> a movie <---> starring <---> Lead actor So you need to join to the `casting` table twice. ``` SELECT m.title, lead.name FROM actor AS julie JOIN casting AS c1 ON (julie.id = c1.actorid) JOIN movie AS m ON (c1.movieid = m.id) JOIN casting AS c2 ON (m.id = c2.movieid) JOIN actor AS lead ON (c2.actorid = lead.id) WHERE julie.name = 'Julie Andrews' AND c2.ord = 1; ``` Remember that "table aliases" reference potentially different rows, even if they are aliases to the same table.
How do I list the first value from a three-way joined table query?
[ "", "mysql", "sql", "mysql-5.0", "" ]
How to decide whether to choose a Replication or Mirroring in SQL Server 2005 to provide data availabilty and performance at the same time. --- To be more specific about my SQL server architecture, I have an active/active cluster of 2 nodes which are used for load balancing, and I have another server for replication, which will be used only for reporting, I want to make sure which technology best provides both availabilty and performance, Transactional replication or Database Mirroring?
It turns out that Database mirroing prevents data to be accessed directly, mirrored data are only accessable through a database snapshot, so reports from snapshot data will not be up to date so, I will use Database Transactional Replication to provide high availabilit and load balancing.
It depends on the level (hot, warm, cold) of standby availability you require. > Various mechanisms in SQL Server > provide database-level redundancy, > such as backup/restore, log shipping, > and database mirroring (in SQL Server > 2005 and later). Database mirroring is > the only mechanism that provides a > real-time, exact copy of the protected > database with the guarantee of zero > data loss (when the mirror is > synchronized). Database mirroring operates in either synchronous or asynchronous mode. Under asynchronous operation, transactions commit without waiting for the mirror server to write the log to disk, which maximizes performance. This MS Whitepaper, [Providing High Availability using Database Mirroring](http://download.microsoft.com/download/d/9/4/d948f981-926e-40fa-a026-5bfcf076d9b9/ReplicationAndDBM.docx), covers a range of scenarios. You should probably read this TechNet article, [Database Mirroring Best Practices and Performance Considerations](http://www.microsoft.com/technet/prodtechnol/sql/2005/technologies/dbm_best_pract.mspx).
Mirroring vs Replication
[ "", "sql", "sql-server-2005", "" ]
I'm trying to debug javascript code just by adding a breakpoint in VS2008, but the debugger's not stopping. Do I have to do some special setup in order to enable javascript debugging? Or does the code have to be in a separate js file?
Did you uncheck the checkboxes in the settings Tools-->Internet Options-->Advanced-->Browsing [heading]-->Uncheck "Disable Script Debugging (Internet Explorer)" and Uncheck "Disable Script Debugging (Other)" Sometimes you need to restart the browser to get VS2008 to recognize that it has made some changes. Have you tried to stick the "debugger;" keyword into your JavaScript file? This usually never fails me. If you have IE8, you can debug right in the browser itself.
Any particular browser? Mainly it works with IE, and needs script debugging enabled in the IE internet options (advanced => browsing).
Javascript Debugging in Visual Studio 2008
[ "", "javascript", "visual-studio-2008", "debugging", "" ]
I have written a program that will etablish a network connection with a remote computer using TCPClient I am using it to transfer files in 100k chunks to a remote .net application and it inturn then writes them to the HardDrive. All file transfers work good except when it comes to ZIP files - it is curious to note that the reasembled file is always 98K...is there some dark secret to ZIP files that prevent them from being handled in this manner. Again all other file transfers work fine, image, xls, txt, chm, exe etc. Confused
Well, you haven't shown any code so it's kinda tricky to say exactly what's wrong. The *usual* mistake is to assume that Stream.Read reads all the data you ask it to instead of realising that it might read less, but that the amount it *actually* read is the return value. In other words, the code shouldn't be: ``` byte[] buffer = new byte[input.Length]; input.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, buffer.Length); ``` but something like: ``` byte[] buffer = new byte[32 * 1024]; int bytesRead; while ( (bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, bytesRead); } ``` But that's just a guess. If you could post some code, we'd have a better chance of figuring it out.
The actual code would be helpful. Are you using BinaryReader / BinaryWriter? (i.e. data based rather than text based). You could try using a hex file compare (e.g. [Beyond Compare](http://www.scootersoftware.com/)) to compare the original and copy and see if that gives you any clues.
C# Reading 'Zip' files with FileStream
[ "", "c#", "zip", "filestream", "tcpclient", "" ]
One meme that gets stressed with Java development is always use ArrayList over Vector. Vector is deprecated. That may be true, but Vector and Hashtable have the advantage that they are synchronized. I am working with a heavily concurrent oriented application, wouldn't it benefit to use objects that are synchronized like Vector? It seems that they have their place?
The problem with Vector and Hashtable is that they're only locally synchronized. They won't break (as in corrupt data) in a concurrent application, however, due to the local synchronization (e.g. get is synchronized, but only until get returns), you'll be wanting to perform your own synchronization anyway for situations such as iteration over the content. Now, even your put-method needs some extra synchronization to cooperate with the iteration synchronization and you end up with a situation where your Hashtable/Vector is doubly synchronized.
[ConcurrentHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html) is [way faster](http://www.ibm.com/developerworks/java/library/j-jtp07233.html#N10244) than Hashtable. It's **concurrent**, not just synchronized. It admits multiple readers/writers at once. There is no such 'concurrent' array list though. Depending on your needs, [CopyOnWriteArrayList](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CopyOnWriteArrayList.html) may or may not be what you need.
Use Hashtable, Vector or HashMap or ArrayList in Java
[ "", "java", "vector", "" ]
Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something? ``` #include <algorithm> #include <iostream> #include <ostream> #include <vector> using namespace std; int main() { vector<int> v; for (int i = 0; i < 10; ++i) { v.push_back(i); } for_each(v.begin(), v.end(), [](int n) { cout << n << " "; }); cout << endl; } ``` Thank you in advance.
See [Stackoverflow question #146381](https://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards) Simply put: no. Visual Studio 2010 will support C++0x to some extent, but I'm unsure if that will include lambda expressions.
You can... kind of. The Visual C++ 2008 *compiler* doesn't support lambdas, but you **can** certainly use the Visual C++ 2010 *compilers* from Visual Studio 2008!! Just install Visual C++ 2010 Express, and then open Visual Studio 2008 and go to: > Tools`->`Options`->`Project and Solutions`->`VC++ Directories and then add the following entries: * For the Win32 platform, insert `$(ProgramFiles)\Microsoft Visual Studio 10.0\VC\bin` at the **beginning**, and `$(ProgramFiles)\Microsoft Visual Studio 10.0\Common7\IDE` at the **end**. * For the x64 platform, insert `$(ProgramFiles)\Microsoft Visual Studio 10.0\VC\bin\amd64` at the **beginning**. Now you can use all the VC++ 2010 features from Visual Studio 2008! :)
Lambda expressions support in VS2008 SP1
[ "", "c++", "visual-studio-2008", "lambda", "c++11", "" ]
How can I convert a `List<MyObject>` to an `IEnumerable<MyObject>` and then back again? I want to do this in order to run a series of LINQ statements on the List, e. g. `Sort()`
``` List<string> myList = new List<string>(); IEnumerable<string> myEnumerable = myList; List<string> listAgain = myEnumerable.ToList(); ```
A `List<T>` is an `IEnumerable<T>`, so actually, there's no need to 'convert' a `List<T>` to an `IEnumerable<T>`. Since a `List<T>` is an `IEnumerable<T>`, you can simply assign a `List<T>` to a variable of type `IEnumerable<T>`. The other way around, not every `IEnumerable<T>` is a `List<T>` offcourse, so then you'll have to call the `ToList()` member method of the `IEnumerable<T>`.
Freely convert between List<T> and IEnumerable<T>
[ "", "c#", "linq", "list", "ienumerable", "" ]
Are there any documents/tutorials on how to clip or cut a large image so that the user only sees a small portion of this image? Let's say the source image is 10 frames of animation, stacked end-on-end so that it's really wide. What could I do with Javascript to only display 1 arbitrary frame of animation at a time? I've looked into this "CSS Spriting" technique but I don't think I can use that here. The source image is produced dynamically from the server; I won't know the total length, or the size of each frame, until it comes back from the server. I'm hoping that I can do something like: ``` var image = getElementByID('some-id'); image.src = pathToReallyLongImage; // Any way to do this?! image.width = cellWidth; image.offset = cellWidth * imageNumber; ```
This can be done by enclosing your image in a "viewport" div. Set a width and height on the div (according to your needs), then set `position: relative` and `overflow: hidden` on it. Absolutely position your image inside of it and change the position to change which portions are displayed. To display a 30x40 section of an image starting at (10,20): ``` <style type="text/css"> div.viewport { overflow: hidden; position: relative; } img.clipped { display: block; position: absolute; } </style> <script type="text/javascript"> function setViewport(img, x, y, width, height) { img.style.left = "-" + x + "px"; img.style.top = "-" + y + "px"; if (width !== undefined) { img.parentNode.style.width = width + "px"; img.parentNode.style.height = height + "px"; } } setViewport(document.getElementsByTagName("img")[0], 10, 20, 30, 40); </script> <div class="viewport"> <img class="clipped" src="/images/clipped.png" alt="Clipped image"/> </div> ``` The common CSS properties are associated with classes so that you can have multiple viewports / clipped images on your page. The `setViewport(…)` function can be called at any time to change what part of the image is displayed.
In answer to : Alas, JavaScript simply isn't capable of extracting the properties of the image you'd require to do something like this. However, there may be salvation in the form of the HTML element combined with a bit of server-side scripting. ... ``` < ? (open php) $large_image = 'path/to/large_image'; $full_w = imagesx($large_image); $full_h = imagesy($large_image); (close php) ? > ``` **This can be done in Javascript, just google a bit :** ``` var newimage = new Image(); newimage.src = document.getElementById('background').src; var height = newimage.height; var width = newimage.width; ``` This generates a new image from an existing one and captures this way in java script the original height and width properties of the original image (not the one id'ed as background. In answer to : The width/height properties of the document's image object are read only. If you could change them, however, you would only squish the frames, not cut the frames up like you desire. The kind of image manipulation you want can not be done with client-side javascript. I suggest cutting the images up on the server, or overlay a div on the image to hide the parts you do not wish to display. ... ``` var newimage = new Image(); newimage.src = document.getElementById('background').src; var height = newimage.height; var width = newimage.width; newimage.style.height = '200px'; newimage.style.width = '200px'; newimage.height = '200px'; newimage.width = '200px'; ``` and if wanted : ``` newimage.setAttribute('height','200px'); ``` The doubled newimage.style.height and newimage.height is needed in certain circumstances in order to make sure that a IE will understand in time that the image is resized (you are going to render the thing immediately after, and the internal IE processing is too slow for that.) Thanks for the above script I altered and implemented on <http://morethanvoice.net/m1/reader13.php> (right click menu... mouseover zoom lent) correct even in IE , but as you will notice the on mousemove image processing is too fast for the old styled IE, renders the position but only once the image. In any case any good idea is welcome. Thanks to all for your attention, hope that the above codes can help someone... Claudio Klemp <http://morethanvoice.net/m1/reader13.php>
Programmatically Clip/Cut image using Javascript
[ "", "javascript", "image", "" ]
I am now debugging a program that utilizes many different threads. There is an exception that is thrown from time to time. The problem is that there is no way to know what thread caused the problem... Is there an easy way to get the stack trace after the exception is thrown? I thought about simply writing a debug messages, but it is going to be a huge :-) I guess there are much better techniques than this one ... I'm using Visual Studio 2008 - native C++ project....
Unless I'm very much mistaken, you need to know which thread triggered the exception in order to use the Visual Studio debugger's call stack view, which is obviously the catch-22 situation you're in at the moment. One thing I would try is to see if you can get the debugger to break when the exception is thrown (using Debug > Exceptions). You'll have to explicitly enable this, but if you know what type of exception is thrown, this might allow you to work out where it's thrown. Other than that, putting a breakpoint in the constructor of the exception (if it's one of your own) should also allow you to work out where it's triggered from. If those methods don't work for you I'd be looking at the debug messages as you already suggested.
This is trivially easy with [WinDBG](http://www.microsoft.com/whdc/devtools/debugging/default.mspx "Microsoft: Debugging Tools for Windows"), which is free from Microsoft. You will also want to install symbols for your version of [Windows](http://www.microsoft.com/whdc/devtools/debugging/symbolpkg.mspx#d "Microsoft: Symbol Packages for Windows"), if you don't have them already. Simply setup WinDBG as your Crash Dump tool. I use this registry setting: (*You may wish to edit the paths*) ### Sample: `CrashDumpSettings.reg`: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug] "Auto"="1" "Debugger"="C:\\progra~1\\debugg~1\\cdb.exe -p %ld -e %ld -g -y SRV*c:\\mss*http://msdl.microsoft.com/download/symbols -c \"$<c:\\Dumps\\CrashDump.cdbscript\"" ``` Here is what your `CrashDump.cdbscript` might look like: (*This is basically what I use... Edit the paths as appropriate.*) ### Sample: `CrashDump.cdbscript`: ``` .sympath+ c:\windows\symbols;c:\some\path\to\symbols\for\your\project as /c CrashFirstModule .printf "%mu", @@c++((*(ntdll!_LDR_DATA_TABLE_ENTRY**)&@$peb->Ldr->InLoadOrderModuleList.Flink)->BaseDllName.Buffer) .logopen /t c:\dumps\${CrashFirstModule}_process.log .kframes 100 !analyze -v ~*kv lmv .logclose .dump /mhi /u /b c:\dumps\${CrashFirstModule}_mini.cab .dump /mhia /u /b c:\dumps\${CrashFirstModule}_full.cab q ``` And you get a nice log file and some dumps you can use to view the state of the process when the exception happened with WinDBG. The log file will have analysis of the error that occurred, including the line of code that caused the error. It will also list the call-stack for each thread. In the call stack listing, the thread with the `#` next to it's number is the one that caused the exception. There is a TON of information in these files. I recommend picking up [Debugging Applications for Microsoft .Net and Microsoft Windows](https://rads.stackoverflow.com/amzn/click/com/0735615365 "Amazon: Debugging Applications for Microsoft .Net and Microsoft Windows") by John Robbins. It's a great book on Debugging, even if it's from a few years ago. You can get it from Amazon for about $20.00.
Get the stack trace when an exception is thrown
[ "", "c++", "visual-studio-2008", "debugging", "" ]
I'm looking for the best approach to getting an XML document from a JDBC resultset. The structure of the XML isn't awfully important, but it should be fairly speedy. For clearification, I would like the data from the resultset and only enough metadata to identify the data (field names essentially). I'm working with MySQL, DB2, SQL Server at the moment, but the solution needs to be database agnostic (for XML in SQL Server isn't a viable option).
Are you looking to convert the ResultSet table into XML? I don't know of any thirdparty tool, but tt is not very difficult to roll one of your own. Your two options are to either have a constant format: ``` <ResultSet> <MetaData> <Column name="...." type="..."/> .... <MetaData> <Data> <Row><Cell value="valueConvertedToString"/><Cell null="true"/></Row> .... </Data> </ResultSet> ``` Or metadata specific: ``` <ResultSet> <MetaData> <Column name="id" type="int"/> <Column name="color" type="string"/> .... <MetaData> <Data> <Row><id value="45"/><color null="true"/></Row> .... </Data> </ResultSet> ``` In the second case, you can't define schema statically.
By using WebRowSet, once can convert the entire ResultSet into XML. The XML generated by WebRowSet is far clear and simple, i am not sure about the speed, since it also depends upon driver implementations. Here is a good article on [WebRowSet using Oracle](http://www.jdbctutorial.net/jdbc-rowset/Jdbc-WebRowSet-Generate-XML-Oracle-tutorial.php) which will fulfill your needs, i guess.
Best Way to get XML from a JDBC resultset
[ "", "java", "xml", "jdbc", "" ]
What values should I pass to create an efficient `HashMap` / `HashMap` based structures for N items? In an `ArrayList`, the efficient number is N (N already assumes future grow). What should be the parameters for a `HashMap`? ((int)(N \* 0.75d), 0.75d)? More? Less? What is the effect of changing the load factor?
Regarding the load factor, I'll simply quote from the [HashMap javadoc](http://java.sun.com/javase/6/docs/api/java/util/HashMap.html): > As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. Meaning, the load factor should not be changed from `.75` , unless you have some specific optimization you are going to do. Initial capacity is the only thing you want to change, and set it according to your `N` value - meaning `(N / 0.75) + 1`, or something in that area. This will ensure that the table will always be large enough and no rehashing will occur.
I ran some [unit tests](http://blog.scottlogic.com/2012/08/14/efficient-map-initialization-in-java.html) to see if these answers were correct and it turned out that using: ``` (int) Math.ceil(requiredCapacity / loadFactor); ``` as the initial capacity gives what you want for either a `HashMap` or a `Hashtable`. By "what you want" I mean that adding `requiredCapacity` elements to the map won't cause the array which it's wrapping to resize and the array won't be larger than required. Since the default load capacity is 0.75, initializing a HashMap like so works: ``` ... = new HashMap<KeyType, ValueType>((int) Math.ceil(requiredCapacity / 0.75)); ``` Since a HashSet is effectively just a wrapper for a HashMap, the same logic also applies there, i.e. you can construct a HashSet efficiently like this: ``` .... = new HashSet<TypeToStore>((int) Math.ceil(requiredCapacity / 0.75)); ``` @Yuval Adam's answer is correct for all cases except where `(requiredCapacity / 0.75)` is a power of 2, in which case it allocates too much memory. @NotEdible's answer uses too much memory in many cases, as the HashMap's constructor itself deals with the issues that it want the maps array to have a size which is a power of 2.
HashMap initialization parameters (load / initialcapacity)
[ "", "java", "collections", "hashmap", "" ]
I am now designing an SNMP library. The problem is caused by a special function like this, \*\*\* GetTable(string id) This function may return Variable[,] which is a two dimensional array sometimes, but also Variable[,,] and arrays with more dimensions. So I believe it is not reasonable to return fixed array such as Variable[,], Variable[,,] and so on. But what should this method return then? How to design it? What about a custom VariableCollection? Any suggestion is welcome.
As a general rule, returning a custom type allows for greater flexibility in the representation of your data. I'd also favour providing your own methods for accessing the data in this collection, rather than exposing multidimensional arrays. I generally avoid using multidimensional rectangular arrays myself. In many cases, multidimensional jagged arrays are more convenient as you can lift a slice out in isolation.
Well, you could return `Array` and let the caller check the `.Rank`? Of course, returning an array may not be the best option in the first place (depending on the scenario): [Arrays considered somewhat harmful](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx)
How to design this method if it returns multi-dimensional arrays?
[ "", "c#", ".net", "arrays", "methods", "multidimensional-array", "" ]
I'm new to unit testing using nunit (and Java development in general). When creating unit tests for private methods on classes, it looks as though the test file must be in the same package as the class being tested. What is the typical way of avoiding exporting the APIs of the unit tests? Can I make the classes/test methods package-protected? Or do developers typically have a separate build for release that excludes unit test files?
The test file does not necessarily have to be in the same package as the class being tested. In fact, it is a good practice to have the test files in a completely separate package, allowing them to test the public API without being concerned with package-level implementation details. Alternately, you can set up your build script (e.g. Nant) to ignore files containing "Test" when you build your release executable.
I can tell IntelliJ or Ant not to package JUnit tests in the deployment. I have tests in a separate directory from the source code, which is what makes it possible. Don't mingle source and test classes together. Keep them separate to make it easier for the tool/script you use to deploy.
Creating nunit tests without exporting them with the api
[ "", "java", "unit-testing", "tdd", "nunit", "" ]
I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this? Thank you
It is possible but it might not be the best thing to do. Unit tests aren't really suitable for testing concurrency behaviour, unfortunately there aren't many test-methods that are suitable. NUnit doesnt do anything with threads. You could write tests that start several threads and then test their interaction. But these would start to look more like integration tests than unit tests. Another problem is that deadlock behaviour usually depends on the order threads are scheduled in. So it would be hard to write a conclusive test to test a certain deadlock issue because you don't have any control over the thread scheduling, this is done by the OS. You could end up with tests that sometimes fail on multicore processors but always succeed on single core processors.
Well its certainly possible to test for a deadlock by running your code on another thread and seeing if it returns in a timely fashion. Here's some (very basic) example code: ``` [TestFixture] public class DeadlockTests { [Test] public void TestForDeadlock() { Thread thread = new Thread(ThreadFunction); thread.Start(); if (!thread.Join(5000)) { Assert.Fail("Deadlock detected"); } } private void ThreadFunction() { // do something that causes a deadlock here Thread.Sleep(10000); } } ``` I wouldn't like to say that this is the "best way", but it is one I have found useful on occasions.
Testing for a deadlock with nUnit
[ "", "c#", "unit-testing", "nunit", "deadlock", "" ]
I have some special cells in my Excel workbooks which are managed by my Excel Add-in. I want to prevent users from changing content of those cells, but I also want to know, what value users wanted to enter to those cells. On the SheetChange event I can check what users entered to my special cells, but how do I determine the PREVIOUS value in those cells and REVERT user changes? --- It is not a solution for me. If I lock cell in Excel, it becomes read-only - user can not even try to enter anything to this cell - Excel popups warning dialog in this case. My problem is that I want to catch what user entered to my cell, do something with this value, and then revert cell content to original value.
How about something like this, which is in VBA, but should be fairly easy to translate to C# ``` Option Explicit ' We are monitoring cell B2... Private initialB2Value As Variant ' holds the value for reinstatement when the user changes it Private Sub Worksheet_Activate() ' record the value before the user makes any changes. ' Could be a constant value, or you could use .Formula to ensure a calculation is not lost initialB2Value = Range("B2").Value End Sub Private Sub Worksheet_Change(ByVal Target As Range) Static alreadyChanging As Boolean ' when we reset the cell, Worksheet_Change will fire again, so we'll use a flag ' to tell us if we should care or not... If alreadyChanging Then ' change is because of this code, no need to process alreadyChanging = False Exit Sub End If If IsEmpty(Intersect(Target, Range("B2"))) Then ' If the change is not happening to the range we are monitoring, ignore it Exit Sub End If ' Do something with the user's input here Debug.Print "User input " & Range("B2").Value & " into B2" ' before we reset the value, flag that we are changing the value in code alreadyChanging = True ' now apply the old value Range("B2").Value = initialB2Value End Sub ```
Perhaps it would suit to capture the value on entering the cell: ``` Option Explicit Dim LastText As String Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, _ ByVal Target As Excel.Range) LastText = Target.Value End Sub Private Sub Workbook_SheetChange(ByVal Sh As Object, _ ByVal Source As Range) Debug.Print LastText; Source End Sub ```
How can I determine new & previous cell value on SheetChange event in Excel?
[ "", "c#", "excel", "vsto", "" ]
A program written in Visual C/C++ 2005/2008 might not compile with another compiler such as GNU C/C++ or vice-versa. For example when trying to reuse code, which uses windows.h, written for a particular compiler with another, what are the differences to be aware of? Is there any information about how to produce code which is compatible with either one compiler or another e.g. with either GC/C++ or MSVC/C++? What problems will attempting to do this cause? What about other compilers, such as LCC and Digital Mars?
The first thing to do when trying to compile code written for MSVC to other compilers is to compile it with Microsoft-extensions switched off. (Use the /Za flag, I think). That will smoke out lots of things which GCC and other compilers will complain about. The next step is to make sure that Windows-specific APIs (MFC, Win32, etc.) are isolated in Windows-specific files, effectively partioning your code into "generic" and "windows-specific" modules.
Remember the argument that if you want your web page to work on different browsers, then you should write standards-compliant HTML? Same goes for compilers. At the language level, if your code compiles without warnings on GCC with -std=c89 (or -std=c++98 for C++), -pedantic -Wall, plus -Wextra if you're feeling brave, and as long as you haven't used any of the more blatant GNU extensions permitted by -pedantic (which are hard to do accidentally) then it has a good chance of working on most C89 compilers. C++ is a bit less certain, as you're potentially relying on how complete the target compiler's support is for the standard. Writing correct C89 is somewhat restrictive (no // comments, declarations must precede statements in a block, no inline keyword, no stdint.h and hence no 64bit types, etc), but it's not too bad once you get used to it. If all you care about is GCC and MSVC, you can switch on some language features you know MSVC has. Otherwise you can write little "language abstraction" headers of your own. For instance, one which defines "inline" as "inline" on GCC and MSVC/C++, but "\_\_inline" for MSVC/C. Or a MSVC stdint.h is easy enough to find or write. I've written portable code successfully in the past - I was working mostly on one platform for a particular product, using GCC. I also wrote code that was for use on all platforms, including Windows XP and Mobile. I never compiled it for those platforms prior to running a "test build" on the build server, and I very rarely had any problems. I think I might have written bad code that triggered the 64bit compatibility warning once or twice. The Windows programmers going the other way caused the occasional problem, mostly because their compiler was less pedantic than ours, so we saw warnings they didn't, rather than things that GCC didn't support at all. But fixing the warnings meant that when the code was later used on systems with more primitive compilers, it still worked. At the library level, it's much more difficult. If you #include and use Windows APIs via windows.h, then obviously it's not going to work on linux, and the same if you use KDE with GCC and then try to compile with MSVC. Strictly speaking that's a platform issue, not a compiler issue, but it amounts to the same thing. If you want to write portable code, you need an OS abstraction API, like POSIX (or a subset thereof) that all your targets support, and you need to be thinking "portable" when you write it in the first place. Taking code which makes heavy use of windows-specific APIs, and trying to get it to work on GCC/linux, is basically a complete rewrite AFIAK. You might be better off with WINE than trying to re-compile it.
What are the practical differences between C compilers on Windows?
[ "", "c++", "c", "winapi", "cross-platform", "" ]
I'm trying to decide whether it is better to use static methods for loading/saving objects, or use constructor/instance methods instead. So, say for object `Project`, the instance version would be ``` public Project(path) { // Load project here } public void Save(path) { // Save project here } ``` And the static version would be ``` public static Project Load(path) { // Load project and return result } public static void Save(path, proj) { // Save project } ``` So, which do you prefer?
Neither. Favor extracting persistence logic from your domain model and into a separate layer of classes. (from a comment left in ChrisW's answer) Regarding the details of the domain object leaking into another class: you can restrict the visibility of those details, if your language permits, by using package-privacy/internal access. Alternatively, you can use a DTO approach.
If there is no state to be maintained, only behavior, then use the static approach. However, if the Project object needs to have state, then the constructor/instance method should be used.
Constructors or Static Methods for Loading and Saving Objects?
[ "", "c#", ".net", "design-patterns", "architecture", "" ]
I'm currently writing a C#-class in my ASP.NET (3.5) application to handle all database-queries. Some of the methods are there to make a select-query to the database. Inside the method i simply have a `SqlDataReader r = command.ExecuteReader();` to fetch the data. I now want `r` to be returned by the method, but when i close the database-connection, the datareader closes and the object contains nothing anymore. Thought of putting everything into a string-array, but this is unpractical if i have mixed integer and text-fields in my database. Is there an easy ("premade") way of storing the data in some object to return?
You can use a datatable and SqlDataAdapter: ``` using(SqlDataAdapter adap = new SqlDataAdapter(cmd)) { adap.fill(myDataTable); } return myDataTable; ```
Typically, the results are either stuffed into a collection or a datatable. Datatables are a little easier from the perspective of not having to instantiate objects and storing them.
Storing an SqlDataReader-object in C#/ASP.NET?
[ "", "c#", "asp.net", "database", "class", "sqldatareader", "" ]
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen. Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this? ``` function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function if(typeof(thisShouldBeAString) === 'string') { throw('foo(var), var should be of type string'); } #yadayada } ``` I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' \* 1 = 234) and this could make my methods do very weird things. **EDIT** To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?
Some small remarks on type checking - it's actually not that complicated: Use `typeof` to check for primitives and `instanceof` to check for specific object types. Example: Check for strings with ``` typeof x === 'string' ``` or ``` typeof x === 'string' || x instanceof String ``` if you want to include string objects. To check for arrays, just use ``` x instanceof Array ``` This should work reasonably well (there are a few known exceptions - eg Firefox 3.0.5 has a bug where `window instanceof Object === false` although `window.__proto__ instanceof Object === true`). **edit:** There are some further problems with detection of function objects: In principle, you could both use `typeof func === 'function'` and `func instanceof Function`. The catch is that in an unnamed browser from a big corporation these checks return the wrong results for some predefined functions (their type is given as `'object'`). I know of no workaround for this - the checks only work reliably for user-defined functions... **edit2:** There are also problems with objects passed from other windows/frames, as they will inherit from different global objects - ie `instanceof` will fail. Workarounds for built-in objects exists: For example, you can check for arrays via `Object.prototype.toString.call(x) === '[object Array]'`.
The problem with type checking is that its actually quite hard to do. For example:- ``` var s = new String("Hello World!"); alert(typeof s); ``` What gets alerted? Ans: "object". Its true its a daft way to initialise a string but I see it quite often none-the-less. I prefer to attempt conversions where necessary or just do nothing. Having said that in a Javascript environment in which I have total control (which is ***not*** true if you are simply providing a library) I use this set of prototype tweaks:- ``` String.prototype.isString = true; Number.prototype.isNumber = true; Boolean.prototype.isBoolean = true; Date.prototype.isDate = true; Array.prototype.isArray = true; ``` Hence testing for the common types can be as simple as:- ``` if (x.isString) ``` although you still need to watch out for null/undefined:- ``` if (x != null && x.isString) ``` In addition to avoiding the `new String("thing")` gotcha, this approach particularly comes into its own on Dates and Arrays.
What is the best way to tell users of my library functions that passed variables are not of the correct type
[ "", "javascript", "typechecking", "" ]
Is there a way for a Java GUI application to respond to system shutdown or logoff events, other than to use JNI? (On Windows, the JNI would use WM\_QUERYENDSESSION, on Linux?) The method should allow the program to prompt users to save, etc., and then continue the logoff process.
As far as I know, there's no way in Java to catch the system shutdown or logoff events. You can, however, catch when the JVM is terminating by [adding a shutdown hook](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). AWT's [WindowAdapter](http://java.sun.com/javase/6/docs/api/java/awt/event/WindowAdapter.html) also has a windowClosing event that you can override and hook to a window that you want to monitor. Swing inherits this; I believe SWT does as well. Be aware that you MUST manually dispose of the window if you override this event! I believe that MS Windows will fire these events as it is closing. I believe a SIGTERM on Linux/UNIX does the same, although Linux will SIGKILL an app shortly afterwords if this is during shutdown.
I think that Runtime.getRuntime().addShutdownHook should provide the functionality you need.
Java: Handle logoff or shutdown on Windows and Linux
[ "", "java", "windows", "linux", "swing", "" ]
I've decided I want to get more into native code development with C++. I'm trying to decide if I would be better served using CodeGear C++ Builder 2009 or Visual Studio 2008. I currently use Delphi 2007, so I'm very comfortable with C++ Builder's IDE (its the same as Delphi), as well as the VCL and RTL. I've never been a big fan of MFC (from the first time I played around with it in the VS 6.0 days), but haven't taken a close look at it since then. I'm interested in hearing from some experts that have experience with both IDE's, whether they are the most recent versions or not. Right now, I'm leaning towards C++ Builder because I believe the VCL is much more robust and easier to work with than MFC --- but as I said, it's been a while since I've used MFC. I'm not interested in building programs that rely on the .NET Framework because I'm partly teaching myself native development. Is MFC still king for Windows C++? Or is WTL or ATL the big thing? Any C++ gurus out there want to share their opinions? **EDIT**: I understand MFC is not the only gui toolkit for Visual Studio. However, I'm looking for some recommendations based on GUI toolkit + IDE. For C++ Builder, there is only 1 real option, which is C++ Builder + the VCL. For VS 2008, it's VS + MFC/ATL/WTL/QT....confusing for me since I don't know much about them.
Coming from Delphi, you'll find the VCL straightforward to use with C++ Builder. There are a few oddities, like C++ doesn't hide the fact that TObjects are all really pointers (which Delphi hides from you), and some things like array properties are accessed differently. Two or three years back, I was looking for any way out of C++Builder, but now, with recent releases (and Embarcadero's purchase of Codegear), I'm happy with the product and the direction. You'll find the number of string types and the assorted potential incompatibilities quite painful with C++Builder, but you'll get used to it! (std::string, char[], wchar\_t[], TCHAR, AnsiString, WideString, UnicodeString and String to name a few) Personally I'd vote for C++ Builder - because of two-way RAD and the VCL, although it may not be the best way of learning modern C++ idioms.
Visual Studio and MFC are not the same. I use Studio all the time and I avoid MFC like the plague. You can use WTL, ATL, Win32 or any number of libraries to create apps without MFC.
C++ Builder or Visual Studio for native C++ development?
[ "", "c++", "visual-studio", "c++builder", "" ]
There are three tables, Students, Classes, Student\_Class Is it possible to select students who are not registered in any classes without using NOT IN? e.g. Select studentname from Students Where studentid NOT IN (Select Distinct studentid From Student\_Class)
There are three methods: 1. `SELECT StudentName FROM Students WHERE StudentID NOT IN (SELECT StudentID FROM StudentClass)`; 2. `SELECT StudentName FROM Students s WHERE NOT EXISTS (SELECT StudentID FROM StudentClass WHERE StudentID = s.StudentID)`; and 3. `SELECT StudentName FROM Students s LEFT OUTER JOIN StudentClass sc ON s.StudentID = sc.StudentID WHERE sc.StudentID IS NULL)`. And I really wouldn't use (3). So pick one. `WHERE EXISTS`/`WHERE NOT EXISTS` is often preferred to `IN`/`NOT IN`. Modern optimizers will probably optimize (1) and (2) to being the same a lot of the time. It's worth comparing performance (when it matters).
I really don't know why you don't want to use NOT IN, but here's one other option... ``` SELECT Studentname FROM Students LEFT JOIN Student_Class ON Student_Class.StudentID = Student.ID WHERE Student_Class.StudentID IS NULL ```
Selecting records from a many-to-many design
[ "", "sql", "t-sql", "" ]
What is the best way to handle several different onload scripts spread across many pages? For example, I have 50 different pages, and on each page I want to set a different button click handler when the dom is ready. Is it best to set onclicks like this on each individual page, ``` <a id="link1" href="#" onclick="myFunc()" /> ``` Or a very long document ready function in an external js file, ``` Element.observe(window, 'load', function() { if ($('link1')) { // set click handler } if ($('link2')) { // set click hanlder } ... } ``` Or split each `if ($('link')) {}` section into script tags and place them on appropriate pages, Or lastly, split each `if ($('link')) {}` section into its own separate js file and load appropriately per page? Solution 1 seems like the least elegant and is relatively obtrusive, solution 2 will lead to a very lengthy load function, solution 3 is less obtrusive then 1 but still not great, and solution 4 will load require the user to download a separate js file per page he visits. Are any of these best (or worst) or is there a solution 5 I'm not thinking of? *Edit: I am asking about the design pattern, not which onload function is the proper one to use.*
Have you thought about making a class for each type of behavior you'd like to attach to an element? That way you could reuse functionality between pages, just in case there was overlap. For example, let's say that on some of the pages you want to a have button that pops up some extra information on the page. Your html could look like this: ``` <a href="#" class="more-info">More info</a> ``` And your JavaScript could look like this: ``` jQuery(".more-info").click(function() { ... }); ``` If you stuck to some kind of convention, you could also add multiple classes to a link and have it do a few different things if you needed (since jQuery will let you stack event handlers on an element). Basically, you're focusing on the behaviors for each type of element you're attaching JavaScript to, rather than picking out specific ids of elements to attach functionality to. I'd also suggest putting all of the JavaScript into one common file or a limited number of common files. The main reason being that, after the first page load, the JavaScript would be cached and won't need to load on each page. Another reason is that it would encourage you do develop common behaviors for buttons that are available throughout the site. In any case, I would discourage attaching the onlick directly in the html (option #1). It's obtrusive and limits the flexibility you have with your JavaScript. Edit: I didn't realize Diodeus had posted a very similar answer (which I agree with).
I would use [JQuery's](http://docs.jquery.com/How_jQuery_Works) *document ready* if possible ``` $(document).ready(function() { // jQuery goodness here. }); ```
Best Practices for onload Javascript
[ "", "javascript", "onload", "" ]
### Question --- I'm trying to build a quick and easy ASP.NET page that redirects a user to a new URL using a meta redirect. Only trouble is that I need to also pass along the GET values of the current request. I've found a way to do this programatically in the code behind using the HtmlMeta object. However, I'd like to avoid using the code behind and just put this code directly into the ASPX page. Here is what I have so far: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <meta http-equiv="refresh" content='10;url=http://contact.test.net/main.aspx?<%=Request.QueryString.ToString()%>' /> </head> </html> ``` However, this spits out the following meta tag: ``` <meta http-equiv="refresh" content="10;url=http://contact.test.net/main.aspx?<%=Request.QueryString.ToString()%>" /> ``` So is there any way to escape the attribute so the ASP.NET code actually executes? ### Solution 1 --- For the time being, I have fixed my problem by removing the quotes from the HTML attribute. Thus making the meta tag the following: ``` <meta http-equiv="refresh" content=10;url=http://contact.test.net/main.aspx?<%=Request.QueryString.ToString()%> /> ``` Although this fixes the issue, I'd be curious if anyone knows of a more correct way to do it where I could escape the literal quotes of the HTML attribute. ### Solution 2 (Final Chosen Solution) --- Per the much appreciated advise of Scott, I decided to go ahead and do this from the code behind. For anyone who is curious how this was implemented: ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim nRef As String = Request.QueryString("n") Dim sRef As String = Request.QueryString("s") Dim contentAttrBuilder As New StringBuilder("0;http://contact.cableone.net/main.aspx") contentAttrBuilder.Append("?n=") contentAttrBuilder.Append(nRef) contentAttrBuilder.Append("&s=") contentAttrBuilder.Append(sRef) Dim metaRedirect As New HtmlMeta() metaRedirect.HttpEquiv = "refresh" metaRedirect.Content = contentAttrBuilder.ToString() Me.Header.Controls.Add(metaRedirect) End Sub ``` Thanks, Chris
Maybe this code inside the head tag will be what you need: ``` <%= string.Format("<meta http-equiv='refresh' content='10;url=http://contact.test.net/main.aspx?{0}' />", Request.QueryString.ToString()) %> ``` **However**, I wouldn't advise you to do it this way. For example, this URL: ``` http:/mysite.with.metaredirect?<script>alert('hello!!!')</script> ``` will throw an exception in asp.net if you haven't disabled its security features, and you never know if someone (or even yourself) will turn those off for some other reason. A code-behind *massage* of the querystring is **strongly** advised!
Have you tried adding the whole meta tag programmatically? Once you get the to run server-side, add your new tag dynamically on Page\_Load() and you can specify all its attributes. The process is well described here: <http://www.howtoadvice.com/SetMetaTags>
Edit HTML Meta Tag w/ ASP.NET
[ "", "c#", "asp.net", "html", "" ]
Since I received no positives answers to my [last](https://stackoverflow.com/questions/285237/does-a-javascriptable-ftp-upload-javaflash-applet-exist) question. I will try to write a Java FTP upload applet myself. My question is: "Can you recommend a Java FTP client library for me to use?" I want it to be: * stable * able to handle passive and active modes * able to provide upload progress information * throw catchable exceptions if something went wrong (especially when an upload does not succeed) * cheap/free to use, preferably open source I found [this](http://www.javaworld.com/javaworld/jw-04-2003/jw-0404-ftp.html) [overview](http://www.javaworld.com/javaworld/jw-04-2003/ftp/jw-0404-ftptable.html) of some libraries, but since this article is from 2003, maybe some new developments have happened :)
Check out Apache [commons-net](http://commons.apache.org/net/), which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!
ftp4j is the best one, both for features and license: <http://www.sauronsoftware.it/projects/ftp4j/>
What Java FTP client library should I use?
[ "", "java", "ftp", "client", "" ]