Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
After some find and replace refactoring I ended up with this gem: ``` const class A { }; ``` What does "const class" mean? It seems to compile ok.
> What does "const class" mean? It seems to compile ok. Not for me it doesn't. I think your compiler's just being polite and ignoring it. **Edit:** Yep, VC++ silently ignores the const, GCC complains.
The `const` is meaningless in that example, and your compiler should give you an error, but if you use it to declare variables of that class between the closing `}` and the `;`, then that defines those instances as `const`, e.g.: ``` const class A { public: int x, y; } anInstance = {3, 4}; // The above is equiva...
What does "const class" mean?
[ "", "c++", "class", "constants", "" ]
Is there any meaningful distinction between: ``` class A(object): foo = 5 # some default value ``` vs. ``` class B(object): def __init__(self, foo=5): self.foo = foo ``` If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you...
There is a significant *semantic* difference (beyond performance considerations): * **when the attribute is defined on the instance** (which is what we usually do), there can be multiple objects referred to. **Each gets a totally separate version of that attribute**. * **when the attribute is defined on the class**, t...
The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance. If coming from C++, attributes on the class are more like static member variables.
What is the difference between class and instance attributes?
[ "", "python", "attributes", "member-variables", "" ]
I'm working on a project where we're doing a lot of remote object transfer between a Java service and clients written in other various languages. Given our current constraints I've decided to see what it would take to generate code based on an existing Java class. Basically I need to take a `.class` file (or a collecti...
I've used BCEL and find it really quite awkward. [ASM](http://asm.objectweb.org/) is much better. It very extensively uses visitors (which can be a little confusing) and does not create an object model. Not creating an object model turns out to be a bonus, as any model you do want to create is unlikely to look like a l...
From your description, it sounds like [simple reflection](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html) would suffice. You can discover all of the static structure of the class, as well as accessing the fields of a particular instance. I would only move on to BCEL if you are trying to translate method ...
Programmatically inspect .class files
[ "", "java", "bytecode", "decompiling", "" ]
Is there a way to compile multiple java source directories in a single maven project?
You can add a new source directory with build-helper: ``` <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.2.0</version> <executions> <execution> ...
I naively do it this way : ``` <build> <finalName>osmwse</finalName> <sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory> </build> ```
Maven compile with multiple src directories
[ "", "java", "maven-2", "" ]
I'm all for language diversity, but Objective C is insane. So I'm curious: is it possible to code iPhone apps with C++ while using the Cocoa API, etc?
Short answer, yes, sort of. You can use Objective-C++, which you can read about at [Apple Developer Connection.](http://web.archive.org/web/20101203170217/http://developer.apple.com/library/mac/#/web/20101204020949/http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCPlusPlus.htm...
Although Objective-C does indeed appear to be "insane" initially, I encourage you to stick with it. Once you have an "a-ha" moment, suddenly it all starts to make sense. For me it took about 2 weeks of focused Objective-C concentration to really understand the Cocoa frameworks, the language, and how it all fits togethe...
Is it possible to program iPhone in C++
[ "", "c++", "iphone", "objective-c", "" ]
We are moving our database server to a bigger box. I have several databases with full text indexes. What is the best way to move the full text indexes?
I find backup and restore is the only reliable way to move databases. The FTS should move with it when you do that. Detaching and reattaching databases never really sits well with me.
My first attempt was to copy over the database files and reattach them. I ran into the following error when attempting to access the catalog: **Full-text catalog '*database name*' is in an unstable state. Drop and re-create this full-text catalog. (Microsoft SQL Server, Error: 7624** My second and **Successful** atte...
Move/copy SQL Server 2005 full text index
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have a very painful library which, at the moment, is accepting a C# string as a way to get arrays of data; apparently, this makes marshalling for pinvokes easier. So how do I make a ushort array into a string by bytes? I've tried: ``` int i; String theOutData = ""; ushort[] theImageData = inImageData.DataArray; //...
P/Invoke can actually handle what you're after most of the time using StringBuilder to create writable buffers, for example see [pinvoke.net on GetWindowText and related functions](http://www.pinvoke.net/search.aspx?search=GetWindowText). However, that aside, with data as ushort, I assume that it is encoded in UTF-16L...
One thing you can do is switch from using a string to a stringBuilder it will help performance tremendously. If you are willing to use unsafe code you can use pointers and implement the your c# code just like your c++. Or you could write a small c++\cli dll that implements this functionality.
C# ushort[] to string conversion; is this possible?
[ "", "c#", "string", "ushort", "" ]
I am using VC++. Is `assert(false)` ignored in release mode?
If compiling in release mode includes defining NDEBUG, then yes. See [assert (CRT)](https://msdn.microsoft.com/library/9sb57dw4.aspx)
IIRC, assert(x) is a macro that evaluates to nothing when NDEBUG is defined, which is the standard for Release builds in Visual Studio.
Is assert(false) ignored in release mode?
[ "", "c++", "visual-c++", "posix", "assert", "" ]
What is the string concatenation operator in Oracle SQL? Are there any "interesting" features I should be careful of? (This seems obvious, but I couldn't find a previous question asking it).
It is `||`, for example: ``` select 'Mr ' || ename from emp; ``` The only "interesting" feature I can think of is that `'x' || null` returns `'x'`, not `null` as you might perhaps expect.
There's also concat, but it doesn't get used much ``` select concat('a','b') from dual; ```
What is the string concatenation operator in Oracle?
[ "", "sql", "oracle", "plsql", "string-concatenation", "" ]
I have a form with a textbox and a button. IE is the only browser that will not submit the form when Enter is pressed (works in FF, Opera, Safari, Chrome, etc.). I found this javascript function to try to coax IE into behaving; but no avail: ``` function checkEnter(e){ var characterCode if (e && e.which) { ...
The other thing I have done in the past is wrap the form area in a Panel and set the DefaultButton attribute to the submit button you have. This effectively maps the enter key to the submission as long as you have a form element in focus in the panel area.
Just create a text input in a hidden div on the page. This will circumvent the IE bug. Example div: ``` <!-- Fix for IE bug (One text input and submit, disables submit on pressing "Enter") --> <div style="display:none"> <input type="text" name="hiddenText"/> </div> ```
Enter button does not submit form (IE ONLY) ASP.NET
[ "", "asp.net", "javascript", "internet-explorer", "textbox", "" ]
I'm working with an existing XML document which has a structure (in part) like so: ``` <Group> <Entry> <Name> Bob </Name> <ID> 1 </ID> </Entry> <Entry> <Name> Larry </Name> </Entry> </Group> ``` I'm using LINQ to XML to query the XDocument to retrieve all these entries as follo...
[XElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) actually has [interesting explicit conversion operators](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.op_explicit.aspx) that do the right thing in this case. So, you rarely actually need to access the `.Value` propert...
In a similar situation I used an extension method: ``` public static string OptionalElement(this XElement actionElement, string elementName) { var element = actionElement.Element(elementName); return (element != null) ? element.Value : null; } ``` usage: ``` id = g.OptionalElement("ID...
LINQ to XML optional element query
[ "", "c#", "linq", "linq-to-xml", "anonymous-types", "" ]
How should I show users which fields are compulsory in a windows forms application. I have considered changing the label color or maybe the background color of the text box. I use an error provider to show a red exclamation mark next to the field, however this is only visible after they have clicked the save button.
* Asterisk or icon to the side of control * Red border when required validation fails (when user tries to save) * Bold Labels * Different background color for required controls (perhaps only when user tries to save)
Use the errorprovider extension control. This places a red cross next to the control with a tooltip message.
How to show compulsory fields on a windows form
[ "", "c#", ".net", "windows", "winforms", "" ]
I want to use google chrome as a control. I think Enso does this because they have a dir in their folder called chrome... Maybe there is a google chrome toolkit, SDK
Lots of apps have folders named Chrome. The terms refers to the decorations and arrangments used for all the different GUI widgets.
google chrome is an application, not a window or a directX which you can create as a control. You can however as someone already mention host a WebKit control. You can do that quite easily using QT which has a WebKit widget. a folder called "chrome" can mean any number of things. "chrome" is a general term for the ...
How can I open a google chome window (only the page) using c#
[ "", "c#", "" ]
I realize that this would be COMPLETELY bad practice in normal situations, but this is just for a test app that needs to be taking input from a bar code scanner (emulating a keyboard). The problem is that I need to start up some scripts while scanning, so I need the window to regain focus directly after I click the scr...
## Visibility Make the window a "Top-Most" window. This is the way the Task-Manager can remain on top of other windows. This is a property of a `Form` and you make the form top-most (floating above other windows) by setting the value to **`true`**. You shouldn't need to override any of the "Active window" behaviour w...
I struggled with a similar problem for quite a while. After much experimentation and guessing, this is how I solved it: ``` // Get the window to the front. this.TopMost = true; this.TopMost = false; // 'Steal' the focus. this.Activate(); ```
Keep window on top and steal focus in WinForms
[ "", "c#", ".net", "winforms", "" ]
I'm having trouble with something that I thought would be easy... I can't get my NotifyIcon to show a balloon tip. The basic code is: ``` public void ShowSystrayBubble(string msg, int ms) { sysTrayIcon.Visible = true; sysTrayIcon.ShowBalloonTip(20, "Title", "Text", ToolTipIcon.None); } ``` Nothing happens when I ...
I had foiled myself... This turned out to be an issue at the OS level. I had previously disabled all balloons via the registry a few weeks ago. You can read the information here on how to disable balloon tips in WinXP: <http://support.microsoft.com/kb/307729> To enable them, just set the registry value to 1 instead a...
You should then log the messages for users who have disabled the balloons be able to go review them in case of need. If you can get permissions to read the registry, you could check the value and act accordingly (not to modify the value, but to log or to show the balloon).
Balloon not showing up with NotifyIcon.ShowBalloonTip
[ "", "c#", ".net", "notifyicon", "systray", "" ]
I'm trying to write an iterator for results from a PDO statement but I can't find any way of rewinding to the first row. I would like to avoid the overhead of calling fetchAll and storing all the result data. ``` // first loop works fine foreach($statement as $result) { // do something with result } // but subseq...
I'm pretty sure this is database dependent. Because of that, it is something you should try to avoid. However, I think you can achieve what you want by enabling [buffered queries](http://www.php.net/pdo-mysql#pdo-mysql.constants). If that doesn't work, you can always pull the result into an array with [`fetchAll`](http...
This little class I wrote wraps a PDOStatement. It only stores the data that is fetched. If this doesn't work, you could move the cache to read and write to a file. ``` // Wrap a PDOStatement to iterate through all result rows. Uses a // local cache to allow rewinding. class PDOStatementIterator implements Iterator {...
Is it possible to rewind a PDO result?
[ "", "php", "iterator", "pdo", "" ]
How to implement CEditListCtrl?. List control with edit capabality (Report/Grid view). I have a list view in Report View. It has some values. I need to extend this to edit the values present in the list view. I declared a class which inherits from CListCtrl. And I have handled the two Window messages to start and end t...
Thanks for all answers I have done it easily. 1. I have handled the WM\_LBUTTONDOWN. This handler pops up the edit box to get the new value for the field 2. Handled LVN\_ENDLABELEDIT to know the end of update. 3. After receiving the above message, updated the values. “One thing I forgotten was to set the flag in ...
There are some neat grid controls on Code Project which might help: <http://www.codeproject.com/KB/miscctrl/gridctrl.aspx> <http://www.codeproject.com/KB/library/gridprojects.aspx> <http://www.codeproject.com/KB/MFC/UltimateGrid.aspx>
How to implement CEditListCtrl
[ "", "c++", "visual-c++", "mfc", "" ]
I am extending a class defined in a library which I cannot change: ``` public class Parent { public void init(Map properties) { ... } } ``` If I am defining a class 'Child' that extends Parent and I am using Java 6 with generics, what is the best way to override the init method without getting unchecked warnings?...
Yes, you have to declare the overriding method with the same signature as in the parent class, without adding any generics info. I think your best bet is to add the `@SuppressWarnings("unchecked")` annotation to the raw-type parameter, not the method, so you won't squelch other generics warnings you might have in your...
Short answer: no way to do that. Unsatisfying answer: disable the (specific) warnings in your IDE/build.xml. If you cannot change the library, alas, you have to stick with non-generic methods. The problem is that, despite after type erasure both init() have the same signature, they may in fact be different methods -...
Can unchecked warnings be avoided when overriding a method with raw type parameters?
[ "", "java", "generics", "suppress-warnings", "raw-types", "" ]
I took the plunge this afternoon and began studying LINQ, so far just mucking around with LINQ on collections. One of the first things I tried was to implement QSort. Now -- ignoring the fact that I *could* just use an ORDERBY and that this is a very silly qsort implementation -- what I came up with was this: ``` pub...
Just change the type of the parameter to `IEnumerable` and use the `var` construct instead of your `List<int>` for your local variables. This will make your `QSLinq` method better because it will accept more types of parameters, for example `int[]`, as well as `List<int>`. See the new method: ``` public static I...
Fun Question! This doesn't outperform OrderBy, but it does limit the repeated enumerations some. ``` public static IEnumerable<int> QSort2(IEnumerable<int> source) { if (!source.Any()) return source; int first = source.First(); return source .GroupBy(i => i.Compa...
Learning LINQ: QuickSort
[ "", "c#", ".net", "linq", "" ]
Using C or C++, After I decrypt a file to disk- how can I guarantee it is deleted if the application crashes or the system powers off and can't clean it up properly? Using C or C++, on Windows and Linux?
Don't write the file decrypted to disk at all. If the system is powerd off the file is still on disk, the disk and therefore the file can be accessed. Exception would be the use of an encrypted file system, but this is out of control of your program.
Unfortunately, there's no 100% foolproof way to insure that the file will be deleted in case of a full system crash. Think about what happens if the user just pulls the plug while the file is on disk. No amount of exception handling will protect you from that (the worst) case. The best thing you can do is not write th...
How to guarantee files that are decrypted during run time are cleaned up?
[ "", "c++", "c", "encryption", "filesystems", "" ]
F# declared namespace is not available in the c# project or visible through the object browser. I have built a normal F# library project, but even after i build the project and reference it to my C# project, I am unable to access the desired namespace. I am also unable to see it in the object browser, i get an error ...
What if you reference the produced DLL directly (i.e., not via a project reference, but via a file reference)?
Maybe IntelliSense is just messed up? What compiler error do you get when you try to use it in C#? When you say "the object browser is unable to read it" what does that mean? For what it's worth, I added this to a F# library project, referenced it (project) from a C# console app, and was able to use it. IntelliSense d...
F# declared namespace is not available in the c# project or visible through the object browser
[ "", "c#", "f#", "resharper", "interop", "" ]
How can I print a message to the error console, preferably including a variable? For example, something like: ``` print('x=%d', x); ```
Install [Firebug](http://en.wikipedia.org/wiki/Firebug_(software)) and then you can use `console.log(...)` and `console.debug(...)`, etc. (see [the documentation](http://getfirebug.com/wiki/index.php/Console_Panel#Message_types) for more).
``` console.error(message); // Outputs an error message to the Web Console console.log(message); // Outputs a message to the Web Console console.warn(message); // Outputs a warning message to the Web Console console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small...
JavaScript: How do I print a message to the error console?
[ "", "javascript", "debugging", "" ]
There are times when I want to use *mootools* for certain things and Prototype & *`script.aculo.us`* for others but within the same site. I've even considered adding others, but was concerned about conflicts. Anyone have experience, or am I just trying to make things too complicated for myself?
If you really, really want to do this, then you will be able to without too many problems - the main libraries are designed to behave well inside their own namespaces, with a couple of notable exceptions - from [Using JQuery with Other Frameworks](http://docs.jquery.com/Using_jQuery_with_Other_Libraries): > The jQuery...
AFAIK, all the popular frameworks are designed to be combined with other frameworks. I don't think combining them is that much of a problem. I would however discourage combining them purely from a case of bandwidth needs. A slow site experience is less forgivable than a more complicated development experience.
What JavaScript frameworks conflict with each other?
[ "", "javascript", "frameworks", "conflict", "" ]
I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions. Example: "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc. The current appr...
``` #include <iostream> #include <conio.h> #include <string> #include <map> using namespace std; struct Token { enum E { Replace, Literal, Eos }; }; class ParseExp { private: enum State { State_Begin, State_Literal, State_StartRep, State_Rep...
How many evaluation expressions do intend to have? If it's small enough, you might just want to use brute force. For instance, if you have a `std::map<string, string>` that goes from your `key` to its `value`, for instance `user` to `Matt Cruikshank`, you might just want to iterate over your entire map and do a simple...
Evaluating expressions inside C++ strings: "Hi ${user} from ${host}"
[ "", "c++", "parsing", "boost", "string", "expression", "" ]
There is small system, where a database table as queue on MSSQL 2005. Several applications are writing to this table, and one application is reading and processing in a FIFO manner. I have to make it a little bit more advanced to be able to create a distributed system, where several processing application can run. The...
This will work, but you'll probably find you'll run into blocking or deadlocks where multiple processes try and read/update the same data. I wrote a procedure to do exactly this for one of our systems which uses some interesting locking semantics to ensure this type of thing runs with no blocking or deadlocks, [describ...
This approach looks reasonable to me, and is similar to one I have used in the past - successfully. Also, the row/ table will only be locked while the update and select operations take place, so I doubt the row vs table question is really a major consideration. Unless the processing overhead of your app is so low as ...
Parallel processing of database queue
[ "", "c#", "sql-server-2005", "distributed-system", "" ]
For example: Base class header file has: ``` enum FOO { FOO_A, FOO_B, FOO_C, FOO_USERSTART }; ``` Then the derived class has: ``` enum FOO { FOO_USERA=FOO_USERSTART FOO_USERB, FOO_USERC }; ``` Just to be clear on my usage it is for having an event handler where the base class has events and then derived classes ca...
No. The compiler needs to be able to decide whether the enum fits in a char, short, int or long once it sees the }. So if the base class header has ``` enum Foo { A, B, MAX = 1<<15 }; ``` a compiler may decide the enum fits in 16 bits. It can then use that, e.g. when laying out the base class. If you were late...
Yes, as long as the enum's are both members of a class. If they weren't then they would be of the same type and the compiler would be very unhappy.
In C++: Is it possible to have a named enum be continued in a different file?
[ "", "c++", "enums", "continue", "" ]
I don't care what the differences are. I just want to know whether the contents are different.
The low level way: ``` from __future__ import with_statement with open(filename1) as f1: with open(filename2) as f2: if f1.read() == f2.read(): ... ``` The high level way: ``` import filecmp if filecmp.cmp(filename1, filename2, shallow=False): ... ```
If you're going for even basic efficiency, you probably want to check the file size first: ``` if os.path.getsize(filename1) == os.path.getsize(filename2): if open('filename1','r').read() == open('filename2','r').read(): # Files are the same. ``` This saves you reading every line of two files that aren't even t...
In Python, is there a concise way of comparing whether the contents of two text files are the same?
[ "", "python", "file", "compare", "" ]
I wanted to make Map of Collections in Java, so I can make something like ``` public void add(K key, V value) { if (containsKey(key)) { get(key).add(value); } else { Collection c = new Collection(); c.add(value); put(key, value); } } ``` I've tried to make it with somethi...
If `map` is a `Map<K, Collection<V>>`, use the idiom [`computeIfAbsent(...).add(...)`,](http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-) like this: ``` map.computeIfAbsent(key, k -> new ArrayList<>()).add(value); ``` Or, for a `Set`: ``` map.computeIfAbsent(...
If it's an option, you may want to just use the Google Collections API - <http://code.google.com/p/google-collections/>. Even if you can't use it, maybe having a look at how they implemented their MultiMaps would help you with your implementation.
Map of collections
[ "", "java", "generics", "collections", "" ]
Say I create an object thus: ``` var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; ``` What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that: ``` keys == ["ircEvent", "method", "regex"] ```
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method: ``` var keys = Object.keys(myObject); ``` The above has a full polyfill but a simplified version is: ``` var getKe...
As [slashnick](https://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object#208020) pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iter...
How to list the properties of a JavaScript object?
[ "", "javascript", "" ]
I am refactoring some MFC code that is littered with `ASSERT` statements, and in preparation for a future Linux port I want to replace them with the standard `assert`. Are there any significant differences between the two implementations that people know of that could bite me on the backside? Similarly, I have also co...
No. The MFC version just includes an easy to debug break point.
Replace them with [your own assertion macro](https://stackoverflow.com/questions/17732/when-should-assertions-stay-in-production-code). That's how you get the most benefit out of it (logging, stack trace, etc.)
ASSERT vs. ATLASSERT vs. assert
[ "", "c++", "mfc", "assert", "" ]
Am I able to embed the .net runtime so that .net is not required on the host operating system? I was looking at doing this with Mono by looking here: <http://mono-project.com/Embedding_Mono> but seems to allude to using external modules to accomplish this. My goal is to have one single executable with no installed .net...
You can now [statically compile Mono assemblies](http://tirania.org/blog/archive/2008/Nov-05.html) as was just demonstrated at PDC. The purpose of doing this was to allow .Net applications to run on the iPhone, but this should work anywhere. There are some limitations to this; obviously, it can't depend on runtime-gen...
Third-party solution i've used with much success: [Xenocode](http://www.xenocode.com/)
Embedding .Net Runtime
[ "", "c#", "windows", "mono", "clr", "" ]
I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError). What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping refer...
VisualVM is included in the most recent releases of Java. You can use this to create a heap dump, and look at the objects in it. Alternatively, you can also create a heapdump commandine using jmap (in your jdk/bin dir): ``` jmap -dump:format=b,file=heap.bin <pid> ``` You can even use this to get a quick histogram of...
If you need something free, try [VisualVM](https://visualvm.github.io/) From the project's description: > VisualVM is a visual tool integrating commandline JDK tools and lightweight profiling capabilities. Designed for both development and production time use.
How can I see what is in my heap in Java?
[ "", "java", "out-of-memory", "" ]
I know this question has been asked before, but I ran into a problem. Oddly enough, when I execute this function, it includes the html of the page that the link you select to execute the function. ``` function exportCSV($table) { $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num...
My guess is that you've got some sort of template that generates the same HTML header and footer regardless of the page that is requested. Sometime before the exportCSV function is called, the header is generated. You don't show the bottom of the output, but I'll bet the footer is there too, since I suspect the flow c...
php isn't really my thing, but it seems like you need to clear the response stream before writing out your content. Perhaps something else is writing html out to the stream, before reaching this function? Like a template or master page or something of that nature? The HTML content looks like a typical header/nav bar. ...
Why am I getting HTML in my MySQL export to CSV?
[ "", "php", "mysql", "csv", "" ]
I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run: ``` groovy RunScript.groovy ``` instead of: ``` groovy -cp ojdbc5.jar RunScript.groovy ```
Summarized from *Groovy Recipes*, by Scott Davis, **Automatically Including JARs in the ./groovy/lib Directory**: 1. Create `.groovy/lib` in your login directory 2. Uncomment the following line in ${GROOVY\_HOME}/conf/groovy-starter.conf `load !{user.home}/.groovy/lib/*.jar` 3. Copy the jars you want included to `...
There are a few ways to do it. You can add the jar to your system's CLASSPATH variable. You can create a directory called .groovy/lib in your home directory and put the jar in there. It will be automatically added to your classpath at runtime. Or, you can do it in code: ``` this.class.classLoader.rootLoader.addURL(new...
How do I auto load a database jar in Groovy without using the -cp switch?
[ "", "java", "scripting", "groovy", "classpath", "" ]
Is it possible to enable a second monitor programatically and extend the Windows Desktop onto it in C#? It needs to do the equivalent of turning on the checkbox in the image below. ![alt text](https://i.stack.imgur.com/ss2sE.png)
[MSDN Device Context Functions](http://msdn.microsoft.com/en-us/library/ms533259.aspx) What you basically need to do: > Use the EnumDisplayDevices() API call > to enumerate the display devices on > the system and look for those that > don't have the > `DISPLAY_DEVICE_ATTACHED_TO_DESKTOP` > flag set (this will include...
If you have windows 7, then just start a process: ``` private static Process DisplayChanger = new Process { StartInfo = { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, FileName = "DisplaySwitch.exe", Arguments = "/extend" ...
How do I enable a second monitor in C#?
[ "", "c#", "winforms", "desktop", "multiple-monitors", "" ]
I'm trying to write a small app that monitors how much power is left in a notebook battery and I'd like to know which Win32 function I could use to accomplish that.
For Vista and up you can use [RegisterPowerSettingNotification](http://msdn.microsoft.com/en-us/library/aa373196(VS.85).aspx) For earlier functions see the [Power Management Functions](http://msdn.microsoft.com/en-us/library/aa373163(VS.85).aspx) in this section of the MSDN page "Power Management Functions: Windows Se...
I recommend the use of the Win32 [GetSystemPowerStatus](https://msdn.microsoft.com/en-us/library/windows/desktop/aa372693%28v=vs.85%29.aspx) function. A code snippet : ``` int getBatteryLevel() { SYSTEM_POWER_STATUS status; GetSystemPowerStatus(&status); return status.BatteryLifePercent; } ```
Monitor battery charge with Win32 API
[ "", "c++", "c", "winapi", "monitor", "power-management", "" ]
Is there an elegant way to specialize a template based on one of its template parameters? Ie. ``` template<int N> struct Junk { static int foo() { // stuff return Junk<N - 1>::foo(); } }; // compile error: template argument '(size * 5)' involves template parameter(s) template<int N> struct Ju...
How's this: ``` #include <iostream> using namespace std; template < typename T, T N, T D > struct fraction { typedef T value_type; static const value_type num = N; static const value_type denom = D; static const bool is_div = (num % denom == 0); }; template< typename T, T N, T D, bool P > struct do_i...
Using D programming language templates, one could write it as: ``` struct Junk(int N) { static int foo() { static if (N == 0) return 0; else static if ((N % 5) == 0) return N; else return Junk!(N - 1).foo(); } } ``` static if's are executed at co...
Elegant template specialization
[ "", "c++", "templates", "" ]
I have a file with data listed as follows: ``` 0, 2, 10 10, 8, 10 10, 10, 10 10, 16, 10 15, 10, 16 17, 10, 16 ``` I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers. Fo...
There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it's as short and readable as the python code: ``` FILE *fp = fopen("file.dat", "r"); int x, y, z; std::vector<int> vx, vy, vz; while (fscanf(fp, "%d, %d, %d", &x, &y, &z) == 3) { vx.push_back(x); vy.push_back(y); ...
There's no real need to use boost in this example as streams will do the trick nicely: ``` int main(int argc, char* argv[]) { ifstream file(argv[1]); const unsigned maxIgnore = 10; const int delim = ','; int x,y,z; vector<int> vecx, vecy, vecz; while (file) { file >> x; f...
c++ file io & splitting by separator
[ "", "c++", "file-io", "split", "" ]
For example, if I have a *unicode* string, I can encode it as an *ASCII* string like so: ``` >>> u'\u003cfoo/\u003e'.encode('ascii') '<foo/>' ``` However, I have e.g. this *ASCII* string: ``` '\u003foo\u003e' ``` ... that I want to turn into the same *ASCII* string as in my first example above: ``` '<foo/>' ```
It took me a while to figure this one out, but [this page](http://www.egenix.com/www2002/python/unicode-proposal.txt) had the best answer: ``` >>> s = '\u003cfoo/\u003e' >>> s.decode( 'unicode-escape' ) u'<foo/>' >>> s.decode( 'unicode-escape' ).encode( 'ascii' ) '<foo/>' ``` There's also a 'raw-unicode-escape' codec...
On Python 2.5 the correct encoding is "unicode\_escape", not "unicode-escape" (note the underscore). I'm not sure if the newer version of Python changed the unicode name, but here only worked with the underscore. Anyway, this is it.
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
[ "", "python", "unicode", "ascii", "" ]
I have checked with the [wikipedia article](http://en.wikipedia.org/wiki/Facade_pattern), and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?
**Facade pattern: provides a unified - simplified interface to a complex subsystem or set of interfaces. It provides a higher level interface simultaneously decoupling the client from the complex subsystem.** An example to help you understand .. a cab driver. You tell the cab driver 'Take me to PointX' (unified simpli...
``` class Engine { public: void Start() { } }; class Headlights { public: void TurnOn() { } }; // That's your facade. class Car { private: Engine engine; Headlights headlights; public: void TurnIgnitionKeyOn() { headlights.TurnOn(); engine.Start(); } }; int Main(in...
Explain Facade pattern with c++ example?
[ "", "c++", "design-patterns", "facade", "" ]
I've developed an application (C#) that currently sits on a a number of workstations. Each workstation accesses the same database (MS-SQL). I've been asked to port this to Citrix. Can anyone offer insight into documentation or suggestion of where someone would start with this? Is the application installed on the Citrix...
For fairly straight forward app things just run. Does you app need use localization configuration? i.e. time / date or currency formatting? There are Citrix settings that can do many things in this area. The users computer settings can be "projected" into Citrix or they could be overridden in Citrix. Also do you use ...
I wrote a C# application for a client once, and they ran it off a Citrix server without ever informing me of this, so if you're lucky you won't need to worry about Citrix at all. The only problem I ever ran into was due to my use of ActiveReports, which released a hotfix that broke on 64-bit processors (like the one my...
What are the basics one needs to know when porting an application to Citrix?
[ "", "c#", "citrix", "" ]
How does one go about converting an image to black and white in PHP? Not just turning it into greyscale but every pixel made black or white?
Simply round the grayscale color to either black or white. ``` float gray = (r + g + b) / 3 if(gray > 0x7F) return 0xFF; return 0x00; ```
Using the php [gd](https://www.php.net/manual/en/function.imagefilter.php) library: ``` imagefilter($im, IMG_FILTER_GRAYSCALE); imagefilter($im, IMG_FILTER_CONTRAST, -100); ``` Check the user comments in the link above for more examples.
How do you convert an image to black and white in PHP
[ "", "php", "image", "imagefilter", "" ]
I'm writing some Javascript to resize the large image to fit into the user's browser window. (I don't control the size of the source images unfortunately.) So something like this would be in the HTML: ``` <img id="photo" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title ...
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there. ``` <img id="photo" onload='loaded(this.id)' src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /> ```
Using the [jquery data store](http://api.jquery.com/data/) you can define a 'loaded' state. ``` <img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" /> ``` Then elsewhere you can do: ``` if ($('#myimage').data('loaded')) { // loaded, so do stuff } ```
How can I determine if an image has loaded, using Javascript/jQuery?
[ "", "javascript", "jquery", "image", "" ]
I'm reading *The C++ Programming Language* and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127. If not, why are their only 255 possible values in the second implementation possibility, ...
You're stuck in [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) thinking - The C++ standard does not define the representation used for negative numbers! If your computer (god forbid) uses [ones's complement](http://en.wikipedia.org/wiki/Ones_complement#Ones.27_complement) to represent negative num...
It's wrong to think that an unsigned char ranges from 0 to 255. that's only its minimal range. a char must have at least 8 bits, and signed char, unsigned char and char itself can have indeed more that just 8 bits. so then that means that unsigned char could go beyond 255. though admittedly, i haven't got an implementa...
Does the range for integer values of a char depend on implementation?
[ "", "c++", "language-implementation", "" ]
The Winform application is release with ClickOnce in our Intranet. We store personal preference for the GUI in the Isolated Storage. All works pretty fine :) The problem is when we have a new version of the application, we publish... all preferences are lost! User need to setup their preference over and over each vers...
You need to use *application* scoped, rather than *domain* scoped, isolated storage. This can be done by using one of **IsolatedStorageFileStream's** overloaded constructors. Example: ``` using System.IO; using System.IO.IsolatedStorage; ... IsolatedStorageFile appScope = IsolatedStorageFile.GetUserStoreForApplicati...
I was working on a ClickOnce app a while ago and used Environment.GetFolderPath(ApplicationData) - e.g. roaming app data folder, to store all settings. Worked fine and survived numerous updates. Just create a subdireectory with the name of your app or CompanyName/AppName or whatever and store everything in there.
ClickOnce and IsolatedStorage
[ "", "c#", "winforms", ".net-2.0", "clickonce", "isolatedstorage", "" ]
The Zend Framework coding standard mentions the following: > For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing whitespace into the response. * [Zend Framework coding standard: file formatting](http:...
Removing the closing tags when you can is probably a best practice really. The reason for that is because if you have any character (even whitespace) outside of the ?> in a php file it can stop thing such as headers to stop working if the character gets sent to the browser before the header gets set.
If you use closing PHP tags then you can easily find files that have been accidentally truncated (e.g. haven't been uploaded completely). However such problem should be fixed by making filesystem and transfers reliable rather than adding PHP "canary" tags :) Another possible reason is that PEAR coding standards requ...
What are the arguments IN FAVOR of PHP closing tags for PHP only files?
[ "", "php", "" ]
I have a client server application that sends XML over TCP/IP from client to server and then broadcast out to other clients. How do i know at what the minimun size of the XML that would warrant a performance improvement by compression the XML rather than sending over the regular stream. Are there any good metrics on t...
Xml usually compresses very well, as it tends to have a lot of repetition. Another option would be to swap to a binary format; BinaryFormatter or NetDataContractSerializer are simple options, but both are notoriously incompatible (for example with java) compared with xml. Another option would be a portable binary for...
A loose metric would be to compress anything larger than a single packet, but that's just nitpicking. There is no reason to refrain from using a binary format internally in your application - no matter how much time compression will take, the network overhead will be several orders of magnitude slower than compressing...
Compression XML metrics .
[ "", "c#", "xml", "winforms", "vb6", "compression", "" ]
I'm painfully new to PHP, and was trying to set up phpBB on my local site. I have a stock debian install of apache2 and php5. The phpBB installer ran fine, connected to the database and created all its tables with no problem. But when I tried to open the login page, I got a 0-byte response. A little digging showed tha...
try doing this: ``` <?php ini_set('display_errors', true); error_reporting(E_ALL | E_NOTICE); $id = mysql_pconnect('localhost','myusername', 'mypassword', true); print "id=".$id."\n"; ?> ``` and see what the response is **edit** From your comment it looks like the mysql module is not installed or enabled. You could...
Just noted that you're using a @ in front of mysql\_pconnect(). That suppresses all errors, which in this case is a pretty bad idea. Remove that and you would probably see the output. Otherwise: Check your php.ini, should be in /etc/php5/apache2/php.ini for debian. Check for a line called display\_errors, set that t...
PHP5: calling external functions, and logging errors
[ "", "php", "mysql", "pear", "" ]
I recently installed VS 6.0 after installing VS 2008 and overwrite JIT settings .. when i started VS 2008 option dialog .. it said another debugger has taken over VS 2008 debugger and I asked me to reset .. so I did .. Now everything works fine except javascript debugging. I am unable to debug javascript .. I can set ...
I guess I have to reinstall Visual Studio 2008 and see if that solves this problem
It sounds like your script debugging is disabled. To enable it goto, tools internet options, advanced and make sure disable script debugging is unticked. What I also found helps is if you put a > "debugger;" line in your javascript. Remeber that if you put a debugger statement on the first line in a function it will...
Script Debugging Not Working (VS 2008)
[ "", "javascript", "visual-studio-2008", "debugging", "jit", "" ]
I use the Boost Test framework to unit test my C++ code and wondered if it is possible to test if a function will assert? Yes, sounds a bit strange but bear with me! Many of my functions check the input parameters upon entry, asserting if they are invalid, and it would be useful to test for this. For example: ``` void...
I don't think so. You could always write your own assert which throws an exception and then use BOOST\_CHECK\_NOTHROW() for that exception.
Having the same problem, I digged through the documentation (and code) and found a "solution". The Boost UTF uses `boost::execution_monitor` (in `<boost/test/execution_monitor.hpp>`). This is designed with the aim to catch everything that could happen during test execution. When an assert is found execution\_monitor i...
Testing for assert in the Boost Test framework
[ "", "c++", "unit-testing", "boost", "assert", "boost-test", "" ]
What are some good jQuery Resources along with some gotchas when using it with ASP.Net?
One thing to note is that if you use WebMethods for Ajax, the response values will be returned wrapped in an object named 'd' for security reasons. You will have to unwrap that value, which is usually not a problem, unless you are using a component (such as the jqGrid plugin) that relies upon jquery ajax. To get around...
ASP.Net's autogenerated id's make using jQuery's selector syntax somewhat difficult. Two easy ways around this problem: * Search for objects using css class instead of id * You can weed out the uniqueid garbage with: `$('[id$=myid]')`
jQuery & ASP.Net Resources & Gotchas
[ "", "javascript", "jquery", "asp.net", ".net", "resources", "" ]
I am trying to come up with the best data structure for use in a high throughput C++ server. The data structure will be used to store anything from a few to several million objects, and no sorting is required (though a unique sort key can be provided very cheaply). The requirements are that it can support efficient in...
Personally, I'm quite fond of persistent immutable data structures in highly-concurrent situations. I don't know of any specifically for C++, but Rich Hickey has created some excellent (and blisteringly fast) immutable data structures in Java for [Clojure](http://clojure.org). Specifically: vector, hashtable and hashse...
Linked lists are definitely the answer here. Insertion and deletion in O(1), iteration from one node to the next in O(1) and stability across operations. `std::list` guarantees all of these, including that all iterators are valid unless the element is removed from the list (this include pointers and references to eleme...
Concurrent data structure design
[ "", "c++", "data-structures", "concurrency", "" ]
I want to scale an image in C# with quality level as good as Photoshop does. Is there any C# image processing library available to do this thing?
Here's a nicely commented Image Manipulation helper class that you can look at and use. I wrote it as an example of how to perform certain image manipulation tasks in C#. You'll be interested in the **ResizeImage** function that takes a System.Drawing.Image, the width and the height as the arguments. ``` using System;...
When you draw the image using GDI+ it scales quite well in my opinion. You can use this to create a scaled image. If you want to scale your image with GDI+ you can do something like this: ``` Bitmap original = ... Bitmap scaled = new Bitmap(new Size(original.Width * 4, original.Height * 4)); using (Graphics graphics ...
High Quality Image Scaling Library
[ "", "c#", "image", "image-processing", "image-manipulation", "image-scaling", "" ]
I have a `contacts` table which contains fields such as `postcode`, `first name`, `last name`, `town`, `country`, `phone number` etc, all of which are defined as `VARCHAR(255)` even though none of these fields will ever come close to having 255 characters. (If you're wondering, it's this way because Ruby on Rails migra...
In storage, `VARCHAR(255)` is smart enough to store only the length you need on a given row, unlike `CHAR(255)` which would always store 255 characters. But since you tagged this question with MySQL, I'll mention a MySQL-specific tip: as rows are copied from the storage engine layer to the SQL layer, `VARCHAR` fields ...
In addition to the size and performance considerations of setting the size of a varchar (and possibly more important, as storage and processing get cheaper every second), the disadvantage of using varchar(255) "just because" is reduced *data integrity*. Defining maximum limits for strings is a **good thing to do** to ...
Are there disadvantages to using a generic varchar(255) for all text-based fields?
[ "", "mysql", "sql", "" ]
I am making a program in C# to connect to a webcam and do some image manipulation with it. I have a working application that uses win32 api (avicap32.dll) to connect to the webcam and send messages to it that sends it to the clipboard. The problem is that, while accessible from paint, reading it from the program resul...
I've recently started doing some hobby work in this area. We settled on using the [OpenCV](http://sourceforge.net/projects/opencv/) library with the [opencvdotnet](http://code.google.com/p/opencvdotnet/) wrapper. It supports capturing frames from a webcam: ``` using (var cv = new OpenCVDotNet.CVCapture(0)) { var ...
There are really two ways to get camera data into your application, DirectShow and WIA. Microsoft recommends that you use [WIA](http://msdn.microsoft.com/en-us/library/ms630368.aspx), and the interface for WIA is fairly simple to wrap your brain around. I created and published an open source [WIA desktop library](http:...
Webcam usage in C#
[ "", "c#", "clipboard", "webcam", "" ]
I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a `°` character - [Unicode U+00B0](http://en.wikipedia.org/wiki/Degree_symbol) (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that...
pdc got it right, the following works fine (but fails without the `decode`): ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import wx app = wx.PySimpleApp() app.TopWindow = wx.Frame(None) field = wx.TextCtrl(app.TopWindow) field.Value += '°'.decode('ISO8859-1') app.TopWindow.Show() app.MainLoop() ```
I can't say mych about wxPython itself, but I am guessing that it is trying to convert the text to Unicode before displaying it, If you have a string like `'123\xB0'` and try to convert it to Unicode with teh default encoding (ASCII) then it will throw `UnicodeDecodeError`. You can probably fix this by replacing ``` s...
How do I safely decode a degrees symbol in a wxPython app?
[ "", "python", "unicode", "wxpython", "decode", "textctrl", "" ]
What's the most appropriate type used to store the duration time information of a video in sql server?
There are [several options](http://www.sqlteam.com/article/working-with-time-spans-and-durations-in-sql-server), including using the builtin DateTime or Time data type with offset from a particular fixed zero (which will allow you to use the built-in date/time function to get hours, minutes and seconds, etc. If you we...
It depends on how granular you need and if you have any constraints on a maximum time. For example, would you need to know down to the millisecond of time duration or is 1 second granular enough? The other thing to consider is how much data do you (or can you) store. For SQL Server 2005, you have these constraints: t...
Storing video duration time in sql server
[ "", "sql", "sql-server", "database", "sql-server-2005", "" ]
i have a class with a static public property called "Info". via reflection i want to get this properties value, so i call: ``` PropertyInfo pi myType.GetProperty("Info"); string info = (string) pi.GetValue(null, null); ``` this works fine as long as the property is of type string. but actually my property is of type ...
Could you create a short but complete program that demonstrates the problem? Given that you're talking about plugins, my *guess* is that you've got the problem of having IPluginInfo defined in two different assemblies. See if [this article](http://pobox.com/~skeet/csharp/plugin.html) helps at all. The easiest way to ...
ok, thanks for all the answers. i indeed already had the plugininterface in a separate .dll but had placed this .dll in the pluginhosts directory as well as in the directory with all the plugins.
PropertyInfo.GetValue(null, null) returns null
[ "", "c#", "" ]
I've successfully used the Windows SendMessage method to help me do various things in my text editor, but each time I am just copying and pasting code suggested by others, and I don't really know what it means. There is always a cryptic message number that is a parameter. How do I know what these code numbers mean so t...
This is the windows message code. They are defined in the header files, and generally available translated as an include of some sort with different languages. example: WM\_MOUSEMOVE = &H200 MK\_CONTROL = &H8 MK\_LBUTTON = &H1 MK\_MBUTTON = &H10 MK\_RBUTTON = &H2 MK\_SHIFT = &H4 MK\_XBUTTON1 = &H20 M...
Each message in Windows is signified by a number. When coding using the Windows SDK in native code, these are provided by defines such as WM\_CHAR, WM\_PAINT, or LVM\_GETCOUNT, but these defines are not carried over to the .NET framework because in the most part, the messages are wrapped by .NET events like OnKeyPresse...
Explanation of SendMessage message numbers?
[ "", "c#", "winforms", "interop", "" ]
I'm attempting to fulfill a rather difficult reporting request from a client, and I need to find away to get the difference between two DateTime columns in minutes. I've attempted to use trunc and round with various [formats](http://www.ss64.com/orasyntax/fmt.html) and can't seem to come up with a combination that make...
``` SELECT date1 - date2 FROM some_table ``` returns a difference in days. Multiply by 24 to get a difference in hours and 24\*60 to get minutes. So ``` SELECT (date1 - date2) * 24 * 60 difference_in_minutes FROM some_table ``` should be what you're looking for
By default, oracle date subtraction returns a result in # of days. So just multiply by 24 to get # of hours, and again by 60 for # of minutes. Example: ``` select round((second_date - first_date) * (60 * 24),2) as time_in_minutes from ( select to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as f...
Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?
[ "", "sql", "oracle", "datediff", "" ]
I'm using the [freeodbc++](http://libodbcxx.sourceforge.net/) library to access data on a MS SQL Server 2000 database (SP3? SP4?). In particular, I'm running a particularly long and nasty stored procedure. I can watch the procedure execute in SQL Profiler, however, it tends to stop processing at a certain point. No err...
Have you tried profiling on the SQL Server side, to see what is happening with your SPID? Also, I have not used freeodbc++, but maybe there is a PRINT statement in there that it does not like. You could also SET NOCOUNT ON to suppress the row count messages. Again, this depends upon how freeodbc++ reacts to these "inf...
Adding "::Sleep(30000);" immediately after I call execute on the ODBC statement object (and before the statement close command) keeps the server process from exiting prematurely. Must be a bug with freeodbc++ or a configuration error on my part. Thanks for the troubleshooting/debugging tips.
Why does the Store Procedure I'm calling over ODBC fail at the same location?
[ "", "sql", "sql-server", "sql-server-2000", "odbc", "" ]
I am declaring an array of void pointers. Each of which points to a value of arbitary type. `void **values; // Array of void pointers to each value of arbitary type` Initializing values as follows: ``` values = (void**)calloc(3,sizeof(void*)); //can initialize values as: values = new void* [3]; int ival...
You have 3 things that are dynamically allocated that need to be freed in 2 different ways: ``` delete reinterpret_cast<int*>( values[0]); delete reinterpret_cast<float*>( values[1]); free( values); // I'm not sure why this would have failed in your example, // but it would have leaked the 2 it...
I suspect the issue is with the way that you allocated `values`: `values = (void*)calloc(3,sizeof(`**`void`**`))`. That should be `sizeof(void *)` rather than just `sizeof(void)`. sizeof(void) may be zero or something else that makes no sense, so you're not really allocating any memory to begin with... it's just dumb ...
Freeing memory allocated to an array of void pointers
[ "", "c++", "c", "memory-management", "" ]
Is there a way to hide private data members of a C++ class away from its users, in the cpp file? I think of the private members as part of the implementation and it seems a little backwards to declare them in the header file.
The "pimpl" idiom is how this is generally handled. See * <http://www.gotw.ca/gotw/024.htm> * <http://www.gotw.ca/gotw/028.htm> * <http://herbsutter.com/gotw/_100/> (updated for C++11)
you want to use something like the PIMPL idiom <http://en.wikipedia.org/wiki/Opaque_pointer>
Hiding private data members? (C++)
[ "", "c++", "class", "private", "" ]
I've recently gotten my hobby java project embedded into a page [thanks to this very site](https://stackoverflow.com/questions/138157/java-console-like-web-applet), but now I'm having some security issues. I have the include: ``` import java.sql.*; ``` and the line: ``` Class.forName("com.mysql.jdbc.Driver").newIns...
I think the security exception is actually from a System.exit() call in your applet, after the Class.forName(). Generally you are not allowed to call System.exit() in unsigned applets as it shuts the whole JVM down. Have you checked if line 80 is actually the Class.forName() line, or does line 80 have some kind of exce...
If you're trying to use the a JDBC driver from the applet, then the applet needs to be signed with a certificate, and your server needs to deliver this certificate when the applet is loaded on the client side.
How do I permit my Java applet to use MySQL?
[ "", "java", "mysql", "security", "applet", "" ]
When using `__import__` with a dotted name, something like: `somepackage.somemodule`, the module returned isn't `somemodule`, whatever is returned seems to be mostly empty! what's going on here?
From the python docs on `__import__`: > ``` > __import__( name[, globals[, locals[, fromlist[, level]]]]) > ``` > > ... > > When the name variable is of the form > package.module, normally, the > top-level package (the name up till > the first dot) is returned, not the > module named by name. However, when a > non-emp...
python 2.7 has importlib, dotted paths resolve as expected ``` import importlib foo = importlib.import_module('a.dotted.path') instance = foo.SomeClass() ```
Python's __import__ doesn't work as expected
[ "", "python", "python-import", "" ]
How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and write the results to a text box.
``` // Start the child process. Process p = new Process(); // Redirect the output stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "YOURBATCHFILE.bat"; p.Start(); // Do not wait for the child process to exit before // reading to ...
Here's a quick sample: ``` //Create process System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); //strCommand is path and file name of command to run pProcess.StartInfo.FileName = strCommand; //strCommandParameters are parameters to pass to program pProcess.StartInfo.Arguments = strCommandParamete...
How To: Execute command line in C#, get STD OUT results
[ "", "c#", "command-line", "" ]
We are looking to provide two **custom Platform switches** (the **platform dropdown** in the configuration manager) for our projects **in Visual Studio**. For example one for 'Desktop' and one for 'Web'. The target build tasks then compile the code in a custom way based on the platform switch. We don't want to add to ...
You should be able to use the Configuration Manager dialog to create new platforms.
May be this subject will be interesting for somebody after three years. I had similar difficulties with configuring build platforms and resolved them. The error you gave was thrown because the PlatformTarget property was set with Desctop, not because the Platform property. These two properties have a little bit differ...
How to add and compile for custom 'Platform' switch for visual studio projects?
[ "", "c#", "visual-studio", "visual-studio-2008", "" ]
In VS2008 I have written a C# service, an installer, and have created a setup package to install it. The service needs to load an xml file to operate. Where is the best place to put this file in the various filesystem folders offered by the VS setup project, and how do I then refer to these paths from my code? I shoul...
I am not sure which place is better to store the XML file. I don't think it will matter alot. But if you need to get special folder path in the system you can use Environment class to do so. The following line of code get the path of the Program Files: ``` string path = Environment.GetFolderPath(Environment.SpecialFol...
To read installation path used by installer created from setup project: 1) Open "Custom Actions" editor in your setup project 2) Add custom action from your assembly where your installer class is located (If you haven't done so already) 3) Select this custom action and add `/myKey="[TARGETDIR]\"` to CustomActionData...
Locating installer paths in c#
[ "", "c#", "visual-studio-2008", "installation", "service", "" ]
I'm looking for a lightweight, easy to setup CI server that I can run on my laptop along with Visual Studio & Resharper. I'm obviously looking at all the big names like CruiseControl, TeamCity etc etc but the biggest consideration to me is ease of setup and to a lesser extent memory footprint. Edit: I'd also like some...
I use [TeamCity](http://www.jetbrains.com/teamcity/), and is really, really easy to setup and get it running. Check the [Demos and Documentation](http://www.jetbrains.com/teamcity/documentation/index.html). You will have it up and running in less than one hour!
I have just started to use CruiseControl.NET. With no prior knowlege I was able to get it up and running with a single test project using MSBuild, MSTest and Team Foundation Server (i.e. CodePlex) in a couple of hours. I posted a bunch of links to useful resources here [Devsta 2008 Day 0: Source Control and CI](http:/...
Best Continuous Integration Setup for a solo developer (.NET)
[ "", "c#", ".net", "asp.net", "continuous-integration", "" ]
I have a problem when an unhandeld exception occurs while debugging a WinForm VB.NET project. The problem is that my application terminates and I have to start the application again, instead of retrying the action as was the case in VS2003 The unhandeld exception is implemented in the new My.MyApplication class found...
Ok I found the answer to this issue in this blog post: [Handling "Unhandled Exceptions" in .NET 2.0](http://www.julmar.com/blog/mark/PermaLink,guid,f733e261-5d39-4ca1-be1a-c422f3cf1f1b.aspx) Thank you Mark! The short answer is: ``` Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); ``` Th...
OK I have done more work on this but still don't have an answer. I found that this problem is not only related to VB.NET but also to C# Here is simple C# program that demonstrates the problem: ``` using System; using System.Windows.Forms; namespace TestCSharpUnhandledException { public partial class Form1 : Form ...
Visual Studio 2008 - Application closes when unhandled exception occurs
[ "", "c#", "vb.net", "visual-studio-2008", "debugging", "" ]
I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page). What I'd like to know is what the consensus is on the 'best' way to open a link in a new brow...
I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler: ``` $(document).ready(function() { $('a[rel*=external]').click(function(){ window.open($(this).attr('href')); return false; }); }); ``` I fi...
Why is `target="_blank"` a bad idea? It's supposed to do exactly what you want. edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)
What's the best way to open new browser window?
[ "", "javascript", "html", "browser", "" ]
I have a public static class in which I would like to have a ToString() method. I have defined it as public static string ToString(), but get the following warning: > 'Class.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Other...
Yes, using the "new" modifier will effectively silence the compiler warning but you are **explicitly hiding** an instance method with a static method. (This is different than overriding the method.) Typically you don't want to hide an instance method except with very good reasons and you really shouldn't hide it with a...
In a static class you cannot override ToString. .ToString is an instance method and by definition a static class can only have static members. Also why would you want to override .ToString()? There is no way to get an instance of the class and hence no way to call the function. Note: Using the new syntax will not ove...
How do you override ToString in a static class?
[ "", "c#", ".net", "static", "overriding", "" ]
I want to make a generic class that accepts only serializable classes, can it be done with the where constraint? The concept I'm looking for is this: ``` public class MyClass<T> where T : //[is serializable/has the serializable attribute] ```
Nope, I'm afraid not. The only things you can do with constraints are: * `where T : class` - T must be a reference type * `where T : struct` - T must be a non-nullable value type * `where T : SomeClass` - T must be SomeClass or derive from it * `where T : ISomeInterface` - T must be ISomeInterface or implement it * `w...
What I know; you can not do this. Have you though about adding an 'Initialize' method or something similar? ``` public void Initialize<T>(T obj) { object[] attributes = obj.GetType().GetCustomAttributes(typeof(SerializableAttribute)); if(attributes == null || attributes.Length == 0) throw new Inval...
Can you use "where" to require an attribute in c#?
[ "", "c#", "generics", "attributes", "constraints", "where-clause", "" ]
This might be a old question: Why does `IEnumerable<T>` inherit from `IEnumerable`? This is how .NET do, but it brings a little trouble. Every time I write a class implements `IEumerable<T>`, I have to write two `GetEnumerator()` functions, one for `IEnumerable<T>` and the other for `IEnumerable`. And, `IList<T>` doe...
[Straight from the horse's mouth](https://learn.microsoft.com/en-us/archive/blogs/brada/why-does-ienumerable-inherits-from-ienumerable) (Hejlsberg): > Ideally all of the generic collection interfaces (e.g. `ICollection<T>`, `IList<T>`) would inherit from their non-generic counterparts such that generic interface insta...
The answer for `IEnumerable` is: "because it can without affecting type safety". `IEnumerable` is a "readonly" interface - so it doesn't matter that the generic form is more specific than the nongeneric form. You don't break anything by implementing both. `IEnumerator.Current` returns `object`, whereas `IEnumerator<T>...
Why does IEnumerable<T> inherit from IEnumerable?
[ "", "c#", "generics", "ienumerable", "" ]
I have a function that automatically exports a table into a CSV file, then I try to attach that same file into a function that will email it. I have sent attachments using html mime mail before, but I was wondering if that created CSV file needs to be stored on the server first before attaching it to the email?
It depends on your functions, if you have a function that can export the table as CSV into a string and then the mail functions support creating attachments from a string then I think you have what you need...
In theory you could embed it yourself by writing the appropriate tags and handcrafing the email yourself. Or you can go the easy way and save it to a temporary location, use a tool like PHPMailer (which might also support string attachment) to attach the file, send the mail and then remove the temp file.
When attaching a file to an email, does it need to be stored on the server first?
[ "", "php", "mysql", "" ]
What are the best ways of dealing with UTC Conversion and daylight saving times conversion. What are the problems and their solutions. All in C# .Net 2.0. Also any existing problems with this in .Net 2.0.
If you use UTC times you shouldn't worry about clients timezones or daylight saving... (if they have set a standard)
You really don't need to worry about it much with .NET if you're using UTC everywhere. If you're interested in seeing this sort of stuff in action you might check out the [TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo_members.aspx) class.
Best ways to deal with UTC and daylight saving times
[ "", "c#", ".net", "" ]
What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index. This is one way to do it, but it seems inelegant at best. ``` //Remove the existing role assignment for the user. int cnt = 0; int assToDelete = 0; foreach (SPRoleAssignment spAssignment in workspace.Ro...
If you want to access members of the collection by one of their properties, you might consider using a `Dictionary<T>` or `KeyedCollection<T>` instead. This way you don't have to search for the item you're looking for. Otherwise, you could at least do this: ``` foreach (SPRoleAssignment spAssignment in workspace.Role...
If RoleAssignments is a `List<T>` you can use the following code. ``` workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName); ```
Best way to remove items from a collection
[ "", "c#", "collections", "" ]
every time i create a FileInfo object and access it's lastaccesstime property, it's always a few minutes off. the file property window remains constant, however the application shows that it is usually a few minutes after the property window time. Also, i noticed that if i drag the file to the cmd window to pass the f...
In my experience, last access time is notoriously unreliable. According to <http://technet.microsoft.com/en-us/library/cc781134.aspx>... > The Last Access Time on disk is not always current because NTFS looks for a one-hour interval before forcing the Last Access Time updates to disk. NTFS also delays writing the Last...
[The MSDN article with basic info about file times](http://msdn.microsoft.com/en-us/library/ms724290(VS.85).aspx) has this to say about file time resolution and Last Access times: > For example, on FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a res...
LastAccess Time is incorrect
[ "", "c#", "fileinfo", "lastaccesstime", "" ]
I am a little confused by the multitude of ways in which you can import modules in Python. ``` import X import X as Y from A import B ``` I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen a...
In production code in our company, we try to follow the following rules. We place imports at the beginning of the file, right after the main file's docstring, e.g.: ``` """ Registry related functionality. """ import wx # ... ``` Now, if we import a class that is one of few in the imported module, we import the name ...
Let me just paste a part of conversation on django-dev mailing list started by Guido van Rossum: > [...] > For example, it's part of the Google Python style guides[1] that all > imports must import a module, not a class or function from that > module. There are way more classes and functions than there are > modules, ...
What are good rules of thumb for Python imports?
[ "", "python", "python-import", "" ]
Is there anyway to automatically run `javascript:window.print()` when the page finishes loading?
`<body onload="window.print()">` or `window.onload = function() { window.print(); }`
The following code must be put at the **end** of your HTML file so that once the content has loaded, the script will be executed and the window will print. ``` <script type="text/javascript"> <!-- window.print(); //--> </script> ```
Auto start print html page using javascript
[ "", "javascript", "html", "printing", "" ]
After staring at [this 3D cube](http://maettig.com/code/javascript/3d_dots.html) and [these triangles](http://www.uselesspickles.com/triangles/demo.html) for a while I started wondering if there's any good reliable Javascript graphics library with basic 3D support. Any suggestion?
John Resig's port of the Processing library to Javascript: <http://ejohn.org/blog/processingjs>
I'm very psyched about [Raphaël](http://raphaeljs.com/). I've used it in one project and it works like a charm.
Are there any good Javascript graphics libraries?
[ "", "javascript", "graphics", "3d", "" ]
I'm having problems with Iterator.remove() called on a HashSet. I've a Set of time stamped objects. Before adding a new item to the Set, I loop through the set, identify an old version of that data object and remove it (before adding the new object). the timestamp is included in hashCode and equals(), but not equalsDa...
I was very curious about this one still, and wrote the following test: ``` import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; public class HashCodeTest { private int hashCode = 0; @Override public int hashCode() { return hashCode ++; } public ...
Under the covers, HashSet uses HashMap, which calls HashMap.removeEntryForKey(Object) when either HashSet.remove(Object) or Iterator.remove() is called. This method uses both hashCode() and equals() to validate that it is removing the proper object from the collection. If both Iterator.remove() and HashSet.remove(Obje...
HashSet.remove() and Iterator.remove() not working
[ "", "java", "collections", "" ]
I think questions like this are the reason why I don't like working with PHP. The manual is good, if you can find what you are looking for. After reading through the [Array Functions](https://www.php.net/array), I didn't see one that provides the functionality I need. I have an array (in my case, numerically indexed) ...
[`array_diff`](http://de.php.net/array_diff) is what you want. ``` $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); ``` Result: `"blue"`.
Just to add to this... array\_diff appears to show elements in the first array which don't appear in the second array. It doesn't show those elements which only appear in one or the other array. e.g. ``` <? $test = "hello"; $array1 = array("a" => "green", "red", "bicycle", "red"); $array2 = array("b" => "green", "ye...
Is there a PHP function to remove any/all key/value pairs that have a certain value from an array?
[ "", "php", "arrays", "" ]
I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely **different parts of the DOM** and mostly pos...
I never used jQuery, just looked up API, so I can assume you can do the following: ``` var o1 = $(element1).offset(); var o2 = $(element2).offset(); var dx = o1.left - o2.left; var dy = o1.top - o2.top; var distance = Math.sqrt(dx * dx + dy * dy); ```
Using pure javascript. ``` var dx = obj1.offsetLeft - obj2.offsetLeft; var dy = obj1.offsetTop - obj2.offsetTop; var distance = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2)); ```
Get relative position between 2 DOM elements using JavaScript
[ "", "javascript", "jquery", "dom", "" ]
In the spirit of [Best Practices: Always return a \_\_\_\_, never a \_\_\_\_](https://stackoverflow.com/questions/171156/best-practices-always-return-a-never-a), I face a similar question in my upcoming [migration from JDK1.4.2 to JDK5 and more](https://stackoverflow.com/questions/219164/generics-in-legacy-code). (Yes,...
Prefer Collection (or List, or Set as appropriate) to an array. With generics you get the type-checking that was lacking pre-Java 5. Also, by exposing only the interface, you are free to change the implementation later (e.g. switch an ArrayList for a LinkedList). Arrays and generics don't mix very well. So, if you wan...
Actually arrays still have one advantage over Collections/Lists. Due to the way that Java implements Generics through type erasure, you cannot have two methods that take Collections as arguments yet only differ by the Collection's generic type. Ex: ``` public void doSomething(Collection<String> strs) { ... } public v...
API java 5 and more: should I return an array or a Collection?
[ "", "java", "arrays", "api", "generics", "collections", "" ]
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. * [phpUnderControl](http://phpundercontrol.org/about.html) * [Jenkins](http://jenkins-ci.org/content/about-jenkins-ci) + [Hudson](http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudso...
You might want to check out [Nose](http://somethingaboutorange.com/mrl/projects/nose/) and [the Xunit output plugin](http://nose.readthedocs.org/en/latest/plugins/xunit.html). You can have it run your unit tests, and coverage checks with this command: ``` nosetests --with-xunit --enable-cover ``` That'll be helpful i...
Don't know if it would do : [Bitten](http://bitten.edgewall.org/) is made by the guys who write Trac and is integrated with Trac. [Apache Gump](http://gump.apache.org/) is the CI tool used by Apache. It is written in Python.
"Pretty" Continuous Integration for Python
[ "", "python", "jenkins", "continuous-integration", "buildbot", "" ]
I know that you can use a dummy "int" parameter on `operator++` and `operator--` to override the postfix versions of those operators, but I vaguely recall something about a dummy parameter that you could declare on a destructor. Does anyone know anything about that, and if so, what that dummy parameter did? This was i...
You're possibly thinking of the placement and nothrow forms of operator delete, which have the signatures: ``` void operator delete(void *, void *) throw(); void operator delete(void *, const std::nothrow_t&) throw(); void operator delete[](void *, void *) throw(); void operator delete[](void *, const std::nothrow_t&)...
Either you are misremembering, or you should try to forget it. Destructors don't have parameters, return types and they shouldn't throw exceptions.
C++ class member functions that use dummy parameters
[ "", "c++", "parameters", "destructor", "" ]
Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what's wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same re...
The dates you print from `Calendar` are local to your timezone, whereas the epoch is defined to be midnight of 1970-01-01 in UTC. So if you live in a timezone west of UTC, then your date will show up as 1969-12-31, even though (in UTC) it's still 1970-01-01.
First, `c.get(Calendar.MONTH)` returns 0 for Jan, 1 for Feb, etc. Second, use `DateFormat` to output dates. Third, your problems are a great example of how awkward Java's Date API is. Use Joda Time API if you can. It will make your life somewhat easier. Here's a better example of your code, which indicates the timez...
Java.util.Calendar - milliseconds since Jan 1, 1970
[ "", "java", "calendar", "" ]
How do I tell if my application (compiled in Visual Studio 2008 as *Any CPU*) is running as a 32-bit or 64-bit application?
``` if (IntPtr.Size == 8) { // 64 bit machine } else if (IntPtr.Size == 4) { // 32 bit machine } ```
If you're using [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 4.0, it's a one-liner for the current process: ``` Environment.Is64BitProcess ``` Reference: *[Environment.Is64BitProcess Property](http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess.aspx)* (MSDN)
How do I tell if my application is running as a 32-bit or 64-bit application?
[ "", "c#", "64-bit", "32-bit", "" ]
I've got a Excel VSTO 2005 application I need to debug, I've tried attaching to the process EXCEL.EXE in Visual Studio 2005 to no avail. Does anyone know what to do in order to debug managed code running in a VSTO Excel Application?
I haven't worked with Excel, but with VSTO in Word, attaching the debugger to the WINWORD process works, but makes it impossible to debug startup code, as it has already ran before you can attach. In this case you can insert ``` Debugger.Launch(); ``` which will stop your code and ask to attach a debugger. It's about...
I usually include a "StopSwitch" which launches the debugger when the stop-switch is enabled in the app.config file. * *StopSwitch Stops Execution for Just-In-Time Debugging* at <http://missico.spaces.live.com/blog/cns!7178D2C79BA0A7E3!309.entry>) After enabling the `StopSwitch`, sometimes the JIT Debugger is not lau...
How to I attach to a VSTO Excel Application Process to Debug?
[ "", "c#", "excel", "vsto", "" ]
How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I've been searching a lot but c...
For normal DateTimes, if you don't initialize them at all then they will match `DateTime.MinValue`, because it is a value type rather than a reference type. You can also use a nullable DateTime, like this: ``` DateTime? MyNullableDate; ``` Or the longer form: ``` Nullable<DateTime> MyNullableDate; ``` And, finally...
If you're using .NET 2.0 (or later) you can use the nullable type: ``` DateTime? dt = null; ``` or ``` Nullable<DateTime> dt = null; ``` then later: ``` dt = new DateTime(); ``` And you can check the value with: ``` if (dt.HasValue) { // Do something with dt.Value } ``` Or you can use it like: ``` DateTime d...
DateTime "null" / uninitialized value?
[ "", "c#", "datetime", "null", "initialization", "" ]
I am building a fun little app to determine if I should bike to work. I would like to test to see if it is either Raining or Thunderstorm(ing). ``` public enum WeatherType : byte { Sunny = 0, Cloudy = 1, Thunderstorm = 2, Raining = 4, Snowing = 8, MostlyCloudy = 16 } ``` I was thinking I could do something like: ``...
Your current code will say whether it's *exactly* "raining and thundery". To find out whether it's "raining and thundery and possibly something else" you need: ``` if ((currentWeather.Type & _badWeatherTypes) == _badWeatherTypes) ``` To find out whether it's "raining *or* thundery, and possibly something else" you ne...
I'm not sure that it should be a flag - I think that you should have an range input for: * Temperature * How much it's raining * Wind strength * any other input you fancy (e.g. thunderstorm) you can then use an algorithm to determine if the conditions are sufficiently good. I think you should also have an input for ...
Determining if enum value is in list (C#)
[ "", "c#", ".net", "enums", "" ]
I've made a Django site, but I've drank the Koolaid and I want to make an *IPhone* version. After putting much thought into I've come up with two options: 1. Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework. 2. Find some time of middleware that reads the user-agent...
Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render\_to\_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the stand...
Detect the user agent in middleware, switch the url bindings, profit! How? Django request objects have a .urlconf attribute, which can be set by middleware. From django docs: > Django determines the root URLconf > module to use. Ordinarily, this is the > value of the ROOT\_URLCONF setting, but > if the incoming Http...
Change Django Templates Based on User-Agent
[ "", "python", "django", "django-templates", "mobile-website", "django-middleware", "" ]
Developing a website and just trying to get back into the swing of (clever) SQL queries etc, my mind had totally gone tonight! There is a website <http://www.ufindus.com/> which has a textbox allowing you to enter either a place name or a postcode/zipcode. I am trying to do something similiar but I am rubbish at SQL -...
You could use an "OR" to get the job done. For example, place = 'YORK' or postcode = 'YORK' You might also do better using the LIKE statement, as in WHERE place LIKE 'YORK%' or postcode LIKE 'YORK%' (this assumes both place and postcode are character-based columns)
why not use OR instead of AND? ``` place = @textboxvalue OR post = @textboxvalue ```
SQL - querying via a textbox which could take different values
[ "", "asp.net", "sql", "sql-server", "" ]
I'm trying to get this piece of code working a little better. I suspect it's the loop reading one byte at a time. I couldn't find another way of doing this with gzip decompression. Implementing a `StreamReader` is fine, but it returns a string which I can't pass to the decompression stream. Is there a better way? ```...
I'd agree with jmcd that WebClient would be far simpler, in particular WebClient.DownloadData. re the actual question, the problem is that you are reading single bytes, when you should probably have a fixed buffer, and loop - i.e. ``` int bytesRead; byte[] buffer = new byte[1024]; while((bytesRead = webStream.Read(bu...
Is the [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx) class no use for what you want to do?
C# downloading a webpage. A better way needed, CPU usage high
[ "", "c#", "url", "download", "uri", "" ]
Using the client-side ASP.NET AJAX library, I have created an instance of a client component with the $create shortcut-method (<http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx>). The object is attached to a DOM element. Now I need to get a reference to the instance, but it is neither registered on window o...
Does the $find() routine find it?
According to MSDN, Sys.Component.Create should return the object that it just created. And, $create is just a shortcut for Sys.Component.create. ``` Returns: A new instance of a component that uses the specified parameters. ``` So, try: ``` var instance = $create(someType); ```
ASP.NET AJAX: How to get a client instance created with the $create method?
[ "", "asp.net", "javascript", "ajax", "asp.net-ajax", "client-side", "" ]
I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback ...
Since Twisted is event driven, you don't need a timeout per se. You simply need to set a state variable (like datagramRecieved) when you receive a datagram and register a [looping call](http://twistedmatrix.com/projects/core/documentation/howto/time.html) that checks the state variable, stops the reactor if appropriate...
I think `reactor.callLater` would work better than `LoopingCall`. Something like this: ``` class Protocol(DatagramProtocol): def __init__(self, timeout): self.timeout = timeout def datagramReceived(self, datagram): self.timeout.cancel() # ... timeout = reactor.callLater(5, timedOut) r...
Is it possible to set a timeout on a socket in Twisted?
[ "", "python", "networking", "sockets", "twisted", "" ]
Trends data from Twitter Search API in JSON. Grabbing the file using: ``` $jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); ``` How do I work with data from this object. As an array? Only really need to extract data from the [name]...
You mean something like this? ``` <?php $jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); foreach ( $json_output->trends as $trend ) { echo "{$trend->name}\n"; } ```
If you use `json_decode($string, true)`, you will get no objects, but everything as an associative or number indexed array. Way easier to handle, as the stdObject provided by PHP is nothing but a dumb container with public properties, which cannot be extended with your own functionality. ``` $array = json_decode($stri...
Handling data in a PHP JSON Object
[ "", "php", "json", "" ]
I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach? ``` def by_tag(tag): return ''' function(doc) { if (doc.tags.length > 0) { for (var tag in...
*Disclaimer: I didn't test this and don't know if it can perform better.* Create a single perm view: ``` function(doc) { for (var tag in doc.tags) { emit([tag, doc.published], doc) } }; ``` And query with \_view/your\_view/all?startkey=['your\_tag\_here']&endkey=['your\_tag\_here', {}] Resulting JSON struct...
You can define a single permanent view, as Bahadir suggests. when doing this sort of indexing, though, *don't* output the doc for each key. Instead, emit([tag, doc.published], null). In current release versions you'd then have to do a separate lookup for each doc, but SVN trunk now has support for specifying "include\_...
How to build "Tagging" support using CouchDB?
[ "", "python", "couchdb", "tagging", "document-oriented-db", "" ]
By default, objects (tables, stored procedures, etc) are set up with the dbo owner/schema (I think ms sql 2000 calls it owner, while ms sql 2005 calls it schema) The owner/schema is really a role or user in the database. I've always left the default of dbo, but I've recently seen some examples in microsoft training bo...
The use of schemas is exceptionally beneficial when you have security concerns. If you have multiple applications that access the database, you might not want to give the Logistics department access to Human Resources records. So you put all of your Human Resources tables into an hr schema and only allow access to it ...
I've used schemas in the past sort of like namespaces so you could have multiple entities named Address (`[Person].[Address]`, `[Company].[Address]`). The advantage to this is visual organization in SQL Management Studio, you can get the same thing by putting everything under one schema and naming tables with a single ...
Schema, Owner for objects in MS SQL
[ "", "sql", "sql-server", "sql-server-2005", "sql-server-2000", "" ]