Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've started to use constructs like these: ``` class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def __setattr__(self, m, v): super.__setattr__(self, m, v) ``` Update: based on this thread, I've revised the DictObj implement...
This is a simpler version of your DictObj class: ``` class DictObj(object): def __getattr__(self, attr): return self.__dict__.get(attr) >>> d = DictObj() >>> d.something = 'one' >>> print d.something one >>> print d.somethingelse None >>> ```
Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with ‘things that resemble objects’, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this kind...
Javascript style dot notation for dictionary keys unpythonic?
[ "", "python", "coding-style", "" ]
Does anyone know where to get the **source** code for LambdaProbe? Alternatively, does anyone know if the project could be moved to a community repository? Besides the tool not being updated for over a year, the LambdaProbe website has been down since late September 2008. Background: Lambda Probe is a useful tool fo...
The site still seems to be pretty dead. However, I've done some looking into available source code and release notes and here's everything I've found in regards to lambda probe. I hope it helps! Google cache search: site:www.lambdaprobe.org Release notes: <http://209.85.173.104/search?q=cache:HB0527hDa5AJ:www.lambdap...
There seems to be a fork of the project over at <http://code.google.com/p/psi-probe/>
Is Lambda Probe dead?
[ "", "java", "memory", "tomcat", "garbage-collection", "" ]
I have the following C# which simply replaces parts of the input string that look like EQUIP:19d005 into URLs, like this: ``` input = Regex.Replace(input, @"(EQUIP:)(\S+)", @"<a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2"">$1$2</a>", RegexOptions.IgnoreCase); ``` The HTML ends up looking l...
OK, 2 solutions, one inline: ``` input = Regex.Replace(input, @"(EQUIP:)(\S+)", m => string.Format(@"<a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp?eqnum={2}"">{0}{1}</a>", m.Groups[1].Value, m.Groups[2].Value, m.Groups[2].Value.ToUpper()), RegexOptions.IgnoreCase); ``` The other using a separate f...
Using Regex.Replace directly I do not think there is a way. But you could make this a two step process and get the result you are looking for. ``` var match = Regex.Match(input, @"(EQUIP:)(\S+)", RegexOptions.IgnoreCase); var input = String.Format( @"&lt;a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp...
Regular Expression Uppercase Replacement in C#
[ "", "c#", ".net", "regex", "" ]
I have a database that stores events in it and a page with a calendar object on it. When rendering the days it looks through the months events and if any match the current day being rendered it creates a linkbutton to represent the event in the day on the calendar and adds it to that cell. I add some javascript to the ...
Your session vars are controlled by the server, JS runs client side, and as such cannot modify the vars directly. You need to make server requests using POST or GET and hidden iframes, or XMLHTTPRequest() calls to send data from the JS to the server, and then have your server side code handle the vars. Add another qu...
Add another query string variable that the page can use to trigger existing vs new.
Javascript and session variables
[ "", "javascript", "session", "" ]
I can't seem to find the \_findfirst / findfirst, \_findnext / findnext API on gcc for Linux, and would actually rather use the Standard Template Library (STL) for that if it is included there. Does anyone know what API there is available for listing files in a directory under Linux for C++ (gcc)?
Check out the [Boost.Filesystem](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm) library. In particular, the [basic\_directory\_iterator](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/reference.html#Class-template-basic_directory_iterator).
It's not a C++-style API, but the API you aren't finding (the Linux/Unix correspondent of DOS/Windows-style findfirst/findnext) is opendir/readdir/closedir. The main advantage of using opendir/readdir/closedir is that you do not need any extra library (it's part of the C library, which you are already using). In fact,...
Is there a standard way to do findfirst, findnext with gcc on linux using stl?
[ "", "c++", "linux", "gcc", "stl", "file", "" ]
I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it. Here's a quick example to make it clearer... this is what I have now: ``` Pages: 1 ...
Here is some code based on original code from [this very old link](https://www.strangerstudios.com/sandbox/pagination/diggstyle.php). It uses markup compatible with Bootstrap's pagination component, and outputs page links like this: ``` [1] 2 3 4 5 6 ... 100 1 [2] 3 4 5 6 ... 100 ... 1 2 ... 14 15 [16] 17 18 ... 100 ....
Kinda late =), but here is my go at it: ``` function Pagination($data, $limit = null, $current = null, $adjacents = null) { $result = array(); if (isset($data, $limit) === true) { $result = range(1, ceil($data / $limit)); if (isset($current, $adjacents) === true) { if ...
Smart pagination algorithm
[ "", "php", "pagination", "" ]
Python's access to environment variables does not accurately reflect the operating system's view of the processes environment. os.getenv and os.environ do not function as expected in particular cases. Is there a way to properly get the running process' environment? --- To demonstrate what I mean, take the two rough...
That's a very good question. It turns out that the `os` module initializes `os.environ` to the value of [`posix`](http://docs.python.org/library/posix.html)`.environ`, which is set on interpreter start up. In other words, the standard library does not appear to provide access to the [getenv](http://www.opengroup.org/o...
You can use `ctypes` to do this pretty simply: ``` >>> from ctypes import CDLL, c_char_p >>> getenv = CDLL("libc.so.6").getenv >>> getenv.restype = c_char_p >>> getenv("HOME") '/home/glyph' ```
Environment Variables in Python on Linux
[ "", "python", "gdb", "environment-variables", "" ]
I have noticed that regardless of a given script's execution time, every date() call will return the same timestamp regardless of where the function is called within the script. It looks like it just returns the time at which the script first started executing. For logging purposes, it would be extremely useful to be ...
<http://us.php.net/microtime> gives me different times within the same script.
I ran this code on my machine: ``` <?php $time_start = time(); sleep(2); $time_end = time(); print 'Start: ' . date("m/d/Y @ g:i:sA", $time_start) . '<br>'; print 'End: ' . date("m/d/Y @ g:i:sA", $time_end); ?> ``` And it output: ``` Start: 10/23/2008 @ 3:12:23PM End: 10/23/2008 @ 3:12:25PM ``` Leading me to bel...
Getting Precise Times in PHP
[ "", "php", "logging", "date", "timestamp", "" ]
I'm creating a table that looks something like this. ``` CREATE TABLE packages ( productCode char(2) , name nvarchar(100) , ... ) ``` How do I make sure the productCode is always one of two values `XJ` or `XD`?
``` ALTER TABLE packages ADD CONSTRAINT constraintname CHECK (productCode in ('XJ', 'XD')) ```
Either make it a [foreign key](http://en.wikipedia.org/wiki/Foreign_key) to a lookup table, or add a [check constraint](http://en.wikipedia.org/wiki/Check_constraint) to enforce it.
How do I ensure a column contains one of a set of values?
[ "", "sql", "sql-server", "" ]
I have this CheckBoxList on a page: ``` <asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource" datatextfield="CountryName" datavaluefield="CountryCode" /> ``` I'd like to loop through the checkbox elements on the client using Javascript and grab the value of each checked checkbox, but t...
Stored in ViewState, you cannot access them on the client without [**some hacking**](http://www.daveparslow.com/2007/08/assigning-value-to-aspnet-checkbox.html).
I finally have the answer I've been looking for! The asp.net CheckboxList control *does* in fact render the value attribute to HTML - it has been working for me in a Production site for over a year now! (We ALWAYS have EnableViewState turned off for all our sites and it still works, without any tweaks or hacks) Howev...
Where are the DataValueField values for a CheckBoxList stored?
[ "", "asp.net", "javascript", "" ]
I've noticed that when generating a new C++ project using MS Visual Studio 2008, the **Release** build contains debugging symbols - specifically the following settings are enabled: * The C++/General/Debug Information Format is set to **Program Database**. * The Linker/Debugging/Generate Debug Info setting is set to **...
We have turned on those settings in our commercial releases for years now with no apparent downside. The upsides are enormous,though. We have integrated a crash dump packager that packages the dump along with some other information and emails it (with the user's consent) to a company inbox. This has helped us find pro...
They're turned on by default because: 1. If you don't create them now, you can't create them later. 2. You need them. Enabling debug info in Visual C++ causes a small entry to be added to the binary header, identifying the PDB for this binary. It's too small to be of any size concern, and doesn't contain any useful s...
Visual C++ 2008 'Release' build contains debug information
[ "", "c++", "visual-studio", "debugging", "" ]
In there an easy way to do this in PHP. I want to make sure that only web requests from certain countries are able to access my website. Any ideas?
Use an IP geolocation database (some are free) and $\_SERVER["REMOTE\_ADDR"] to get the visitor's IP address. <http://www.maxmind.com/app/geolitecity> is a free (less accurate) version of a commercial one.
Like Gilles, I've used MaxMind's GeoIP stuff for this in the past - configured with the PECL extension for speed. It works reasonably well, but... The requirement for this kind of thing tends to come from somebody that doesn't understand that it is impossible to reliably determine a visitors location in this way. It's...
How do I limit which countries can view my website ( PHP )
[ "", "php", "geolocation", "" ]
Anybody have a slicker way to do this? Seems like it should be easier than this, but I'm having a mental block. Basically I need to remove items from an dictionary and recurse into the values of the items that are also dictionaries. ``` private void RemoveNotPermittedItems(ActionDictionary menu) { var keysToRemove...
You don't really need to collect the keys and iterate them again if you iterate the dictionary in reverse (from 'menu.Count - 1' to zero). Iterating in forward order will, of course, yield mutated collection exceptions if you start removing things. I don't know what an ActionDictionary is, so I couldn't test your exac...
While foreach and GetEnumerator fails, a for-loop works, ``` var table = new Dictionary<string, int>() {{"first", 1}, {"second", 2}}; for (int i = 0; i < table.Keys.Count; i++)//string key in table.Keys) { string key = table.Keys.ElementAt(i); if (key.StartsWith("f")) { table.Remove(key); } } `...
Removing Items From IDictionary With Recursion
[ "", "c#", "recursion", "idictionary", "" ]
``` string [] files = new string[2]; files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml"; files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml"; //Resharper complains this is an "access to modified closure" for (int i = 0; i < files.Length; i++ ) { // Resharper disable AccessToModifi...
In this case, it's okay, since you are actually executing the delegate *within* the loop. If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the *variable* `i` rather than its value at the time of t...
I know this is an old question, but I've recently been studying closures and thought a code sample might be useful. Behind the scenes, the compiler is generating a class that represents a lexical closure for your function call. It probably looks something like: ``` private sealed class Closure { public string[] fi...
Access to Modified Closure
[ "", "c#", "resharper", "closures", "" ]
This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this: ``` a = {1:'', 2:'', 3:'', 4:''} exclusion = [3, 4, 5] # have to build up a new list or the iteration breaks toRemove = [] for var in a.iterkeys(): if var in exclusion:...
Consider [dict.pop](http://docs.python.org/library/stdtypes.html#dict.pop): ``` for key in exclusion: a.pop(key, None) ``` The `None` keeps pop from raising an exception when `key` isn't a key.
``` a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion) ```
Removing a subset of a dict from within a list
[ "", "python", "list", "containers", "" ]
I am working on a web page that is using jQuery. I have an Ajax call that gets data from the server and updates a div. Inside that data there is a jQuery function, but the function is not being called after the data is loaded into the page. I have the proper js files included in the page already. This is what is retur...
If you want JavaScript tag evaluation, with html content, you should set the dataType option of the ajax call to "html": ``` $.ajax({ type: "GET", url: "yourPage.htm", dataType: "html" }); ``` Or dataType "script", if you want to load and execute a .js file: ``` $.ajax({ type: "GET", url: "test.js", data...
I had a similar problem where I wanted to add little jquery date pickers to a couple fields I was retrieving via ajax. here is what I did to get around it... just quick and dirty. Instead of returning this whole block from my ajax call: ``` <script type="text/javascript"> $(function() { $('input').myFunct...
Calling a jQuery function inside html return from an AJAX call
[ "", "javascript", "jquery", "ajax", "" ]
I have a windows application running at the backend. I have functions in this applications mapped to hot keys. Like if I put a message box into this function and give hot key as `Alt`+`Ctrl`+`D`. then on pressing `Alt`, `Ctrl` and `D` together the message box comes up. My application is working fine till this point. N...
Your question has two answers ## How can my app set a global hotkey You have to call an API funcion called RegisterHotKey ``` BOOL RegisterHotKey( HWND hWnd, // window to receive hot-key notification int id, // identifier of hot key UINT fsModifiers, // key-modifier flags UINT vk ...
## UPDATE 2020 ### How to get the selected text from the foreground window No idea for how long has this been possible but instead of fighting with Win32 programming (mostly `user32.dll` and various Windows messages like `WM_GETTEXT, WM_COPY` and various `SendMessage(handle, WM_GETTEXT, maxLength, sb)` calls) which i...
Copy and Modify selected text in different application
[ "", "c#", ".net", "clipboard", "hotkeys", "" ]
I want to use an AOP framework, but I have two constraints. Any framework that I choose 1. Must be fairly independent. I plan to use this in a legacy code base, and hence cannot upgrade prospective dependencies like commons-logging-XXX.jar to commons-logging-newest.jar. 2. Must be fairly well documented, should no...
[AspectJ](http://www.eclipse.org/aspectj/) as far as I can tell is just a compiler and imposes no dependencies on compiled programs other than including the AspectJ runtime jar. It is also actively maintained, part of the Eclipse project and has a nice development environment ([AJDT](http://www.eclipse.org/ajdt/), a p...
I like Spring + AspectJ. You can do all of your pointcut definitions in xml **if you like**, and you don't need to change a line of code on your legacy stuff. If you already know spring and AOP concepts, there's not much to learn.
Which is the simplest and least dependent AOP framework in Java?
[ "", "java", "jakarta-ee", "aop", "" ]
What is the best way to validate a crontab entry with PHP? Should I be using a regex, or an external library? I've got a PHP script that adds/removes entries from a crontab file, but want to have some way to verify that the time interval portion is in a valid format.
Hmmm, interesting problem. If you're going to really validate it, regex isn't going to be enough, you'll have to actually parse the entry and validate each of the scheduling bits. That's because each bit can be a number, a month/day of the week string, a range (2-7), a set (3, 4, Saturday), a Vixie cron-style shortcut...
Who said regular expressions can't do that? Courtesy of my employer, [Salir.com](http://www.salir.com), here's a PHPUnit test which does such validation. Feel free to modify & distribute. I'll appreciate if you keep the @author notice & link to web site. ``` <?php /** * @author Jordi Salvat i Alabart - with thanks t...
Validating Crontab Entries with PHP
[ "", "php", "regex", "validation", "cron", "" ]
What is the functional programming approach to convert an `IEnumerable<string>` to a delimited string? I know I can use a loop, but I'm trying to wrap my head around functional programming. Here's my example: ``` var selectedValues = from ListItem item in checkboxList.Items where item.Selected select item.Value; var...
``` var delimitedString = selectedValues.Aggregate((x,y) => x + ", " + y); ```
``` string.Join(", ", string[] enumerable) ```
C# - IEnumerable to delimited string
[ "", "c#", "functional-programming", "" ]
I've inherited a large Java app that uses Struts, Spring, and Hibernate. The classes and interfaces I deal with daily are: Struts Actions, Struts ActionForms, Value Objects, Service Interfaces and Implementations, DAO Interfaces and Implementations, and Entities. I'm pretty clear on the how and why of most of these, ex...
1. Considering the DAO - VO transformation; whether this is usefull depends on how Hibernate is used. If the entire Web request handling is in a single Hibernate session you should not really need separate VO's. If, however, your DAO layer opens a session to retrieve an object and closes the session before you are fin...
1) No need for separate VO and Entities : some companies mandate such a structure for their project. It might have made sense in a different project and hence it was mandated (I can only guess) 2) Service layer : it is the natural separation from DAO and Action layer, right ? 3) It does NOT hurt however value Objects...
How to properly use Struts ActionForms, Value Objects, and Entities?
[ "", "java", "design-patterns", "architecture", "oop", "" ]
I want completely automated integration testing for a Maven project. The integration tests require that an external (platform-dependent) program is started before running. Ideally, the external program would be killed after the unit tests are finished, but is not necessary. Is there a Maven plugin to accomplish this? ...
You could use the [antrun](http://maven.apache.org/plugins/maven-antrun-plugin/) plugin. Inside you would use ant's [exec](http://ant.apache.org/manual/Tasks/exec.html) [apply](http://ant.apache.org/manual/Tasks/apply.html) task. Something like this. ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <a...
The cargo maven plugin is a good way to go if you're doing servlet development and want to deploy the resulting WAR for integration testing. When I do this myself, I often set up a multi-module project (although that's not strictly nessecarily) and encapsulate all the integration testing into that one module. I then e...
Starting external process during integration testing in maven
[ "", "java", "maven-2", "build-process", "automated-tests", "integration-testing", "" ]
If I have a property: ``` public list<String> names { get; set; } ``` How can I generate and handle a custom Event for arguments sake called 'onNamesChanged' whenever a name gets added to the list?
You should check out the [System.ComponentModel.BindingList](http://msdn.microsoft.com/en-us/library/ms132680.aspx), specifically the [ListChanged event](http://msdn.microsoft.com/en-us/library/ms132742.aspx).
A BindingList is likely your best option as it has builtin change tracking and a variety of existing events you can use. Below is an example of exposing a custom event for Add which forwards to the BindingList event. ``` class Example { private BindingList<string> m_names = new BindingList<string>(); ...
C# custom event handlers
[ "", "c#", "properties", "event-handling", "" ]
We're working on an hospital information system that is being written on C# and using NHibernate to map objects to database. MVC pattern is being used to separate business logic from UI. Here is the problem, How do you get variable sized different set of strings to UI? For example a `Contact` object have a property n...
If the locations are actually going to be used for anything, get them into the database. If the data "isn't really used", but cities lookup is provided to make the user interface better, then the XML file option is not a bad way to go either. By used, I mean stuff like *list all emplyees in New York* and stuff like th...
I would vote for solution #4. That's the way I have always done it in similar situations. It just seems like a cleaner solution.
Getting String Sets into Presentation Layer
[ "", "c#", "nhibernate", "oop", "mapping", "domain-driven-design", "" ]
Can someone please point me to the easiest way to have a timer in a Win32 service? I suppose I could create a dummy window for this purpose or have a second thread do tick counts, but what's best? Is there a more elegant way? Thanks in advance.
You can use Timer Queues (<http://msdn.microsoft.com/en-us/library/ms686796.aspx>). They don't require an HWND.
Instead of using UI timers (even though you can use the NULL window handle as shown by Mr. 1800-INFO) you can use kernel waitable timer objects. See [CreateWaitableTimer](http://msdn.microsoft.com/en-us/library/ms682492(VS.85).aspx) in the API docs. These can then be waited-on using WaitForSingleObject or WaitForMultip...
Timer in a win32 service
[ "", "c++", "windows", "winapi", "windows-services", "" ]
Does Java Connection.close rollback into a finally block?. I know .Net SqlConnection.close does it. With this I could make try/finally blocks without catch... Example: ``` try { conn.setAutoCommit(false); ResultSet rs = executeQuery(conn, ...); .... executeNonQuery(conn, ...); .... conn.com...
According to [the javadoc](http://java.sun.com/javase/6/docs/api/java/sql/Connection.html#close()), you should try to either commit or roll back before calling the close method. The results otherwise are implementation-defined.
In any database system I've worked with, there is no harm in doing a rollback right after the commit, so if you commit in the try block, and rollback in the finally, things get committed, whereas if an exception or early return causes the commit to be missed, the rollback will rollback the transaction. So the safe thin...
Does Java Connection.close rollback?
[ "", "java", "transactions", "database-connection", "" ]
I have a custom class that implements that IComparable. This class is stored in a Generic List. I now need to compare to lists to see which objects are in list A but not in list B. I thought the most simple way of doing this would be to iterate through list B and do A.contains(). I do not know how to get it to use my...
Why don't you just override the `Equals` method of your class to be consistent in meaning with `CompareTo(other) == 0`? This is the simplest way and also the most idiomatic since, as you've noticed, `Contains` compares equality rather than using `CompareTo`. However, this check is done via `Equals`. It does *not* check...
Also if you are using framework 3.5 you can make a query like: list notInB = From item in listA where (listB.find(function(x) x.property = item.property) = nothing) select item This will return all the items of the listA that are not in listB. The linq function find returns the item that matches de condition that yo...
How to get a Compare items in a Generic List
[ "", "c#", "" ]
When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps. ``` uint z = -1; // Will not compile uint a = 5; uint b = 6; uint c = a - b; // W...
Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration: ``` uint z; ``` -1 isn't a valid value for a uint any more than 0.5 is, which is why your ex...
The wrapping is because by dfault C# is unchecked. If you add a "checked" block, the overflow will be detected: ``` uint a = 3, b = 4; checked { uint c = a - b; // throws an overflow } ``` As for the compiler: it simply demands valid data.
Difference of two 'uint'
[ "", "c#", ".net", "" ]
What are Null Pointer Exceptions (`java.lang.NullPointerException`) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
There are two overarching types of variables in Java: 1. *Primitives*: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type `int` or `char` are primit...
`NullPointerException`s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a `NullPointerException`. These are the most common, bu...
What is a NullPointerException, and how do I fix it?
[ "", "java", "nullpointerexception", "" ]
What's the advantage of passing data as parameters vs part of the URL in an Ajax GET request? Using parameters: ``` var ajax = new Ajax.Request('server.php',{ parameters: 'store=11200&product=Meat', onSuccess: function(myData){whatever} }); ``` Using URL: ``` var ajax = new Ajax.Request('server.php?store=11...
One advantage to using the `parameters` argument is that you can pass it a `Hash`-like object instead of as a string. (If you do this, though, make sure so set the `method` parameter to `"GET"`, as the default method for Prototype Ajax requests is POST; see [the Prototype Introduction to Ajax](http://www.prototypejs.or...
One of my favorite uses of **parameters** is to pass in all fields of a form without explicitly listing them: ``` new Ajax.Request('/myurl.php', { method: 'get', parameters: $('myForm').serialize(), onSuccess: successFunc(), onFailure: failFunc() } ```
Ajax GET requests: use parameters or put data in URL?
[ "", "javascript", "ajax", "prototypejs", "" ]
Using jQuery, how would you `show()` every `div.foo` on a page in a random order, with a new one appearing every X milliseconds? **Clarification**: I want to start with all these elements hidden and end with all of them showing, so it wouldn't make sense to `show()` the same element twice. I originally thought I'd ma...
An interesting way to do this would be the extend Javascript's Array base object with a shuffle function. In Prototype (should be the same in JQuery, except jQuery.extend). This is quick and dirty shuffle, there are plenty of other ways to do it. ``` Object.extend(Array.prototype, { shuffle : function() { this.s...
I don't use jQuery myself, but what about this: ``` var intervalMilliseconds = X; // set to your value for X var divFoos = $("div.foo").get(); var intervalId = setInterval(function() { $(divFoos.splice(Math.floor(Math.random() * divFoos.length), 1)).show(); if(divFoos.length == 0) clearInterval(intervalId); }, i...
How can I randomly show a set of elements using jQuery?
[ "", "javascript", "jquery", "" ]
When a user clicks a link to download a file on my website, they go to [this PHP file](http://viewsourcecode.org/viewsource/homebrew.php) which increments a download counter for that file and then header()-redirects them to the actual file. I suspect that bots are following the download link, however, so the number of ...
robots.txt: <http://www.robotstxt.org/robotstxt.html> Not all bots respect it, but most do. If you really want to prevent access via bots, make the link to it a POST instead of a GET. Bots will not follow POST urls. (I.E., use a small form that posts back to the site that takes you to the URL in question.)
I would think Godeke's robots.txt answer would be sufficient. If you absolutely cannot have the bots up your counter, then I would recommend using the robots file in conjunction with not not incrementing the clicks with some [common robot user agents](http://support.free-conversant.com/2701). Neither way is perfect., ...
How do I stop bots from incrementing my file download counter in PHP?
[ "", "php", "bots", "" ]
After much searching, I found the download for the [eclipse version of jalopy](http://sourceforge.net/project/showfiles.php?group_id=45216). Is this compatible with Eclipse 3.4? It's dated 2006. I've copied the extracted folder to my plugins directory and run `eclipse -clean`, but I can't find anything matching 'jalop...
Just an update: Note: the latest eclipse3.5 Galileo [code formatter](http://help.eclipse.org/galileo/topic/org.eclipse.jdt.doc.user/tasks/tasks-230.htm) now: * supports most of Jalopy formatting option. * has made quite a few improvement on formatters (look for the term 'formatter' in those [building notes of jdt-cor...
i'm told that open source version of jalopy is not for commercial use. eclipse itself has good source code formatting capabilities. Go to java | preferences/settings. type format and you should see the various options.
Is the Open Source Jalopy Eclipse plugin compatible with Ganymede?
[ "", "java", "eclipse-plugin", "code-formatting", "eclipse-3.4", "jalopy", "" ]
The most favorite feature of StackOverflow for me is that it can automatically detect code in post and set appropriate color to the code. I'm wondering how the color is set. When I do a `Ctrl`+`F5` on a page, the code seems first be black text, then change to be colorful. Is it done by jQuery?
In reply to.. > Spolsky: How do they know, how do they even know what language you're writing in? It doesn't. The highlighter is very dumb, but manages to gets away with it because most programming languages are so similar. Nearly everything uses syntax close-enough to.. ``` AFunction("a string") 1 + 4 # <- numbers ...
From [Stack Overflow Podcast #11](https://stackoverflow.fogbugz.com/default.asp?W12621): > **Atwood:** It is. Okay, so that comes from, that's a project some Google engineer, I think, wrote it--it's called "Prettify." And it's a little interesting in that it actually infers all the syntax highlighting, which sounds li...
How Code Color is Set in StackOverflow?
[ "", "javascript", "syntax-highlighting", "" ]
I have a `Person` model that has a foreign key relationship to `Book`, which has a number of fields, but I'm most concerned about `author` (a standard CharField). With that being said, in my `PersonAdmin` model, I'd like to display `book.author` using `list_display`: ``` class PersonAdmin(admin.ModelAdmin): list_...
As another option, you can do lookups like: ``` #models.py class UserAdmin(admin.ModelAdmin): list_display = (..., 'get_author') def get_author(self, obj): return obj.book.author get_author.short_description = 'Author' get_author.admin_order_field = 'book__author' ``` Since Django 3.2 you...
Despite all the great answers above and due to me being new to Django, I was still stuck. Here's my explanation from a very newbie perspective. **models.py** ``` class Author(models.Model): name = models.CharField(max_length=255) class Book(models.Model): author = models.ForeignKey(Author) title = models...
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
[ "", "python", "django", "django-models", "django-admin", "modeladmin", "" ]
How do I list and export a private key from a keystore?
A portion of code originally from Example Depot for listing all of the aliases in a key store: ``` // Load input stream into keystore keystore.load(is, password.toCharArray()); // List the aliases Enumeration aliases = keystore.aliases(); for (; aliases.hasMoreElements(); ) { String alias ...
You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use `keytool` to convert to the standard format. Make sure you ***use the same password for both files (private key password,...
How do I list / export private keys from a keystore?
[ "", "java", "ssl", "keystore", "" ]
I'm trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two approaches that provide the information I need. **Approach 1:** ``` SELECT COUNT( my_table.my_col ) AS row_count FROM my_table WHERE my_table.foo =...
There are only two ways to be 100% certain that the `COUNT(*)` and the actual query will give consistent results: * Combined the `COUNT(*)` with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus. * Use two queries, as in yo...
If you're using SQL Server, after your query you can select the [@@RowCount](https://learn.microsoft.com/en-us/sql/t-sql/functions/rowcount-transact-sql) function (or if your result set might have more than 2 billion rows use the [RowCount\_Big()](https://learn.microsoft.com/en-us/sql/t-sql/functions/rowcount-big-trans...
Need a row count after SELECT statement: what's the optimal SQL approach?
[ "", "sql", "odbc", "sqlncli", "" ]
I am currently running gdb version 6.7.1 on Ubuntu Linux, and working in a C++ project. Surprisingly I was trying to debug a constructor and I have found that local variables declared within the scope of the constructor are not followed or noticed by gdb. Is this a bug ? Thanks for any information ..
It is a [bug](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27574) in GCC, not in GDB. It was recently [fixed](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27574#c21).
If you are using optimization (-O), disable it (remove the -O or use -O0). The compiler is sometimes too smart and guesses a variable it not needed, do calculations at compile time, change a variable's scope, or several other tricks. Note that even with "no optimization", some trivial optimizations are still done, but...
local variables in constructors are not followed. Is this a bug in gdb ?
[ "", "c++", "debugging", "gdb", "" ]
I'm a C/C++ developer, and here are a couple of questions that always baffled me. * Is there a big difference between "regular" code and inline code? * Which is the main difference? * Is inline code simply a "form" of macros? * What kind of tradeoff must be done when choosing to inline your code? Thanks
> * Is there a big difference between "regular" code and inline code? Yes and no. No, because an inline function or method has exactly the same characteristics as a regular one, most important one being that they are both type safe. And yes, because the assembly code generated by the compiler will be different; with a...
## Performance As has been suggested in previous answers, use of the `inline` keyword can make code faster by inlining function calls, often at the expense of increased executables. “Inlining function calls” just means substituting the call to the target function with the actual code of the function, after filling in ...
Why should I ever use inline code?
[ "", "c++", "optimization", "inline-functions", "tradeoff", "" ]
I have numerous Web Services in my project that share types. For simplicity I will demonstrate with two Web Services. WebService1 at <http://MyServer/WebService.asmx> webService2 at <http://MyServer/WebService.asmx> When I generate the proxy for these two services I use: wsdl /sharetypes <http://MyServer/WebService...
The proxy classes generated are partial classes, so my solution would be to add your own constructor in a different (non-generated) code file, which explicitly reads a different setting for each proxy.
To suplement Elijah's own answer, here's the email answer I gave him. I had to blog it because the XML didn't paste well into this text box: <http://www.rickdoes.net/blog/archive/2008/09/29/wsdl-shared-types-and-configuration.aspx>
Defaulting to different URLs when Generating Web Service Proxy with WSDL.exe
[ "", "c#", "asp.net", "web-services", "wsdl", "" ]
The first one is definitely something that works, but which one below is the efficient way? ``` switch($type) { case 1: print 'success'; break; case 2: print 'success'; break; case 3: print 'success'; break; case 4: print 'success for type 4'; break; }...
``` switch($type) { case 1: case 2: case 3: print 'success'; break; case 4: print 'success for type 4'; break; } ``` Is the way to go!
PHP manual lists an example like your 3rd for [switch](https://www.php.net/manual/en/control-structures.switch.php): ``` <?php switch ($i) { case 0: case 1: case 2: echo "i is less than 3 but not negative"; break; case 3: echo "i is 3"; } ?> ```
Can I have multiple cases that do the same thing?
[ "", "php", "switch-statement", "" ]
I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script: ``` import commands command...
Have a look at the [pexpect](http://www.noah.org/wiki/Pexpect) module. It is designed to deal with interactive programs, which seems to be your case. Oh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D
Use [subprocess](http://www.python.org/doc/2.5.2/lib/module-subprocess.html). Call Popen() to create your process and use communicate() to send it text. Sorry, forgot to include the PIPE.. ``` from subprocess import Popen, PIPE proc = Popen(['server', 'stop'], stdin=PIPE) proc.communicate('password') ``` You would ...
Make python enter password when running a csh script
[ "", "python", "scripting", "passwords", "root", "csh", "" ]
What MySQL query will do a text search and replace in one particular field in a table? I.e. search for `foo` and replace with `bar` so a record with a field with the value `hello foo` becomes `hello bar`.
Change `table_name` and `field` to match your table name and field in question: ``` UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0; ``` * [REPLACE](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace) (string functions) * [INSTR](https://dev.mysql.c...
``` UPDATE table_name SET field = replace(field, 'string-to-find', 'string-that-will-replace-it'); ```
MySQL search and replace some text in a field
[ "", "mysql", "sql", "search", "replace", "" ]
Lets just say you have a table in Oracle: ``` CREATE TABLE person ( id NUMBER PRIMARY KEY, given_names VARCHAR2(50), surname VARCHAR2(50) ); ``` with these function-based indices: ``` CREATE INDEX idx_person_upper_given_names ON person (UPPER(given_names)); CREATE INDEX idx_person_upper_last_name ON person (UP...
The index can be used, though the optimiser may have chosen not to use it for your particular example: ``` SQL> create table my_objects 2 as select object_id, object_name 3 from all_objects; Table created. SQL> select count(*) from my_objects; 2 / COUNT(*) ---------- 83783 SQL> alter table my_obje...
In your example you've created the same index twice - this would give an error so I'm assuming that was a mistake in pasting, not the actual code you tried. I tried it with ``` CREATE INDEX idx_person_upper_surname ON person (UPPER(surname)); SELECT * FROM person WHERE UPPER(surname) LIKE 'P%'; ``` and it produced ...
How to use a function-based index on a column that contains NULLs in Oracle 10+?
[ "", "sql", "oracle", "" ]
Whenever I start our Apache Felix (OSGi) based application under SUN Java ( build 1.6.0\_10-rc2-b32 and other 1.6.x builds) I see the following message output on the console (usually under Ubuntu 8.4): > Warning: The encoding 'UTF-8' is not supported by the Java runtime. I've seen this message display occasionally wh...
According [the documentation](http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html) "Every implementation of the Java platform is required to support the following standard charsets... US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16." So I doubt that Sun have released a build without UTF-8 suppor...
Try the following program: ``` import java.nio.charset.Charset; public class TestCharset { public static void main(String[] args) { System.out.println(Charset.forName("UTF-8")); } } ``` If this throws an exception, then there is something wrong with your JDK. If it prints "UTF-8" then your JDK is OK,...
The encoding 'UTF-8' is not supported by the Java runtime
[ "", "java", "linux", "unicode", "" ]
I'd like to know which method is recommended on Windows C programming: using malloc or the Win32 HeapAlloc (maybe VirtualAlloc?) function. I've read the MSDN [Memory Management Functions](http://msdn.microsoft.com/en-us/library/aa366781(VS.85).aspx) article and the MSDN articles regarding malloc and HeapAlloc, but the...
Stick with malloc unless you have a compelling reason to use something different. It will be implemented underneath in terms of the OS memory allocation primitives, but there is no real advantage in diving down to that layer yourself. A few API calls I believe need a memory block allocated from a Windows heap, but you...
VirtualAlloc and friends can give you a bit of an edge if you do have heaps of data to process or if you need to go to the trouble of creating your own memory manager anyway. Otherwise it's easier and of course more portable to just use malloc(). VirtualAlloc has this nifty feature called MEM\_RESET, which invalidate...
Memory allocation on Windows C code
[ "", "c++", "c", "malloc", "virtualalloc", "heapalloc", "" ]
Looking through some code I came across the following code ``` trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto)); ``` and I'd like to know if casting this way has any advantages over ``` trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto); ``` I've asked the developer responsible and he said he use...
These statements are not identical. The cast method is a normal method invocation (`invokevirtual` JVM instruction) while the other is a language construct (`checkcast` instruction). In the case you show above, you should use the second form: `(TrTuDocPackTypeDto) packDto` The `cast` method is used in reflective progr...
The main case for doing it (IME) is when you need to safely cast in a generic class/method. Due to type erasure, you can't cast to `T` but if you've been provided a `Class<? extends T>` parameter then you can use that to cast and the result will be assignable to a variable of type `T`.
When should I use the java 5 method cast of Class?
[ "", "java", "java-5", "" ]
I'm trying to work through Project Euler and I'm hitting a barrier on problem 03. I have an algorithm that works for smaller numbers, but problem 3 uses a very, very large number. **Problem 03:** The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? Here is my so...
For starters, instead of beginning your search at n / 2, start it at the square root of n. You'll get half of the factors, the other half being their complement. eg: ``` n = 27 start at floor(sqrt(27)) = 5 is 5 a factor? no is 4 a factor? no is 3 a factor? yes. 27 / 3 = 9. 9 is also a factor. is 2 a factor? no. facto...
Although the question asks for the *largest* prime factor, it doesn't necessarily mean you have to find that one first...
Project Euler Question 3 Help
[ "", "c#", "algorithm", "language-agnostic", "primes", "" ]
Is there a way to get the Unicode Block of a character in python? The [unicodedata](http://www.python.org/doc/2.5.2/lib/module-unicodedata.html) module doesn't seem to have what I need, and I couldn't find an external library for it. Basically, I need the same functionality as [`Character.UnicodeBlock.of()`](http://ja...
I couldn't find one either. Strange! Luckily, the number of Unicode blocks is quite manageably small. This implementation accepts a one-character Unicode string, just like the functions in `unicodedata`. If your inputs are mostly ASCII, this linear search might even be faster than binary search using `bisect` or what...
``` pip install unicodeblock ``` A third-party library [UnicodeBlock](https://github.com/neuront/pyunicodeblock) does this. Here is an example from their page: ``` >>> import unicodeblock.blocks >>> print(unicodeblock.blocks.of('0')) DIGIT >>> print(unicodeblock.blocks.of('汉')) CJK_UNIFIED_IDEOGRAPHS >>> print(unicod...
Unicode block of a character in python
[ "", "python", "unicode", "character-properties", "" ]
Is there a library method to copy all the properties between two (already present) instances of the same class, in Python? I mean, something like Apache Commons' `PropertyUtilsBean.copyProperties()`
If your class does not modify `__getitem__` or `__setitem__` for special attribute access all your attributes are stored in `__dict__` so you can do: ``` nobj.__dict__ = oobj.__dict__.copy() # just a shallow copy ``` If you use python properties you should look at `inspect.getmembers()` and filter out the ones yo...
Try `destination.__dict__.update(source.__dict__)`.
How to copy all properties of an object to another object, in Python?
[ "", "python", "" ]
Is there a case insensitive version of the [:contains](http://docs.jquery.com/Selectors/contains) jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?
What I ended up doing for jQuery 1.2 is : ``` jQuery.extend( jQuery.expr[':'], { Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0" }); ``` This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged. Edit: For jQuery 1...
To make it optionally case insensitive: <http://bugs.jquery.com/ticket/278> ``` $.extend($.expr[':'], { 'containsi': function(elem, i, match, array) { return (elem.textContent || elem.innerText || '').toLowerCase() .indexOf((match[3] || "").toLowerCase()) >= 0; } }); ``` then use `:containsi` instead of...
Is there a case insensitive jQuery :contains selector?
[ "", "javascript", "jquery", "jquery-selectors", "" ]
How do I extend my parent's options array for child classes in PHP? I have something like this: ``` class ParentClass { public $options = array( 'option1'=>'setting1' ); //The rest of the functions would follow } ``` I would like to append to that options array in a child class without era...
I think it is better practice to initialize this property in the constructor and then you can extend the value in any descendant class: ``` <?php class ParentClass { public $options; public function __construct() { $this->options = array( 'option1'=>'setting1' ); } //The re...
PHP or no, you should have an accessor to do it, so you can call `$self->append_elements( 'foo' => 'bar' );` and not worry about the internal implementation.
Appending to an array variable in a parent class in PHP
[ "", "php", "oop", "" ]
I have an img tag in my webapp that uses the onload handler to resize the image: ``` <img onLoad="SizeImage(this);" src="foo" > ``` This works fine in Firefox 3, but fails in IE7 because the image object being passed to the `SizeImage()` function has a width and height of 0 for some reason -- maybe IE calls the funct...
IE7 is trying to resize the image before the DOM tree is fully rendered. You need to run it on document.onload... you'll just need to make sure your function can handle being passed a reference to the element that isn't "this." Alternatively... and I hope this isn't a flameable offense... jQuery makes stuff like this ...
If you don't have to support IE 6, you can just use this CSS. ``` yourImageSelector { max-width: 150px; max-height: 150px; } ```
img onload doesn't work well in IE7
[ "", "javascript", "html", "internet-explorer", "image", "" ]
I am currently writing a little bootstrap code for a service that can be run in the console. It essentially boils down to calling the OnStart() method instead of using the ServiceBase to start and stop the service (because it doesn't run the application if it isn't installed as a service and makes debugging a nightmare...
Like Ash, I write all actual processing code in a separate class library assembly, which was then referenced by the windows service executable, as well as a console app. However, there are occasions when it is useful to know if the class library is running in the context of the service executable or the console app. T...
Another workaround.. so can run as WinForm or as windows service ``` var backend = new Backend(); if (Environment.UserInteractive) { backend.OnStart(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Fronend(backend)); backend.OnStop...
Am I Running as a Service
[ "", "c#", ".net", "windows-services", "" ]
I'm working on a project where I have 2 web services that need the same entity. The 2 web services are on the same server so on the back-end, they share the same classes. On the front-end side, my code consumes *both* web services and sees the entities from both services as separate (in different namespaces) so I can'...
I think that you can not do that from inside VS but you can manually use the `wsdl.exe` utility like this: ``` wsdl.exe /sharetypes http://localhost/MyService1.asmx?wsdl http://localhost/MyService2.asmx?wsdl ``` Notice the `/sharetypes` option which turns on the type sharing feature. This feature creates one code fil...
I'm not sure about the implementation details with .NET 2.0, but I believe what you want to do is put the common classes in a seperate XSD file and refer to it from within your two WSDL's. This way, the common types have the same namespace between the two services. Now, how you do this in .NET 2.0 I couldn't give you ...
One entity shared across two web services?
[ "", "c#", ".net", "web-services", "wsdl", "" ]
I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two: ``` >>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c) # ...
A generator will solve your problem nicely. ``` def imerge(a, b): for i, j in itertools.izip(a,b): yield i yield j ```
You can do something that is almost exaclty what @Pramod first suggested. ``` def izipmerge(a, b): for i, j in itertools.izip(a,b): yield i yield j ``` The advantage of this approach is that you won't run out of memory if both a and b are infinite.
How do I merge two python iterators?
[ "", "python", "merge", "iterator", "" ]
A co worker of mine asked me to review some of my code and he sent me a diff file. I'm not new to diffs or version control in general but the diff file was very difficult to read because of the changes he made. Specifically, he used the "extract method" feature and reordered some methods. Conceptually, very easy to und...
Eclipse can [export refactoring history](http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/tasks-240.htm) (see [3.2 release notes](http://mirror.calvin.edu/eclipse/downloads/drops/S-3.2M5-200602171115/eclipse-news-M5.html) as well). You could then view the refactoring changes via preview in...
I don't know of compare tools that do a good job when the file has been rearranged. In general, this is a bad idea because of this type of problem. All too often people do it to simply meet their own style, which is a bad, bad reason to change code. It can effectively destroy the history, just like reformatting the ent...
Refactoring Nicely with Version Control
[ "", "java", "eclipse", "svn", "version-control", "" ]
Converting a couple stored procedures from MySQL to Microsoft SQL server. Everything is going well, except one procedure used the MySQL `SHA1()` function. I cannot seem to find an equivalent to this in MS-SQL. Does anyone know a valid equivalent for `SHA1()` on MS-SQL?
SQL Server 2005 and later has the [HashBytes()](http://msdn.microsoft.com/en-us/library/ms174415.aspx) function.
If you want to get a SHA1 hash exactly as MySQL would generate it (i.e. as a varchar), you can combine HashBytes with sys.fn\_varbintohexsubstring. E.g. ``` SELECT sys.fn_varbintohexsubstring(0, HashBytes('SHA1', 'password'), 1, 0) ``` See <http://accessrichard.blogspot.co.nz/2010/12/sql-server-and-net-equivalent-to-...
Is there an equivalent to SHA1() in MS-SQL?
[ "", "sql", "mysql", "sha1", "t-sql", "sql-server", "" ]
Besides the CODEX what resources do you recommend to help a person new to creating plugins help create a WordPress plugin. I have an idea, but need a bit better explanation than what is in the CODEX to get started. UPDATE: Is there a book that I could buy to help me out with this?
Having written the MyBlogLog plugin (the original one, that is) I found that the Wordpress Hooks list (can't remember the link offhand) was incredibly useful, as was the sample code from the Codex and WP Install files. Reading through other developer's plugins is also a good way to learn, as you can see how they implem...
Here is a [useful set of links](http://www.devlounge.net/extras/how-to-write-a-wordpress-plugin) on how to do Wordpress plugins. Be aware that it is relatively "advanced" (in that it introduces a number of object oriented methods to the process). You should really read the Wordpress Codex stuff first.
WordPress Plugin Development
[ "", "php", "wordpress", "plugins", "resources", "" ]
I was helping out some colleagues of mine with an SQL problem. Mainly they wanted to move all the rows from table A to table B (both tables having the same columns (names and types)). Although this was done in Oracle 11g I don't think it really matters. Their initial naive implementation was something like ``` BEGIN ...
Depending on your isolation level, selecting all the rows from a table does not prevent new inserts, it will just lock the rows you read. In SQL Server, if you use the Serializable isolation level then it will prevent new rows if they would have been including in your select query. <http://msdn.microsoft.com/en-us/lib...
I can't speak to the transaction stability, but an alternate approach would be to have the second step delete from the source table where exists (select ids from target table). Forgive the syntax, I have not tested this code, but you should be able to get the idea: ``` INSERT INTO B SELECT * FROM A; DELETE FROM A WH...
transaction isolation problem or wrong approach?
[ "", "sql", "sql-server", "oracle", "transactions", "database", "" ]
I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project. this forum thread [IDataObject : ambiguous symbol error](http://www.daniweb.com/forums/thread29742.html) answers a problem I've seen multiple times. Post #4 states "Move all 'using namespace XXXX'...
It's a good idea to always use fully qualified names in header files. Because the `using` statement affects all following code regardless of `#include`, putting a `using` statement in a header file affects everybody that might include that header. So you would change your function declaration in your header file to: ...
In my experience the only namespace you have to be careful about is System itself. It's somewhat annoying that the most common, most important one is where you find problems, but that's life. At least you can take comfort that if you're creating managed classes, you're issues with includes will get relief at the assem...
How to order headers in .NET C++ projects
[ "", ".net", "c++", "reference", "header", "" ]
Does the placement of a function have an effect on the performance of closures within scope? If so, where is the optimal place to put these functions? If not, is the implied association by closure enough reason to place a function in another place logically? For instance, if **foo** does not rely on the value of **loc...
Every function in Javascript is a closure. The runtime to resolve a variable's value is only incurred if the variable is referenced by the function. For instance, in this example function y captures the value of x even though x is not referenced directly by y: ``` var x = 3; function y() eval("x"); y(); 3 ```
Both those snippets are equivalent, because they're both defined in the (same) environment of the anonymous function you're creating. I think you'd be able to access `localState` from `foo` either way. That being said... if you have absurd amounts of variables in the environment you're creating, then `foo`'s execution...
javascript closures and function placement
[ "", "javascript", "performance", "coding-style", "structure", "closures", "" ]
I have a variable that is built in loop. Something like: ``` $str = ""; for($i = 0; $i < 10; $i++) $str .= "something"; ``` If $str = "" is ommitted, I get undefined variable notice, but I thought php auto-declare a variable the first time it sees undeclared one? How do I do this right?
You get the undefined variable because you're concatenating the value of itself with another value. The equivalent of > `$str = $str . "something";` So, it can't say what's the initial value is. It's the equivalent of this: > `$str = [undefined value] . "something";` What's the result of a concatenation of `[undef...
If you really need to make it a it cleaner you could do: ``` for($i = 0, $str = ''; $i < 10; $i++) $str .= "something"; ``` But what you have is what I normally do. vlceBerg explains it well.
PHP: Right way to declare variable before use in loop
[ "", "php", "performance", "loops", "" ]
### The situation When you study social sciences, you are frequently confronted with the need for online surveys (scientific data collection online). That's one of the main reasons why I started with **PHP** in the first place. Recently these survey applications have grown and grown. A **lot of complexity** has been ...
> is PHP/mysql still a way to go? Yes, PHP/MYSQL (LAMP) has been successfully used in hundreds of sites with exponentially larger user bases than yours. > could a framework like codeIgnitor be a basis for such an application or should I develop everything from the scratch? Nontrivial PHP sites built without a framew...
PHP/mysql should be fine for this scale, but you must tune it and give it sufficient resources. For example, if your schema is not thought out, you'll hit all sorts of performance walls. How your data is stored and indexed is probably the most important factor for the performance of reports. I've had 60-100gb of data ...
Large custom survey / reporting applications - best practice
[ "", "php", "reporting", "scaling", "survey", "" ]
I'm a jQuery novice, so the answer to this may be quite simple: I have an image, and I would like to do several things with it. When a user clicks on a 'Zoom' icon, I'm running the 'imagetool' plugin (<http://code.google.com/p/jquery-imagetool/>) to load a larger version of the image. The plugin creates a new div arou...
Wehey! I've sorted it out myself... Turns out if I remove the containing div completely, and then rewrite it with .html, the imagetool plugin recognises it again. Amended code for anyone who's interested: ``` $(document).ready(function(){ // Product Zoom (jQuery) $("#productZoom").click(function() { $('#pr...
You could try abstracting the **productZoom.click()** function to a named function, and then re-binding it after changing to an alternate image. Something like: ``` // Product Zoom (jQuery) $(document).ready(function(){ $("#productZoom").click(bindZoom); // Alternative product photos (jQuery) $(".altPhoto").click(fun...
jQuery - running a function on a new image
[ "", "javascript", "jquery", "zooming", "" ]
Even nowadays I often see underscores in Java variables and methods. An example are member variables (like "m\_count" or "\_count"). As far as I remember, to use underscores in these cases is called bad style by [Sun](https://en.wikipedia.org/wiki/Sun_Microsystems). The only place they should be used is in constants (...
If you have no code using it now, I'd suggest continuing that. If your codebase uses it, continue that. The biggest thing about coding style is *consistency*. If you have nothing to be consistent with, then the language vendor's recommendations are likely a good place to start.
``` sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs(); as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable(); ```
Using underscores in Java variables and method names
[ "", "java", "naming-conventions", "" ]
I'm using a third-party library that returns "XML" that is not valid, because it contains invalid characters, as well as non-declared entities. I need to use a Java XML parser to parse this XML, but it's choking. Is there a generic way to sanitize this XML so that it becomes valid?
I think your options are something like: * [Tag Soup](http://home.ccil.org/~cowan/XML/tagsoup/) * [JTidy](http://jtidy.sourceforge.net/) * Roll your own. The first two are more heavyweight, given that they're designed to parse ill formed HTML. If you know that the problems are due to encoding and entities, but otherw...
Sounds like you need to figure out if there's a way to automatically clean the data yourself before handing off to a parser. How are certain characters invalid, not valid in the declared character set, or unescaped XML meta-characters such as '<'? For non-declared entities, I once solved this by configuring a SAX pars...
Sanitizing bad XML in Java
[ "", "java", "xml", "" ]
I have a lot of Java source code that requires custom pre-processing. I'd like rid of it but that's not feasible right now so I'm stuck with it. Given that I have an unfortunate problem that shouldn't have existed in the first place, how do I solve it using maven? (For the full story, I'm replacing a python-based buil...
This is something that is very doable and I've done something very similar in the past. An example from a project of mine, where I used the antrun plug-in to execute an external program to process sources: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven...
There is a Java preprocessor with support of MAVEN: [java-comment-preprocessor](https://github.com/raydac/java-comment-preprocessor)
Preprocessing source code as a part of a maven build
[ "", "java", "maven-2", "build-process", "" ]
I'm trying to use ASP.net health monitoring to log unhandled exceptions from an asmx web service. I've enabled health monitoring in the web.config but it's not logging anything. Does health monitoring work with asmx web services? I've googled around and seems other people have asked the same question but never got a de...
Please do not post a response unless it answers the question being asked. Half answers to something other than the question confuses the reader. Health monitoring has nothing to do with either "really unhandled" ASP.NET exceptions or the Application\_Error event. The answer is no. I have digged this a bit and for some...
There's a difference between the normal interpretation of unhandled exceptions, and those Tom are referring to. What Tom is referring to are truly unhandled exceptions, that will kill your w3wp.exe process (before it has a chance to log it), as I've blogged about here: <http://www.improve.dk/blog/2008/04/07/spawning-th...
Does ASP.net health monitoring work with asmx web services
[ "", "c#", "asp.net", "asmx", "health-monitoring", "" ]
What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python? Thus far I've tried ``` target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) ``` This gives me data but its garbled or wont play in mp3 players.
If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening `target` in binary mode: ``` target = open(target_path, "wb") ```
The best way for this is: ``` urllib.urlretrieve(stream_url, target_path); ```
How do I capture an mp3 stream with python
[ "", "python", "streaming", "" ]
Replaces Question: [Update multiple rows into SQL table](https://stackoverflow.com/questions/184096/update-multiple-rows-into-sql-table) Here's a Code Snippet to update an exam results set. DB structure is as given, but I can submit Stored Procedures for inclusion (Which are a pain to modify, so I save that until the ...
A few things stand out: * You don't show where the SqlConnection is instantiated, so it's not clear that you're disposing it properly. * You shouldn't be swallowing exceptions in the loop - better to handle them in a top level exception handler. * You're instantiating new parameters on each iteration through the loop ...
For 30 updates I think you're on the right track, although the comment about the need for a using around `updateCommand` is correct. We've found the best performing way to do bulk updates (>100 rows) is via the `SqlBulkCopy` class to a temporary table followed by a stored procedure call to populate the live table.
Multiple DB Updates:
[ "", "c#", ".net", "sql-server", "" ]
Which Eclipse package should I choose for Python development with [PyDev](http://www.pydev.org/)? Nothing on the Eclipse homepage tells me what to choose, and the PyDev documentation assumes I already have Eclipse installed. Does it matter which Eclipse package I choose?
If you just plan on doing Python dev, I'd just go with [Platform Runtime Binary](http://download.eclipse.org/eclipse/downloads/). After that, I'd follow the instructions <http://pydev.org/download.html> and <http://pydev.org/manual_101_root.html> to install PyDev. I use the same setup for Python development. I also h...
PyDev was acquired by [Aptana](http://www.aptana.com), so you might want to check that one out as well.
Which Eclipse package should I download for PyDev?
[ "", "python", "eclipse", "package", "pydev", "" ]
Sometimes you need to skip execution of part of a method under certain non-critical error conditions. You can use *exceptions* for that, but exceptions generally are not recommended in normal application logic, only for abnormal situations. So I do a trick like this: ``` do { bool isGood = true; .... some code...
Bad practice, it depends. What I see in this code is a very creative way to write "goto" with less sulphur-smelling keywords. There are multiple alternatives to this code, which can or can not be better, depending on the situation. ## Your do/while solution Your solution is interesting if you have a lot of code, bu...
You're pretty much just disguising a "goto" as a fake loop. Whether you like gotos or not, you'd be just as far ahead using a real undisguised goto. Personally, I'd just write it as ``` bool isGood = true; .... some code if(isGood) { .... some more code } if(isGood) { .... some more code ...
Do you consider this technique "BAD"?
[ "", "c++", "coding-style", "" ]
I know you can use C++ keyword 'explicit' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion of parameters for a class method? I have two class members, one which takes a bool as a param, the other an unsigned int. When I called the function ...
No, you can't use explicit, but you can use a templated function to catch the incorrect parameter types. With **C++11**, you can declare the templated function as `delete`d. Here is a simple example: ``` #include <iostream> struct Thing { void Foo(int value) { std::cout << "Foo: value" << std::endl; ...
No. `explicit` prevents automatic conversion between specific classes, irrespective of context. And of course you can't do it for built-in classes.
Can you use keyword explicit to prevent automatic conversion of method parameters?
[ "", "c++", "implicit-conversion", "explicit", "" ]
When I create a zip Archive via `java.util.zip.*`, is there a way to split the resulting archive in multiple volumes? Let's say my overall archive has a `filesize` of `24 MB` and I want to split it into 3 files on a limit of 10 MB per file. Is there a zip API which has this feature? Or any other nice ways to achieve...
Check: <http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=38&t=004618> *I am not aware of any public API that will help you do that. (Although if you do not want to do it programatically, there are utilities like WinSplitter that will do it)* *I have not tried it but, every ZipEntry while using Z...
If the goal is to have the output be compatible with pkzip and winzip, I'm not aware of any open source libraries that do this. We had a similar requirement for one of our apps, and I wound up writing our own implementation (compatible with the zip standard). If I recall, the hardest thing for us was that we had to gen...
How to split a huge zip file into multiple volumes?
[ "", "java", "zip", "" ]
Part of my latest webapp needs to write to file a fair amount as part of its logging. One problem I've noticed is that if there are a few concurrent users, the writes *can* overwrite each other (instead of appending to file). I assume this is because of the destination file can be open in a number of places at the same...
Another dirty hack would be to `flock()` a "local" file, and only open / write to the NFS file if you hold the lock on the local file. Edit: from the `flock()` page: > flock() will not work on NFS and many > other networked file systems. Check > your operating system documentation > for more details. Edit 2: Of cou...
Directory operations are *NOT* atomic under NFSv2 and NFSv3 (please refer to the book 'NFS Illustrated' by Brent Callaghan, ISBN 0-201-32570-5; Brent is a NFS-veteran at Sun). NFSv2 has two atomic operations: * symlink * rename With NFSv3 the create call is also atomic. Knowing this, you can implement spin-locks fo...
Locking NFS files in PHP
[ "", "php", "concurrency", "" ]
I display data into an html table, w/ a drop down box with a list of venues. Each volunteer will be assigned a venue. I envision being able to go down thru the html table and assigning each volunteer a venue. The drop down box contains all the possible venues that they can be assigned to. ``` <select> <option value="1...
Change the name of each select, in a way it includes a volunteer id: ``` <select name="venues[1]"> <option value="1">Setup</option> etc... </select> <select name="venues[2]"> <option value="1">Setup</option> etc... </select> <select name="venues[3]"> <option value="1">Setup</option> etc... </select> ``` After submi...
Here's a very rough example of how you might handle this. Note: your MySQL tables (assuming MySQL) must be of a type that supports transactions (InnoDB does, MyISAM does not). ``` <?php if ( isset( $_POST['venuChoice'] ) ) { // Create a transaction mysql_query( 'BEGIN' ); $failure = false; // Loop...
enter multiple variables into table, assigning to each appropriate record
[ "", "php", "mysql", "" ]
I would like to know what is the difference between initializing a static member inline as in: ``` class Foo { private static Bar bar_ = new Bar(); } ``` or initializing it inside the static constructor as in: ``` class Foo { static Foo() { bar_ = new Bar(); } private static Bar bar_; } `...
If you have a static constructor in your type, it alters type initialization due to the [beforefieldinit](http://pobox.com/~skeet/csharp/beforefieldinit.html) flag no longer being applied. It also affects initialization order - variable initializers are all executed before the static constructor. That's about it as f...
In this case I don't believe there si any practical difference. If you need some logic in initializing the static variables - like if you would want to use different concrete types of an interface given different conditions - you would use the static constructor. Else, the inline initialization is fine in my book. ```...
Difference initializing static variable inline or in static constructor in C#
[ "", "c#", ".net", "static", "constructor", "initialization", "" ]
I currently capture MiniDumps of unhandled exceptions using `SetUnhandledExceptionFilter` however at times I am getting "R6025: pure virtual function". I understand how a pure virtual function call happens I am just wondering if it is possible to capture them so I can create a MiniDump at that point.
If you want to catch all crashes you have to do more than just: SetUnhandledExceptionFilter I would also set the abort handler, the purecall handler, unexpected, terminate, and invalid parameter handler. ``` #include <signal.h> inline void signal_handler(int) { terminator(); } inline void terminator() { in...
See [this answer here](https://stackoverflow.com/questions/99552/where-do-pure-virtual-function-call-crashes-come-from#100555) to the question [where do “pure virtual function call” crashes come from?](https://stackoverflow.com/questions/99552/where-do-pure-virtual-function-call-crashes-come-from). > To help with debu...
Capturing R6025 pure virtual call
[ "", "c++", "windows", "minidump", "dbghelp", "" ]
Is it possible to use a variable from one page in a piece of code on another? e.g. submit a form on one page and on the second page use a PHP script to add the data from the form to a MySQL table Thanks for all the help
This is what the GET and POST 'super' globals are for. <http://www.tizag.com/phpT/postget.php>
Your best bet would be to use PHP's session functions. That way if the user navigates away from your page and then comes back, the session variables will still be there (provided the session hasn't expired). You can get more information here -- [PHP Sessions](http://www.php.net/manual/en/ref.session.php). Basically all...
Using PHP variables on multiple pages
[ "", "php", "variables", "" ]
At a new job I started, we have both a Java application that handles most of the heavy lifting in the core business logic, and we also have a Rails application that of course handles the web interface to this server. Both of these access the same database. Up until now, most of the focus has been on the Java applicati...
One approach is to use the rails migration tools, generate the DDL files for the database and use Hibernate to update the Java objects that relate to specific database entities. You don't really say how you manage database changes on the Java side or whether you use an ORM, but you can certainly synchronize the two wit...
We have a similar project structure: shared database with both java and rails applications as clients. I advocated and got buy-in to use the rails migration mechanism for handling database changes. It takes a bit of rails advocacy, and some willingness to help but the java team is also writing their own migrations. We...
Managing database changes between a Rails and Java project
[ "", "java", "ruby-on-rails", "ruby", "database", "migration", "" ]
## Problem I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest. Preferably this should be solved with the STL. boost::\* or stl::tr1::\* (from VS9 with Featurepack) are also possible. Example of timestamped d...
I would use set::lower\_bound to find the matching or greater value, then decrement the iterator to check the next lower value. You should use std::set rather than std::map since your key is embedded in the object - you'll need to provide a functor that compares the timestamp members. ``` struct TimestampCompare { ...
I would use equal\_range too for such a thing. If you are using sort() every time on your vector it might be better to use a map (or set), as that's always sorted automatically, and use the member equal\_range But that depends on the the amount of inserts / queries / amount of data. (although for something that alway...
Finding "best matching key" for a given key in a sorted STL container
[ "", "c++", "sorting", "stl", "containers", "" ]
I have quickly read (and will read with more care soon) the article of Scott Allen concerning the possibility to use an other provider of the default SQL Express or SQL Server database to use the "[Membership and Role Providers](http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-...
I gave it a go on MySQL and found it to be impossible. That could be attributed to my relatively low skill, and the fact that I did it about 5 months after 2.0 release. Is it too much to write your own simple security system? There is an alternate membership provider at: <http://www.codeplex.com/SnitzMember>
It actually fairly simple. It's basically just an interface with a handful of methods that need to be implemented, and most are fairly straight-forward. I implemented one, in MSSQL, but using an existing membership database from another application. You can find it at <http://www.codeplex.com/SnitzMember>
Membership and Role Providers in ASP.NET 2.0 with non SQL Server provider?
[ "", "c#", ".net", "asp.net", ".net-2.0", "" ]
I have a list of variable names, like this: ``` ['foo', 'bar', 'baz'] ``` (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables? ``` {'foo': foo,...
Forget filtering `locals()`! The dictionary you give to the formatting string is allowed to contain unused keys: ``` >>> name = 'foo' >>> zip = 123 >>> unused = 'whoops!' >>> locals() {'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...} >>> '%(name)s %(zip)i' % locals() 'foo 123' ``` With the new [f-string featu...
You can use list or generator comprehensions to build a list of key, value tuples used to directly instantiate a dict. The best way is below: ``` dict((name, eval(name)) for name in list_of_variable_names) ``` In addition, if you know, for example, that the variables exist in the local symbol table you can save yours...
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
[ "", "python", "list", "dictionary", "" ]
I need to validate the email address of my users. Unfortunately, making a validator that [conforms to standards](https://www.rfc-editor.org/rfc/rfc2822#section-3.4.1) is hard. [Here](http://www.ex-parrot.com/%7Epdw/Mail-RFC822-Address.html) is an example of a regex expression that tries to conform to the standard. Is...
I found a library in google code: <http://code.google.com/p/php-email-address-validation/> Are there any others?
Have you looked at [PHP's filter\_ functions](https://www.php.net/manual/en/function.filter-var.php)? They're not perfect, but they do a fairly decent job in my experience. Example usage (returns boolean): `filter_var($someEmail, FILTER_VALIDATE_EMAIL);`
Is there a PHP library for email address validation?
[ "", "php", "email", "open-source", "email-validation", "" ]
I want to use Sharepoint with python (C-Python) Has anyone tried this before ?
I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick: ``` from suds import WebFault from suds.client import * from suds.transport.https import WindowsHttpAuthenticated us...
To get the wsdl : ``` import sys # we use suds -> https://fedorahosted.org/suds from suds import WebFault from suds.client import * import urllib2 # my 2 url conf # url_sharepoint,url_NTLM_authproxy import myconfig as my # build url wsdl = '_vti_bin/SiteData.asmx?WSDL' url = '/'.join([my.url_sharepoint,wsdl]) #...
how can i use sharepoint (via soap?) from python?
[ "", "python", "sharepoint", "soap", "ntlm", "suds", "" ]
I have a `<button>` with an accesskey assgined to it. The accesskey works fine as long as the button is visible, but when I set `display: none` or `visibility: hidden`, the accesskey no longer works. Also tried without success: * Use a different element type: a, input (various types, even typeless). * Assign the acce...
The behavior you are seeing is correct, you cannot "access" an element that is not displayed. Sal's suggestion will almost certainly work, but may I ask what your purpose is in doing this? There is probably a better way to accomplish what you are trying to achieve. Have you considered using a keypress handler? I think...
You can apply a negative margin to push the element outsite of the visible page. I think many browsers and text readers ignore elements with `display:none` and possibly also `visibility:hidden`.
How can I define an accesskey for an invisible HTML element
[ "", "javascript", "html", "css", "firefox", "" ]
What are some things I can do to improve query performance of an oracle query without creating indexes? Here is the query I'm trying to run faster: ``` SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath FROM items a, itempages b, keygroupdata c WHERE a.ItemType IN (112,115,189,241) AND a.ItemNum = b.ItemNum AND b.It...
First I'd rewrite the query to be ANSI standard: ``` SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath FROM items a INNER JOIN itempages b ON b.ItemNum = a.ItemNum INNER JOIN keygroupdata c ON c.ItemNum = b.ItemNum WHERE a.ItemType IN (112,115,189,241) ORDER BY a.DateStored DESC ``` This makes it easier to read and...
Ask the third party to index its join columns, as they should have done in the first place! Without indexes, Oracle has nothing to go on other than brute force.
Improve oracle query performance without indexing
[ "", "sql", "performance", "oracle", "" ]
I have been trying to learn multi-threaded programming in C# and I am confused about when it is best to use a thread pool vs. create my own threads. One book recommends using a thread pool for small tasks only (whatever that means), but I can't seem to find any real guidelines. What are some pros and cons of thread po...
If you have lots of logical tasks that require constant processing and you want that to be done in parallel use the pool+scheduler. If you need to make your IO related tasks concurrently such as downloading stuff from remote servers or disk access, but need to do this say once every few minutes, then make your own thr...
I would suggest you use a thread pool in C# for the same reasons as any other language. When you want to limit the number of threads running or don't want the overhead of creating and destroying them, use a thread pool. By small tasks, the book you read means tasks with a short lifetime. If it takes ten seconds to cr...
When to use thread pool in C#?
[ "", "c#", "multithreading", "threadpool", "" ]
I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A\_DT, which is the date and time the person registered. I started with this: ``` var dailyCountList = (from a in showDC.Attendee let justDate = new DateTim...
O(n) with 2 enumerations. It's very good to pull the items into memory before trying this. Database has enough to do without thinking about this stuff. ``` if (!dailyCountList.Any()) return; //make a dictionary to provide O(1) lookups for later Dictionary<DateTime, RegistrationCount> lookup = dailyCountL...
The problem is that you have no range of dates without executing your query. So, you can either pick a date range, run a SELECT MAX and SELECT MIN against your DB, or execute your query and then add the missing dates. ``` var allDailyCountList = from d in Range(dc[0].EventDateTime, dc[dc.Count - 1].EventDateTime) ...
How do I use LINQ to query for items, but also include missing items?
[ "", "c#", "asp.net", "linq", "" ]
I'm experimenting with a personal finance application, and I'm thinking about what approach to take to update running balances when entering a transaction in an account. Currently the way I'm using involves retrieving all records more recent than the inserted/modified one, and go one by one incrementing their running ...
I think this might work: I was using both the date and the id to order the transactions, but now I'm going to store both the date and the id on one column, and use that for ordering. So, using comparisons (like >) should always work as expected, right? (as opposed to the situation I describe earlier where two columns ...
Some sort of Identity / Auto-increment columnn in there would be wise as well, purely for the transaction order if anything. Also in addition to just the date of the transaction, a date that the transaction is inserted into the database (not always the same) would be wise / helpful as well. These sort of things simpl...
How to update a column value incrementally
[ "", "sql", "" ]
Here's the code. Not much to it. ``` <?php include("Spreadsheet/Excel/Writer.php"); $xls = new Spreadsheet_Excel_Writer(); $sheet = $xls->addWorksheet('At a Glance'); $colNames = array('Foo', 'Bar'); $sheet->writeRow(0, 0, $colNames, $colHeadingFormat); for($i=1; $i<=10; $i++) { $row = array( "foo $i", "bar $...
The code in the question has a bug which causes the error. This line writes a bunch of column names to row 0 ``` $sheet->writeRow(0, 0, $colNames, $colHeadingFormat); ``` Then we have the loop which is supposed to write out the value rows. ``` for($i=1; $i<=10; $i++) { $row = array( "foo $i", "bar $i"); $s...
As Mark Biek points out the main problem is that `$rowNumber` is uninitialised and as such overwrites row 0. This means that the generated Excel file will contain 2 data entries for cells A1 and B1, (0, 0 and 0, 1). This wasn't a problem prior to Office Service Pack 3. However, once SP3 is installed Excel will raise ...
Strange error when creating Excel files with Spreadsheet_Excel_Writer
[ "", "php", "export-to-excel", "pear", "" ]
I'm working on a stored procedure in SQL Server 2000 with a temp table defined like this: ``` CREATE TABLE #MapTable (Category varchar(40), Code char(5)) ``` After creating the table I want to insert some standard records (which will then be supplemented dynamically in the procedure). Each category (about 10) will ha...
``` insert into #maptable (category, code) select 'foo1', b.bar from ( select 'bar11' as bar union select 'bar12' union select 'bar13' ) b union select 'foo2', b.bar from ( select 'bar21' as bar union select 'bar22' union select 'bar23' ) b ```
DJ's is a fine solution but could be simplified (see below). Why does it need to be a single statement? What's wrong with: ``` insert into #MapTable (category,code) values ('Foo','AAAAA') insert into #MapTable (category,code) values ('Foo','BBBBB') insert into #MapTable (category,code) values ('Foo','CCCCC') insert ...
Building a temp table /map
[ "", "sql", "sql-server", "t-sql", "" ]
I'm developing a poker game in C#. At the moment I'm trying to get the players hand score using `RegEx`. I search the string (composed of the cards suit and number) and look for suits or numbers to match the `RegEx`. If i get 2 matches then the player has a pair, 3 matches he has 3 of a kind. I have 3 classes at the m...
I do not think that a regex is the appropriate way to deal with this. You probably should be using a more sophisticated representation of a hand than a string.
You have not provided much detail, but what from what I have read, I assume you're not pushing the OOP very far... I would have a Card class that has a Rank and Suit class instances. I would then have a deck class that handles shuffling / dealing... I would then have a Hand class that would contain your poker hand of...
Using RegEx to get Poker Hand score
[ "", "c#", "regex", "poker", "" ]
Just for my own purposes, I'm trying to build a tokenizer in Java where I can define a regular grammar and have it tokenize input based on that. The StringTokenizer class is deprecated, and I've found a couple functions in Scanner that hint towards what I want to do, but no luck yet. Anyone know a good way of going abo...
The name "Scanner" is a bit misleading, because the word is often used to mean a lexical analyzer, and that's not what Scanner is for. All it is is a substitute for the `scanf()` function you find in C, Perl, *et al*. Like StringTokenizer and `split()`, it's designed to scan ahead until it finds a match for a given pat...
If I understand your question well then here are two example methods to tokenize a string. You do not even need the Scanner class, only if you want to pre-cast the tokens, or iterate through them more sofistically than using an array. If an array is enough just use String.split() as given below. Please give more requi...
How do I tokenize input using Java's Scanner class and regular expressions?
[ "", "java", "regex", "compiler-construction", "tokenize", "" ]
Can anoyne recommend a good library that will let me easily read/write private member fields of a class? I was looking through apache commons, but couldnt see it. I must be getting blind ? Edit: Asking questions on the border of legalities always give these questions of "why"? I am writing several javarebel plugins fo...
In most of the cases java [reflection](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/package-summary.html) solves the problem: Example: ``` public class Foo { /** * Gets the name Field. * * @return the name */ public final String getName() { return name; } /*...
Without knowing why you want that level of access, I can only wonder what you could need that level of access for. Private members are private for a reason. They are not intended to be accessed from outside the class and could result in undocumented behavior. That said, you can get access to most things through the ja...
Library that subverts java access control and lets me access private member variables?
[ "", "java", "" ]
I'm looking for best practices for establishing connections between Oracle 8 and Visual Studio 2005 applications. The target would be a Windows Forms application written in C# that hits the database once a second to monitor tables looking for their last inserted record. I'm considering using "Application settings" to s...
Based on my experience with Oracle 10g.... I recommend using the Oracle data provider (ODP.Net) and not using the Microsoft for Oracle data provider based on my experience with Oracle 10g. Microsoft's has not been updated in years and does not support everything in Oracle 10g, so I would definitely check into that for...
[ConnectionStrings.com](http://www.connectionstrings.com/) has pretty much every type of connection string you'll ever want including [Oracle](http://www.connectionstrings.com/?carrier=oracle).
What would be the most convenient way to connect Visual Studio 2005 (C#) to Oracle8?
[ "", "c#", ".net", "visual-studio", "winforms", "oracle", "" ]
As I've read somewhere it is advised to use !== and === instead.
"Use the strict equality operator (===) when you want to check that the two operands are of the same type and value. Use the regular equality operator (==) if you care only about the value and the type does not matter. If, for example, one operand is the number 5 and the other operand is the string "5", standard equali...
It depends on what your'e trying to do. !== and === compare both value *and* type. ``` 5 == "5" ``` The above will return true. If that's not what you intended, you should do this instead: ``` 5 === "5" ``` That would return false.
Need an example explaining why use of comparison operands != and == is considered bad practice in JavaScript
[ "", "javascript", "" ]
I started off programming in Basic on the [ZX81](http://en.wikipedia.org/wiki/ZX81), then [BASICA](http://en.wikipedia.org/wiki/IBM_BASICA), [GW-BASIC](http://en.wikipedia.org/wiki/GW-BASIC), and [QBasic](http://en.wikipedia.org/wiki/QBasic). I moved on to C (Ah, Turbo C 3.1, I hardly knew ye...) When I got started in...
As an architecture, the main claim to fame of BASIC is that you could make BASIC interpreters very small - just a few KB. In the days of a DG Nova this was a win as you could use systems like Business BASIC to build a multiuser application on a machine with 64K of RAM (or even less). BASIC (VB in particular) is a lega...
[This may come off sounding more negative than it really is. I'm not saying Basic is the root of all evil, [others have said that](http://en.wikiquote.org/wiki/Edsger_Dijkstra). I'm saying it's a legacy we can afford to leave behind.] **"because it was so easy to understand and so hard to make a mistake"** That's cert...
With Lua and Python embeddable, is there a place for Basic?
[ "", "python", "scripting", "lua", "interpreter", "basic", "" ]
I've been asked to display the 'correct' time on our website which I frankly feel is rather pointless as 'correct' can be interpretted in such a variety of ways. Our current method definately results in an inaccurate time as it uses a server control rendering JavaScript that runs onload using the datetime from the ser...
I needed to show the accurate time to clients in an auction web app. You can send the current server time with the page and have the javascript initialize right away without waiting for the rest of the page to load. So the, you only are dealing with network latency which in the worst case is not likely to be more than ...
First, be certain that your client is aware that Windows, Linux, and OSX all have built-in clocks that are almost always visible to the users (or made visible very easily). Also, be certain that your client is aware of physical clocks that are often located near any kiosks that might be setup to hide the built in clock...
Display accurate local time on web site?
[ "", "javascript", "web-services", "timezone", "" ]