Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
What implementations of the [Prototype](http://en.wikipedia.org/wiki/Prototype_pattern) Pattern exist on the Java platform? > A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objec...
According to Josh Bloch and Doug Lea, [Cloneable is broken](http://www.artima.com/intv/bloch13.html). In that case, you can use a [copy constructor](http://www.javapractices.com/topic/TopicAction.do?Id=12).
Java defines the [Cloneable](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html) interface, described here at [JGuru](http://www.jguru.com/faq/view.jsp?EID=255004) > Java provides a simple interface named Cloneable that provides an implementation of the Prototype pattern. If you have an object that is Cl...
Java implementations of the Prototype Pattern
[ "", "java", "oop", "design-patterns", "prototype-pattern", "" ]
How can i map a date from a java object to a database with Hibernate? I try different approaches, but i am not happy with them. Why? Let me explain my issue. I have the following class [1] including the main method i invoke and with the following mapping [2]. The issue about this approach you can see, when you look at ...
MySql DateTime precision is only to the second. Java Date precision is to the millisecond. That is why the last three digits are zeros after it has been put in the database. Do this to your original Date: date = date.setTime((date.getTime() / 1000) \* 1000); This will set it to the last exact second, and all your co...
SQL Server stores datetime with a precision of 3 milliseconds which can definitely cause the problem you're seeing. One fallout of this is that 23:59:59.999 in Java ends up being the next day in SQL Server. I've never had a problem with Oracle, Informix, or MySQL, but other databases may have less precision also. You c...
Comparing hibernate-mapped dates?
[ "", "java", "hibernate", "date", "" ]
Is it possible to somehow mark a `System.Array` as immutable. When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish: ``` public class Immy { public string[] { get; private set; } } ``` I thought the ...
[`ReadOnlyCollection<T>`](http://msdn.microsoft.com/en-us/library/ms132474) is probably what you are looking for. It doesn't have an `Add()` method.
The [Framework Design Guidelines](https://rads.stackoverflow.com/amzn/click/com/0321246756) suggest returning a copy of the Array. That way, consumers can't change items from the array. ``` // bad code // could still do Path.InvalidPathChars[0] = 'A'; public sealed class Path { public static readonly char[] Invalid...
Are immutable arrays possible in .NET?
[ "", "c#", ".net", "arrays", "immutability", "" ]
I find print\_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?
Note @tchrist recommends [Data::Dump](http://search.cpan.org/~gaas/Data-Dump-1.21/lib/Data/Dump.pm) over [Data::Dumper](http://search.cpan.org/~jhi/perl-5.8.0/ext/Data/Dumper/Dumper.pm). I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to int...
As usually with Perl, you might prefer alternative solutions to the venerable Data::Dumper: * [Data::Dump::Streamer](http://search.cpan.org/dist/Data-Dump-Streamer/) has a terser output than Data::Dumper, and can also serialize some data better than Data::Dumper, * [YAML](http://search.cpan.org/dist/YAML) (or [Yaml::S...
What is Perl's equivalent to PHP's print_r()?
[ "", "php", "perl", "debugging", "" ]
In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem. In Vista it instead returns the date that the picture is copied from the camera. How can I find out when a picture is taken in Vista? In windows explorer this field...
Here's as fast and clean as you can get it. By using FileStream, you can tell GDI+ not to load the whole image for verification. It runs over 10 × as fast on my machine. ``` //we init this once so that if the function is repeatedly called //it isn't stressing the garbage man private static Regex r = new Regex(":"); /...
I maintained a [simple open-source library](https://github.com/drewnoakes/metadata-extractor-dotnet) since 2002 for extracting metadata from image/video files. ``` // Read all metadata from the image var directories = ImageMetadataReader.ReadMetadata(stream); // Find the so-called Exif "SubIFD" (which may be null) va...
How can I find out when a picture was actually taken in C# running on Vista?
[ "", "c#", "" ]
Right now, I have a SQL Query like this one: ``` SELECT X, Y FROM POINTS ``` It returns results like so: ``` X Y ---------- 12 3 15 2 18 12 20 29 ``` I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag): ``` XYLIST ---------- 12,3,15,2,18,12,20,29 ``` Is there...
``` DECLARE @XYList varchar(MAX) SET @XYList = '' SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ',' FROM POINTS -- Remove last comma SELECT LEFT(@XYList, LEN(@XYList) - 1) ```
Thanks for the quick and helpful answers guys! I just found another fast way to do this too: ``` SELECT STUFF(( SELECT ',' + X + ',' + Y FROM Points FOR XML PATH('') ), 1, 1, '') AS XYList ``` Credit goes to this guy: [Link](https://web.archive.org/web/20...
How can I combine multiple rows into a comma-delimited list in SQL Server 2005?
[ "", "sql", "sql-server", "list", "function", "concatenation", "" ]
I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?
In a debug compilation, [`Assert`](https://msdn.microsoft.com/en-us/library/kssw4w7z.aspx "MSDN Debug.Assert") takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true. If you compile in Release, all [`Debu...
From [Code Complete](https://web.archive.org/web/20161126131145/http://cc2e.com/) > ## 8 Defensive Programming > > ### 8.2 Assertions > > An assertion is code that’s used during development—usually a routine > or macro—that allows a program to check itself as it runs. When a > assertion is true, that means everything ...
C# - What does the Assert() method do? Is it still useful?
[ "", "c#", "assert", "" ]
What exactly does null do performance and storage (space) wise in MySQL? For example: TINYINT: 1 Byte TINYINT w/NULL 1 byte + somehow stores NULL?
It depends on which storage engine you use. In MyISAM format, each row header contains a bitfield with one bit for each column to encode NULL state. A column that is NULL still takes up space, so NULL's don't reduce storage. See <https://dev.mysql.com/doc/internals/en/myisam-introduction.html> In InnoDB, each column ...
Bill's answer is good, but a little bit outdated. The use of one or two bytes for storing NULL applies **only** to InnoDB REDUNDANT row format. Since MySQL 5.0.3 InnoDB uses **COMPACT** row format which uses only one bit to store a NULL (of course one byte is the minimum), therefore: Space Required for NULLs = **CEILI...
NULL in MySQL (Performance & Storage)
[ "", "sql", "mysql", "null", "" ]
I've been trying for a while now to write a unit test for a UserViewControl in ASP.NET MVC. I'd like to get to code that looks something like this: ``` [TestMethod] public void HaveControlToDisplayThings() { var listControl = new ControlUnderTest(); var viewData = new ViewDataDictionary<IList<string>>(this.rep...
Unfortunately, the ASP.NET viewengine uses the VirtualPathProvider in the ASP.NET hosting environment. To make matters worse, I traced some of the other code using Reflector and found that there is other dependencies to some hardcode references to VirtualPath utilities. I hope they fix this in the release so we can tru...
One option would be to run unit tests inside the browser. I've had success with [Selenium](http://seleniumhq.org/) for such cases.
How can I unit test an MVC UserViewControl?
[ "", "c#", "asp.net-mvc", "mocking", "" ]
The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to. It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but...
Consider broadcasting a specific UDP packet. When the server or servers see the broadcasted UDP packet they send a reply. The client can collect the replies from all the servers and start connecting to them or based on an election algorithm. See example for client (**untested code**): --- ``` using System.Net; using...
I'd say the best way is to use Bonjour/Zeroconf/mDNS for C#; a lot of thought went into making it play nice with the network; IE it pings less frequently over time if possible, etc. There's [Mono.Zeroconf](http://mono-project.com/Mono%2eZeroconf), and I read there's an older .NET project in the [Apple SDK](http://devel...
What is the best way for a client app to find a server on a local network in C#?
[ "", "c#", "remoting", "client-server", "service-discovery", "" ]
I saw this question asked about C# I would like an answer for PHP. I have some old code that has 4 pages of foreach loops and conditions which just makes it hard to read and follow. How would I make this more OO? I was thinking of using SPL Functions but don't fully understand whats involved yet.
This code can probably be cleaned up significantly, and pushed far in the direction of OO, without touching SPL. SPL is only needed if you want to alter normal object behaviour in language constructs like foreach(), or in builtins like count(), or in array access funcitons (both operator [] and functions like key(), n...
If I were you, I'd start by writing test code. If you can build up a set of testcases that fully describe the functionality you're refactoring, you can go ahead and rewrite your code safe in the knowledge that it will still work. [PHPUnit](http://phpunit.sourceforge.net) might be a good place to start with this.
Remove repetitive, hard coded loops and conditions in PHP
[ "", "php", "spl", "" ]
I have a table that looks like that: ![alt text](https://i.stack.imgur.com/R0TIr.jpg) The rows are sorted by CLNDR\_DATE DESC. I need to find a CLNDR\_DATE that corresponds to the highlighted row, in other words: Find the topmost group of rows WHERE EFFECTIVE\_DATE IS NOT NULL, and return the CLNR\_DATE of a last ...
Warning: Not a DBA by any means. ;) But, a quick, untested stab at it: ``` SELECT min(CLNDR_DATE) FROM [TABLE] WHERE (EFFECTIVE_DATE IS NOT NULL) AND (CLNDR_DATE > ( SELECT max(CLNDR_DATE) FROM [TABLE] WHERE EFFECTIVE_DATE IS NULL )) ``` Assuming you want the **first** CLNDR\_DATE **with** EFFECTIVE\_DATE af...
Using Oracle's analytic function (untested) ``` select * from ( select clndr_date, effective_date, lag(clndr_date, 1, null) over (order by clndr_date desc) prev_clndr_date from table ) where effective_date is null ``` The `lag(clndr_date, 1, null) over (order by clndr_date desc)` returns the previo...
Do this with a single SQL
[ "", "sql", "oracle", "" ]
How do I limit `os.walk` to only return files in the directory I provide it? ``` def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList.append(os.path.join(root,...
Use the `walklevel` function. ``` import os def walklevel(some_dir, level=1): some_dir = some_dir.rstrip(os.path.sep) assert os.path.isdir(some_dir) num_sep = some_dir.count(os.path.sep) for root, dirs, files in os.walk(some_dir): yield root, dirs, files num_sep_this = root.count(os.pa...
Don't use os.walk. Example: ``` import os root = "C:\\" for item in os.listdir(root): if os.path.isfile(os.path.join(root, item)): print item ```
os.walk without digging into directories below
[ "", "python", "file", "os.walk", "" ]
I would like to do remote deployment from my build machine onto a server. The remoting can be done via ssh commands from a script, but I would rather use phing and a deploy.xml file that would do the automation. What alternatives do I have to do ssh (and also scp) tasks from within a phing build file?
If you really need phing, then afaik there's only exec. If you are open for other tools, have a look at [capistrano](http://www.capify.org/) and my answer in "[Setting up a PHP web project, the infrastructure.](https://stackoverflow.com/questions/220638/setting-up-a-php-web-project-the-infrastructure#225524)".
[SCPTask](https://www.phing.info/docs/guide/stable/ScpTask.html) in Phing: > copies files to and from a remote host using scp. This task requires the **[PHP SSH2 extension](http://web.archive.org/web/20101219161808/http://pecl.php.net/package/ssh2)** to function...
Are there ssh and scp tasks available for phing?
[ "", "php", "deployment", "phing", "" ]
I am writing some JNI code in C that I wish to test using cunit. In order to call the JNI functions, I need to create a valid JNIEnv struct. Does anyone know if there is a mocking framework for such a purpose, or who can give me some pointers on how to create a mock JNIEnv struct myself?
jni.h contains the complete structure for JNIEnv\_, including the "jump table" JNINativeInterface\_. You could create your own JNINativeInterface\_ (pointing to mock implementations) and instantiate a JNIEnv\_ from it. Edit in response to comments: (I didn't look at the other SO question you referenced) ``` #include ...
Mocking JNI sounds like a world of pain to me. I think you are likely to be better off mocking the calls implemented in Java, and using Junit to test the functionality on the java side
How to create a JNIEnv mock in C/C++
[ "", "c++", "c", "mocking", "java-native-interface", "cunit", "" ]
Is it quicker to make one trip to the database and bring back 3000+ plus rows, then manipulate them in .net & LINQ or quicker to make 6 calls bringing back a couple of 100 rows at a time?
Is this for one user, or will many users be querying the data? The single database call will scale better under load.
It will entirely depend on the speed of the database, the network bandwidth and latency, the speed of the .NET machine, the actual queries etc. In other words, we can't give you a truthful general answer. I know which sounds easier to code :) Unfortunately this is the kind of thing which you can't easily test usefull...
Which is fastest? Data retrieval
[ "", "asp.net", "sql", "database", "linq", "" ]
I'm experimenting with generics and I'm trying to create structure similar to Dataset class. I have following code ``` public struct Column<T> { T value; T originalValue; public bool HasChanges { get { return !value.Equals(originalValue); } } public void AcceptChanges() { ...
As you asked for examples from functional languages; in lisp you could prevent the writing of all that code upon each addition of a column by using a macro to crank the code out for you. Sadly, I do not think that is possible in C#. In terms of performance: the macro would be evaluated at compile time (thus slowing co...
Honestly, it sounds like you really want these `Column`s to be classes, but don't want to pay the runtime cost associated with classes, so you're trying to make them be structs. I don't think you're going to find an elegant way to do what you want. Structs are supposed to be value types, and you want to make them behav...
class with valueTypes fields and boxing
[ "", "c#", "data-structures", "t4", "" ]
I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields. Something like firefox live headers, but for the server side.
The middleware ``` from wsgiref.util import request_uri import sys def logging_middleware(application, stream=sys.stdout): def _logger(environ, start_response): stream.write('REQUEST\n') stream.write('%s %s\n' %( environ['REQUEST_METHOD'], request_uri(environ), )) ...
That shouldn't be too hard to write yourself as long as you only need the headers. Try that: ``` import sys def log_headers(app, stream=None): if stream is None: stream = sys.stdout def proxy(environ, start_response): for key, value in environ.iteritems(): if key.startswith('HTTP_'...
Debug/Monitor middleware for python wsgi applications
[ "", "python", "debugging", "wsgi", "middleware", "" ]
I have code like this: ``` var newMsg = new Msg { Var1 = var1, Var2 = var2 }; using (AppDataContext appDataContext = new AppDataContext(ConnectionString)) { appDataContext.CClass.InsertOnSubmit(newMsg); appDataContext.SubmitChanges(); } ``` After reading [this post](https://stackoverflow.com/question...
The second answer in the post you're referencing says it: > LINQ to SQL uses *execute\_sql* with > parameters. It does not concatenate property values into a one big INSERT ... VALUES('...', '...')
The underlying operation of the DataContext is via the SqlCommand which uses paramatised SQL. So your insert statement will look like this: ``` INSERT INTO [MSG] [Var1] = @p1, [Var2] = @p2 ```
Is LINQ to SQL InsertOnSubmit() subject to SQL Injection Attack?
[ "", "c#", ".net", "linq-to-sql", "sql-injection", "" ]
I have several long running report type transactions that take 5-10 minutes. Would I see any performance increase by using stored procs? Would it be significant? each query runs once a night.
The short answer is: no, stored procedures aren't going to improve the performance. For a start, if you are using parameterised queries there is no difference in performance between a stored procedure and inline SQL. The reason is that ALL queries have cached execution plans - not just stored procedures. Have a look at...
Probably not. Stored procs give you the advantage of pre-compiled SQL. If your SQL is invoked infrequently, they this advantage will be pretty worthless. So if you have SQL that is expensive because the queries themselves are expensive, then stored procs will gain you no meaningful performance advantage. If you have qu...
Performance gains in stored procs for long running transactions
[ "", "sql", "stored-procedures", "" ]
Assume a table with the following columns: `pri_id`, `item_id`, `comment`, `date` What I want to have is a SQL query that will delete any records, for a specific `item_id` that are older than a given date, BUT only as long as there are more than 15 rows for that `item_id`. This will be used to purge out comment reco...
Something like this should work for you: ``` delete from MyTable where item_id in ( select item_id from MyTable group by item_id having count(item_id) > 15 ) and Date < @tDate ```
You want to keep at least 15 of them always, correct? So: ``` DELETE FROM CommentTable WHERE CommentId NOT IN ( SELECT TOP 15 CommentId FROM CommentTable WHERE ItemId=@ItemId AND CommentDate < @Date ORDER BY CommentDate DESC ) A...
sql statement to delete records older than XXX as long as there are more than YY rows
[ "", "sql", "datetime", "" ]
I have a server application that receives information over a network and processes it. The server is multi-threaded and handles multiple sockets at time, and threads are created without my control through BeginInvoke and EndInvoke style methods, which are chained by corresponding callback functions. I'm trying to crea...
You have to call Invoke (or BeginInvoke) on the ListBox control you are accessing in order for the delegate to be called on the thread that created that control. ``` ListBox listBox = c.Controls["listBox1"] as ListBox; if(listBox != null) { listBox.Invoke(...); } ```
I've always used something along these lines: ``` c = <your control> if (c.InvokeRequired) { c.BeginInvoke((MethodInvoker)delegate { //do something with c }); } else { //do something with c } ``` I ...
Need help getting info across a UI thread and another thread in C#
[ "", "c#", "forms", "invoke", "multithreading", "" ]
Given the following HTML: ``` <select name="my_dropdown" id="my_dropdown"> <option value="1">displayed text 1</option> </select> ``` How do I grab the string "displayed text 1" using Javascript/the DOM?
``` var sel = document.getElementById("my_dropdown"); //get the selected option var selectedText = sel.options[sel.selectedIndex].text; //or get the first option var optionText = sel.options[0].text; //or get the option with value="1" for(var i=0; i<sel.options.length; i++){ if(sel.options[i].value == "1"){ ...
``` var mySelect = document.forms["my_form"].my_dropdown; // or if you select has a id var mySelect = document.getElementById("my_dropdown"); var text = mySelect.options[mySelect.selectedIndex].text; ```
How do I access the "displayed" text of a select box option from the DOM?
[ "", "javascript", "dom", "" ]
I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control? ``` <div id="formSpinner"> <img src="images/spinner.gif" /> <p>Saving...</p> </div> ```
Add the `runat="server"` attribute to it so you have: ``` <div id="formSpinner" runat="server"> <img src="images/spinner.gif"> <p>Saving...</p> </div> ``` That way you can access the class attribute by using: ``` formSpinner.Attributes["class"] = "classOfYourChoice"; ``` It's also worth mentioning that the ...
Make sure that your div is set to runat="server", then simply reference it in the code-behind and set the "class" attribute. ``` <div runat="server" id="formSpinner"> ...content... </div> ``` Code-behind ``` formSpinner.Attributes["class"] = "class-name"; ```
How to edit CSS style of a div using C# in .NET
[ "", "c#", ".net", "css", "" ]
When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach?
CSS is fine for rollovers. They're implemented basically using the `:hover` pseudo-selector. Here's a really simple implementation: ``` a{ background-image: url(non-hovered-state.png); } a:hover{ background-image: url(hovered-state.png); } ``` There are a few things you need to be aware of though: * IE6 only...
It will still work in CSS if the browser happens to have Javascript disabled.
What is the preferred way to do a CSS rollover?
[ "", "javascript", "html", "css", "" ]
If I create a Stored Procedure in SQL and call it (`EXEC spStoredProcedure`) within the BEGIN/END TRANSACTION, does this stored procedure also fall into the transaction? I didn't know if it worked like try/catches in C#.
Yes, *everything* that you do between the Begin Transaction and Commit (or Rollback) is part of the transaction.
Sounds great, thanks a bunch. I ended up doing something like this (because I'm on 05) ``` BEGIN TRY BEGIN TRANSACTION DO SOMETHING COMMIT END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK -- Raise an error with the details of the exception DECLARE @ErrMsg n...
Executing a stored procedure inside BEGIN/END TRANSACTION
[ "", "sql", "sql-server", "stored-procedures", "rollback", "sqltransaction", "" ]
Examples could be Infragistics or DevExpress. But I'm also looking for your opinions on other frameworks. It could even be WPF if that is your favorite.
Infragistics is very good. I think they have a better product for windows than the web. However, I get very upset using their products sometimes. I just want to find some hidden property, and it is impossible to find. They have way to many properties. Sure, you can do anything with their grid, but it should be easier. ...
I've used Telerik RAD Controls for Asp.Net and it is a very comprehensive suite of controls that are easily converted to AJAX. The support is top notch, with the forum as a first place to go to for research before contacting the staff. The client side API is fairly easy to understand, and they have good examples of mi...
What is the best 3rd party GUI framework for application development in C#?
[ "", "c#", ".net", "user-interface", "" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/pytho...
[`Popen.communicate()`](https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate) documentation: > Note that if you want to send data to > the process’s stdin, you need to > create the Popen object with > stdin=PIPE. Similarly, to get anything > other than None in the result ...
I figured out this workaround: ``` >>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE) >>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object >>> p.communicate()[0] 'four\nfive\n' >>> p.stdin.close() ``` Is there a better one?
How do I pass a string into subprocess.Popen (using the stdin argument)?
[ "", "python", "subprocess", "stdin", "" ]
Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that `WriteLine()` can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code: ``` StreamWriter sw = new St...
Are you calling StreamWriter.Close() or Flush()?
Be sure you wrap your StreamWriter in a using-block, or are careful about your [explicit management of the resource's lifetime](http://msdn.microsoft.com/en-us/library/system.io.streamwriter.close.aspx). ``` using (StreamWriter writer = new StreamWriter(@"somefile.txt")) { // ... writer.WriteLine(largeAmountsO...
Is there a maximum number of characters that can be written using a StreamWriter?
[ "", "c#", ".net", "file-io", "" ]
Can I access spring bean that exposed using http invoker (server) from GWT application (client)? If so is there any example / tutorial for that?
There's an application template for Spring-GWT apps available [here](http://bram.jteam.nl/index.php/2007/06/20/springone-2007-slides-sample-code/), that you may find useful. I haven't tried it out, but I believe it's implemented as a Maven archetype. For more background on exactly what this template does for you, and ...
you can try my way of GWT and Spring integration: <https://code.google.com/p/gspring>. It's simple and clear.
Access spring bean that is exposed using http invoker from GWT application
[ "", "java", "spring", "gwt", "" ]
I've been using jQuery to do the whole AJAX magic in my web based applications. But I came to a decision that I don’t need all these amazing features jQuery has, except its AJAX functions (like `$.ajax()`, `$.get()`, `$.post`, `getJSON()` and `load();`). Can you recommend a lightweight crossbrowser AJAX library/framew...
You can make jQuery smaller by removing the modules you don't need / Just modify the [Makefile](https://github.com/jquery/jquery/blob/master/Makefile) file.
If you need to use ONLY ajax features take a look at [sajax](http://www.modernmethod.com/sajax/index.phtml) or custom [MooTools](http://mootools.net). Of course, if you are a "lightweight freak" you can write your own routine for this (should be less than 50 lines)
Which JavaScript AJAX Framework is most powerful and very lightweight?
[ "", "javascript", "ajax", "json", "frameworks", "" ]
I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole. I am working ...
There are two main sub-problems one must solve in order to solve this problem: 1. Determine which item is being hovered over 2. Get the MouseHover event to fire when the user has hovered over one item, then moved the cursor within the listbox and hovered over another item. The first problem is rather simple to solve....
Using the MouseMove event, you can keep track of the index of the item that the mouse is over and store this in a variable that keeps its value between MouseMoves. Every time MouseMove is triggered, it checks to see if the index has changed. If so, it disables the tooltip, changes the tooltip text for this control, the...
How can I set different Tooltip text for each item in a listbox?
[ "", "c#", ".net", "winforms", "winapi", "listbox", "" ]
What aspects of the UpdatePanel are sensitive to time? I have an UpdatePanel that works fine. If I leave the page for a few minutes and come back, the UpdatePanel doesn't work. Looking at firebug, I see that it sends the Request and gets a Response back. However, the page itself doesn't update. I'm not seeing any scri...
Maybe your application domain recycled or your Session was lost. Have you tried seeing what is being called on the server? That'd be my suggestion on where to look next.
Turn off Firebug network monitoring if enabled.
Why would an UpdatePanel stop working after a few minutes?
[ "", "javascript", "ajax", "asp.net-ajax", "updatepanel", "" ]
Whats the best practice for setting up package structures in a Java Web Application? How would you setup your src, unit test code, etc?
You could follow maven's [standard project layout](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html). You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since...
There are a few existing resources you might check: 1. [Properly Package Your Java Classes](http://www.techrepublic.com/article/properly-package-your-java-classes/) 2. [Spring 2.5 Architecture](http://chris.headwaysoftware.com/java/) 3. [Java Tutorial - Naming a Package](http://docs.oracle.com/javase/tutorial/java/pac...
Package structure for a Java project?
[ "", "java", "package", "" ]
I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer...
Read up on the try: statement. ``` try: # do something except socket.error, e: # A socket error except IOError, e: if e.errno == errno.EPIPE: # EPIPE error else: # Other error ```
Assuming that you are using the standard socket module, you should be catching the `socket.error: (32, 'Broken pipe')` exception (not IOError as others have suggested). This will be raised in the case that you've described, i.e. sending/writing to a socket for which the remote side has disconnected. ``` import socket,...
How to handle a broken pipe (SIGPIPE) in python?
[ "", "python", "python-2.x", "broken-pipe", "" ]
I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore. There are several places in the codebase where it would clean up the cod...
Generally this is done by using a script that tries running the preprocessor on an attempt at including the file. Depending on if the preprocessor returns an error, the script updates a generated .h file with an appropriate #define (or #undef). In bash, the script might look vaguely like this: ``` cat > .test.h <<'EOM...
# Little Update Some compilers might support `__has_include ( header-name )`. The extension was added to the [C++17 standard](https://isocpp.org/files/papers/p0636r0.html) ([P0061R1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0061r1.html)). ## Compiler Support * Clang * GCC from 5.X * Visual Studio fr...
Can the C preprocessor be used to tell if a file exists?
[ "", "c++", "include", "c-preprocessor", "" ]
I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc. The challenge is that I am accepting input from an outside sourc...
The Spring framework contains a utility class [ClassUtils](http://static.springframework.org/spring/docs/1.1.5/api/org/springframework/util/ClassUtils.html) which contains the static method forName. This method can be used for the exact purpose you described. In case you don’t like to have a dependency on Spring: the ...
The `Class` instances for the primitive types are obtainable as you said using e.g. `int.class`, but it is also possible to get the same values using something like `Integer.TYPE`. Each primitive wrapper class contains a static field, `TYPE`, which has the corresponding primitive class instance. You cannot obtain the ...
Dynamically find the class that represents a primitive Java type
[ "", "java", "reflection", "types", "primitive", "" ]
I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document? ``` <script type="text/javascript"> $(document).ready(function() { // ??? }); </script>...
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag. ``` <script type="text/javascript"> $(document).ready(function() { document.title = 'blah'; }); </script> ```
Do not use `$('title').text('hi')`, because IE doesn't support it. It is better to use `document.title = 'new title';`
How can I change the title of the document during .ready()?
[ "", "javascript", "jquery", "ruby-on-rails", "" ]
I'm looking to utilize jQuery to handle a few very common requests we get for data tables of varying sizes: scrolling, sorting, and dynamic filtering. * I've handled scrolling in the past by having two separate tables with fixed width columns, along with associated div containers for the "actual" scrolling. However, t...
I came across this question as I was searching for a sortable table plugin myself; I really wasn't impressed with any of the suggested widgets, but later I discovered [DataTables](http://datatables.net/index), and I was quite impressed. I recommend checking it out.
Maybe this excellent plug-in could do it: [Demo page](http://trirand.com/jqgrid/jqgrid.html) It's called jQGrid, here is the project page: <http://plugins.jquery.com/project/jqGrid>
jQuery Scrollable, Sortable, Filterable table
[ "", "javascript", "jquery", "html", "" ]
How does one write a unit test that fails only if a function doesn't throw an expected exception?
Use [`TestCase.assertRaises`](http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises) from the `unittest` module, for example: ``` import mymod class MyTestCase(unittest.TestCase): def test1(self): self.assertRaises(SomeCoolException, mymod.myfunc) ```
Since Python 2.7 you can use context manager to get ahold of the actual Exception object thrown: ``` import unittest def broken_function(): raise Exception('This is broken') class MyTestCase(unittest.TestCase): def test(self): with self.assertRaises(Exception) as context: broken_function(...
How do you test that a Python function throws an exception?
[ "", "python", "unit-testing", "exception", "" ]
I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly). As I was reconstructing the query by adding in elements to see which porti...
I suspect that this is a procedure cache issue. One benefit of stored procedures is that the plan is stored for you, which speeds things up. Unfortunately, it's possible to get a bad plan in the cache (even when using dynamic queries). Just for fun, I checked my procedure cache, ran an adhoc query, checked again, then...
Since you are using SQL Server 2005, have you tried with a SqlCommand object instead of the OleDbCommand object?
Case Sensitivity when querying SQL Server 2005 from .NET using OleDB
[ "", "c#", ".net", "sql-server", "oledb", "case-sensitive", "" ]
PHP 4.4 and PHP 5.2.3 under Apache 2.2.4 on ubuntu. I am running Moodle 1.5.3 and have recently had a problem when updating a course. The $\_POST variable is empty but only if a lot of text was entered into the textarea on the form. If only a short text is entered it works fine. I have increased the post\_max\_size f...
Could it be not the size related of the post, but how long the line is before a new line. If they use the Moodle WYSIWYG view the html would just get put into one line with no breaks. If you go into html and hit return around every 1000 characters does it work?
I don't know enough to really provide a useful answer so the following is more a well-educated guess (at least I hope so). First, you should debug the entire request, either by access\_log or for example through [firebug](http://www.getfirebug.com/). (Good to have Firebug anyway.) To me your problem *sounds* like a re...
Why is _POST sometimes empty when a textarea is posted in PHP
[ "", "php", "apache2", "" ]
When I get a java.io.InvalidClassException, it gives me the serialVersionUID that it wants, and the serialVersionUID that it got. Is there an easy way to tell which of my dozens of jars using the wrong serialVersionUID? **Update**: I should mention that our intention is to update everything at the same time, but I'm t...
use the serialver tool from the sun jdk for each class in the jar.
The best way to deal with this kind of trouble is to update jars on the server and client side at the same time. This will guarantee the same version of your classes on both sides and you'll not have trouble when serializing / deserializing. Tracking serial UIDs each time you have this problem is not going to solve any...
Find which class in which jar has a given serialVersionUID
[ "", "java", "serialversionuid", "" ]
In C#, what is the best way to access a property of the derived class when the generic list contains just the base class. ``` public class ClassA : BaseClass { public object PropertyA { get; set; } } public class ClassB: BaseClass { public object PropertyB { get; set; } } public class BaseClass { } public vo...
Certainly you can downcast, like so: ``` for (int i = 0; i < MyList.Count; i++) { if (MyList[i] is ClassA) { var a = ((ClassA)MyList[i]).PropertyA; // do stuff with a } if (MyList[i] is ClassB) { var b = ((ClassB)MyList[i]).PropertyB; // do stuff with b } } ``` ...
Further to TimJ's answer, you can write one extension method that will work for all types: ``` public static IEnumerable<T> OfType<T>(this IEnumerable list) { foreach (var obj in list) { if (obj is T) yield return (T)obj; } } ``` Or if you have Linq, that function is in the namespace S...
Accessing a property of derived class from the base class in C#
[ "", "c#", "generics", "collections", "" ]
I have a specialized list that holds items of type `IThing`: ``` public class ThingList : IList<IThing> {...} public interface IThing { Decimal Weight { get; set; } Decimal Velocity { get; set; } Decimal Distance { get; set; } Decimal Age { get; set; } Decimal AnotherValue { get; set; } [...e...
Yes, you should use a delegate and anonymous methods. For an example see [here](http://encodo.com/en/blogs.php?entry_id=76). Basically you need to implement something similar to the [Find method of Lists](http://msdn.microsoft.com/en-us/library/x0b5b5bc(VS.80).aspx). Here is a sample implementation ``` public class...
(Edited to reflect .NET 2.0 answer, and LINQBridge in VS2005...) There are three situations here - although the OP only has .NET 2.0, other people facing the same problem may not... 1) Using .NET 3.5 and C# 3.0: use LINQ to Objects like this: ``` decimal maxWeight = list.Max(thing => thing.Weight); decimal minWeight...
C#: Getting maximum and minimum values of arbitrary properties of all items in a list
[ "", "c#", ".net", "reflection", ".net-2.0", "" ]
I want to know how to use variables for objects and function names in Python. In PHP, you can do this: ``` $className = "MyClass"; $newObject = new $className(); ``` How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?
In Python, ``` className = MyClass newObject = className() ``` The first line makes the variable `className` refer to the same thing as `MyClass`. Then the next line calls the `MyClass` constructor through the `className` variable. As a concrete example: ``` >>> className = list >>> newObject = className() >>> newO...
Assuming that some\_module has a class named "class\_name": ``` import some_module klass = getattr(some_module, "class_name") some_object = klass() ``` I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in thi...
Using Variables for Class Names in Python?
[ "", "python", "dynamic-typing", "" ]
I would like to know many minutes between 2 dates? Example : Now - tommorow at the exact time would return me 1440.
``` DateTime dt1 = DateTime.Now; DateTime dt2 = DateTime.Now.AddDays(1); int diff = dt2.Subtract(dt1).TotalMinutes; ```
Look at the TimeSpan class. ``` DateTime date1 = DateTime.Now; DateTime date2 = DateTime.Now.AddDays(1); TimeSpan diff = date2.Subtract(date1); Console.WriteLine(diff.Minutes); ```
Exact time between 2 DateTime?
[ "", "c#", ".net", "datetime", ".net-2.0", "" ]
I'm reading this C++ open source code and I came to a constructor but I don't get it ( basically because I don't know C++ :P ) I understand C and Java very well. ``` TransparentObject::TransparentObject( int w, int x, int y, int z ) : _someMethod( 0 ), _someOtherMethod( 0 ), _someOtherOtherMethod( 0 ...
The most common case is this: ``` class foo{ private: int x; int y; public: foo(int _x, int _y) : x(_x), y(_y) {} } ``` This will set `x` and `y` to the values that are given in `_x` and `_y` in the constructor parameters. This is often the best way to construct any objects that are declared as data membe...
You are pretty close. The first line is the declaration. The label left of the :: is the class name and for it to be a constructor, the function name has to be the same as the class name. ``` TransparentObject::TransparentObject( int w, int x, int y, int z ) ``` In C++ you can optionally put a colon and some initial ...
What is the member variables list after the colon in a constructor good for?
[ "", "c++", "constructor", "" ]
Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic. Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a l...
You can mask everything by `0xFFFFFFFF`: ``` >>> m = 0xFFFFFF00 >>> allf = 0xFFFFFFFF >>> ~m & allf 255L ```
You can use [ctypes](http://docs.python.org/lib/module-ctypes.html) and its `c_uint32`: ``` >>> import ctypes >>> m = 0xFFFFFF00 >>> ctypes.c_uint32(~m).value 255L ``` So what I did here was casting `~m` to a C 32-bit unsigned integer and retrieving its value back in Python format.
Python: unsigned 32 bit bitwise arithmetic
[ "", "python", "math", "" ]
Is it really necessary to release COM components from Office PIA, when you don't need them anymore by invoking Marshal.ReleaseComObject(..)? I found various and contradictory advices on this topic on the web. In my opinion, since Outlook PIA is always returning a new references to its interfaces as returning values fr...
With Microsoft Office, in general, you do need to explicitly release your references, which can be safely done in two stages: (1) First release all the minor object to which you do not hold a named object variable via a call to GC.Collect() and then GC.WaitForPendingFinalizers(). (You need to call this twice, if the o...
For VS 2010, see [Marshal.ReleaseComObject Is Considered Dangerous](http://www.infoq.com/news/2010/03/ReleaseComObject-Dangerous).
Release COM Components
[ "", "c#", ".net", "outlook", "add-in", "pia", "" ]
I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't: ``` DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance(); docfactory.setIgnoringElementContentWhitespace(true); ``` I see in Javadoc that setIgnoringElementCon...
‘IgnoringElementContentWhitespace’ is not about removing *all* pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT content — that is to say, they only contain other elements and never text. If you don't have a schema (DTD or XSD) in use, element content default...
This is a (really) late answer, but here is how I solved it. I wrote my own implementation of a `NodeList` class. It simply ignores text nodes that are empty. Code follows: ``` private static class NdLst implements NodeList, Iterable<Node> { private List<Node> nodes; public NdLst(NodeList list) { nod...
How to ignore whitespace while reading a file to produce an XML DOM
[ "", "java", "xml", "whitespace", "" ]
I'd like to make a click event fire on an `<input type="file">` tag programmatically. Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog. I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to ...
You cannot do that in all browsers, supposedly IE *does* allow it, but Mozilla and Opera do not. When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not. I don't know w...
I have been searching for solution to this whole day. And these are the conclusions that I have made: 1. For the security reasons Opera and Firefox don't allow to trigger file input. 2. The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards c...
In JavaScript can I make a "click" event fire programmatically for a file input element?
[ "", "javascript", "html", "" ]
I'm trying to determine how I can detect when the user changes the Windows Font Size from Normal to Extra Large Fonts, the font size is selected by executing the following steps on a Windows XP machine: 1. Right-click on the desktop and select Properties. 2. Click on the Appearance Tab. 3. Select the Font Size: Normal...
[EDIT after re-read] I'm almost positive that changing to "Large fonts" does not cause a DPI change, rather it's a theme setting. You should be able to verify by applying the "Large fonts" change and then opening the advanced display properties where the DPI setting lives, it should have remained at 96dpi. --- DPI ch...
When you call GetDeviceCaps() on the Desktop DC, are you perhaps using a DC that might be cached by MFC, and therefore contains out-of-date information? Are you making the GetDeviceCaps() call synchronously from inside your OnSettingsChange handler? I could see how either or both of these things might get you an out of...
Can't detect when Windows Font Size has changed C++ MFC
[ "", "c++", "winapi", "mfc", "font-size", "system-font", "" ]
I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file. ``` string filePath = "image.jpg"; Image newImage = Image.FromFile(filePath); ``` The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to ima...
JPEG's don't have a formal header definition, but they do have a small amount of metadata you can use. * Offset 0 (Two Bytes): JPEG SOI marker (FFD8 hex) * Offset 2 (Two Bytes): Image width in pixels * Offset 4 (Two Bytes): Image height in pixels * Offset 6 (Byte): Number of components (1 = grayscale, 3 = RGB) There ...
here is my image check. I cannot rely on file extensions and have to check the format on my own. I am loading BitmapImages in WPF from byte arrays and don't know the format upfront. WPF detects the format fine but does not tell you the image format of BitmapImage objects (at least I am not aware of a property for this)...
Validate image from file in C#
[ "", "c#", ".net", "image", "file-io", "" ]
I have a String which I would like to modify in some way. For example: reverse it or upcase it. I have discovered that the fastest way to do this is by using a unsafe block and pointers. For example: ``` unsafe { fixed (char* str = text) { *str = 'X'; ...
The .Net framework requires strings to be immutable. Due to this requirement it is able to optimise all sorts of operations. [String interning](http://en.wikipedia.org/wiki/String_intern_pool) is one great example of this requirement is leveraged heavily. To speed up some string comparisons (and reduce memory consumpt...
> Are there any reasons why I should never ever do this? Yes, very simple: Because .NET relies on the fact that strings are immutable. Some operations (e.g. `s.SubString(0, s.Length)`) actually return a reference to the original string. If this now gets modified, all other references will as well. Better use a `Strin...
Why should I never use an unsafe block to modify a string?
[ "", "c#", ".net", "" ]
If we are writing about power-wise option - is using a console-based application in C#(.NET) better than having Windows GUI and what's the real difference expept few libraries loaded in operational memory? The issue is about text comparisons and working with strings, connecting to Internet, gathering data, working wit...
From your description it seems that you want to write an HTML scraping software or some kind of web spider. I think your decision whether to write a GUI or a command line application should depend on who (users) or which other software components will use or integrate your program. If there is no user interaction invo...
I'm not entirely sure what your requirements are. GUIs tend to be harder to write than console apps, but open up a great level of usability (if you design them well, which is another matter entirely). If it's a simple tool that doesn't really need interactivity: start with some command line arguments, process and repo...
Powerwise: Is it better to use console or windows GUI application in C#(.NET)?
[ "", "c#", "windows", "user-interface", "console", "" ]
I am trying to call out to a legacy dll compiled from FORTRAN code. I am new to Interop, but I've read some articles on it and it seems like my case should be fairly straightforward. The method I really want to call has a complex method signature, but I can't even call this simple GetVersion method without getting a p...
OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works: ``` [DllImport("GeoConvert.dll", EntryPoint="_get_version@4", CallingConvention=CallingConvention.StdCall)] public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPArray)] ...
...snip... OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works: ...snip... You need to pass by reference because that is the semantic being used by the FORTRAN code. The client code is passing in a buffer that the FORTRAN code is going to write to in lieu of using a return value. .....
Protected Memory Violation calling FORTRAN DLL from C#
[ "", "c#", ".net", "interop", "fortran", "dllimport", "" ]
My colleague insists on explicitly specifying the namespace in code as opposed to using the [using directive](http://msdn.microsoft.com/en-us/library/sf0df423.aspx). In other words he wants to use the fully qualified name for each type every time this type occurs in code. Something like ``` public class MyClass { ...
For a slightly different answer: LINQ. Extension methods are obtained only via "using" statements. So either the query syntax or the fluent interface will *only* work with the right "using" statements. Even without LINQ, I'd say use "using"... reasoning that the more you can understand in fewer characters, the better...
If you need to copy and paste code around so much as to actually benefit of having fully qualified types, you've got bigger problems. Also, do you plan on remembering which namespace every single class is in in order to be able to type it fully qualified?
Should I agree to ban the "using" directive from my C# projects?
[ "", "c#", ".net", "" ]
I want to find a sql command or something that can do this where I have a table named tblFoo and I want to name it tblFooBar. However, I want the primary key to also be change, for example, currently it is: ``` CONSTRAINT [PK_tblFoo] PRIMARY KEY CLUSTERED ``` And I want a name change to change it to: ``` CONSTRAINT ...
This is just off the top of my head and isn't complete (you'd need to add similar code for indexes). Also, you would need to either add code to avoid renaming objects from a table with the same base name, but additional characters - for example, this code would also list tblFoo2 and all of its associated objects. Hopef...
Good answer by Tom I've just extended his query here to include indexes ``` declare @old nvarchar(100), @new nvarchar(100) set @old = 'OldName' set @new = 'NewName' select 'EXEC sp_rename ''' + name + ''', ''' + REPLACE(name, @old, @new) + '''' from sys.objects where name like '%' + @old + '%' union -- ind...
Renaming Tables SQL Server, cascading that change through PK and FK's
[ "", "sql", "sql-server", "t-sql", "rename", "" ]
In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as `(void*)0`. You could not assign NULL to any pointer other than `void*`, which made it kind of useless. Back in those days, it was accepted that you used `0` (zero) for null pointers. To this day, I have continued to u...
Here's Stroustrup's take on this: [C++ Style and Technique FAQ](http://www.stroustrup.com/bs_faq2.html#null) > In C++, the definition of `NULL` is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with `NULL` is that people sometimes mistakenly believe that it is differ...
There are a few arguments (one of which is relatively recent) which I believe contradict Bjarne's position on this. 1. **Documentation of intent** Using `NULL` allows for searches on its use and it also highlights that the developer **wanted** to use a `NULL` pointer, irrespective of whether it is being interprete...
Do you use NULL or 0 (zero) for pointers in C++?
[ "", "c++", "null", "" ]
I'm building a Lifestreaming app that will involve pulling down lots of feeds for lots of users, and performing data-mining, and machine learning algorithms on the results. GAE's load balanced and scalable hosting sounds like a good fit for a system that could eventually be moving around a LOT of data, but it's lack of...
While I can not answer your question directly, my experience of building [Microupdater](https://github.com/juvenn/microupdater) (a news aggregator collecting a few hundred feeds on AppEngine) may give you a little insight. * Fetching feeds. Fetching lots of feeds by cron jobs (it was the only solution until SDK 1.2.5)...
It might change when they offer paid plans, but as it stands, App Engine is not good for CPU intensive apps. It is designed to scale to handle a large number of requests, not necessarily a large amount of calculation per request. I am running into this issue with fairly minor calculations, and I fear I may have to star...
Is Google App Engine a worthy platform for a Lifestreaming app?
[ "", "python", "django", "google-app-engine", "web-applications", "" ]
I have a table that holds only two columns - a ListID and PersonID. When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person. Ideally, I would like to call something simple like ``` UPDATE MailingListSubscription SET Perso...
``` --out with the bad DELETE FROM MailingListSubscription WHERE PersonId = @SourcePerson and ListID in (SELECT ListID FROM MailingListSubscription WHERE PersonID = @DestPerson) --update the rest (good) UPDATE MailingListSubscription SET PersonId = @DestPerson WHERE PersonId = @SourcePerson ```
I have to agree with David B here. Remove all the older stuff that shouldn't be there and then do your update.
Merging contacts in SQL table without creating duplicate entries
[ "", "sql", "t-sql", "duplicate-data", "" ]
Is there a way of programmatically determining a rough geographical position of a mobile phone using J2ME application, for example determining the current cell? This question especially applies to non-GPS enabled devices. I am not looking for a set of geographical coordinates, but an ability for a user to define locat...
If the device supports the [JSR 179](http://jcp.org/en/jsr/detail?id=179) location API, you can use this. Last time I looked into this hardly any devices supported it, but that was a few years back.
this is my first post one stackoverflow. You can get the cellID (The id of the phone pole that the mobile is connected to) on a lot of phones thru **`System.getProperty(String arg)`** Here i have an example that tries a few keys to see if a cellID can be found. I have tested this on a lot of SonyEricsson mobiles and i...
Geographical position from Java mobile application?
[ "", "java", "java-me", "mobile", "gis", "mobile-phones", "" ]
Anyone have any idea how to get the value of "Language for Non-Unicode Programs" in Control Panel Regional Settings programmatically using c#? Already tried CultureInfo, RegionInfo and getting the default encoding using the Encoding object, but I can only get the Standards and Formats value or the main code page.
[GetSystemDefaultLocaleName](https://msdn.microsoft.com/en-us/library/dd318122(v=vs.85).aspx) or [GetSystemDefaultLCID](https://msdn.microsoft.com/en-us/library/dd318121(v=vs.85).aspx) (and its [P/Invoke declaration](http://pinvoke.net/default.aspx/kernel32/GetSystemDefaultLCID.html))
The [NLS Terminology](https://msdn.microsoft.com/en-us/library/dd319088(v=vs.85).aspx#Language_for_Non-Unicode_Programs) page in *Internationalization for Windows Applications* has the answer: > An ANSI application should check the language for non-Unicode programs setting during installation. It uses **[GetACP](https...
Getting Language for Non-Unicode Programs
[ "", "c#", "" ]
What is the most efficient way to write the old-school: ``` StringBuilder sb = new StringBuilder(); if (strings.Count > 0) { foreach (string s in strings) { sb.Append(s + ", "); } sb.Remove(sb.Length - 2, 2); } return sb.ToString(); ``` ...in LINQ?
**This answer shows usage of LINQ (`Aggregate`) as requested in the question and is not intended for everyday use. Because this does not use a `StringBuilder` it will have horrible performance for very long sequences. For regular code use `String.Join` as shown in the other [answer](https://stackoverflow.com/a/218419/4...
``` return string.Join(", ", strings.ToArray()); ``` --- In .Net 4, there's a new [overload](http://msdn.microsoft.com/en-us/library/dd783876.aspx) for `string.Join` that accepts `IEnumerable<string>`. The code would then look like: ``` return string.Join(", ", strings); ```
Using LINQ to concatenate strings
[ "", "c#", "linq", "string-concatenation", "" ]
in my application (c# 3.5) there are various processes accessing a single xml file (read and write) very frequently. the code accessing the file is placed in an assembly referenced by quite a couple of other applications. for example a windows service might instanciate the MyFileReaderWriter class (locatied in the prev...
To start with, make sure that all access to the XML Document is done through a single instance. Then put a lock mechanism (that wait for unlock) at the beginning of the function that access it and unlock it at the end.
If by writing you're only appending to the document, then try this <http://msdn.microsoft.com/en-us/library/aa302289.aspx> Basically your xml document is a shell with a start and end tag. Between the tags is an include reference, that references another file, this other file is the body of the xml document. For write...
How to access a file with the least amount of locking
[ "", "c#", "file", "locking", "io", "" ]
As a complete beginner with no programming experience, I am trying to find beautiful Python code to study and play with. Please answer by pointing to a website, a book or some software project. I have the following criterias: * complete code listings (working, hackable code) * beautiful code (highly readable, simple ...
Buy [Programming Collective Intelligence](https://rads.stackoverflow.com/amzn/click/com/0596529325). Great book of interesting AI algorithms based on mining data and all of the examples are in very easy to read Python. The other great book is [Text Processing in Python](https://rads.stackoverflow.com/amzn/click/com/03...
Read the Python libraries themselves. They're working, hackable, elegant, and instructional. Some is simple, some is complex. Best of all, you got it when you downloaded Python itself. It's in your Python library directory. Nothing more to do except start poking around.
Beginner looking for beautiful and instructional Python code
[ "", "python", "" ]
I am trying to install PHP onto my development box (XP SP3 / IIS 5.1) I've got PHP 5.2.6 stable downloaded (the MSI installer package) and I am getting an error "Cannot find httpd.conf". After that the install seems to breeze by quickly (more quickly than I would have expected) and when I try to execute a simple PHP sc...
Not sure if you already have this but I use WAMP from <http://www.wampserver.com/en> It's easy and simple to set up, it has an icon in the system tray to show that its active and you can make it go online or available to the outside by clicking the icon and setting it. I used this when I was first learning PHP since i...
Probably the installer didn't configure your server to use PHP properly. Check out Microsoft's page on [enabling PHP on IIS](http://www.iis.net/php) or alternatively switch to Apache if that's a viable option.
Install PHP on XP / IIS 5.1?
[ "", "php", "windows-xp", "installation", "windows-installer", "" ]
On our site, we get a large amount of photos uploaded from various sources. In order to keep the file sizes down, we strip all [exif data](http://en.wikipedia.org/wiki/Exif) from the source using [mogrify](http://www.imagemagick.org/www/mogrify.html): ``` mogrify -strip image.jpg ``` What we'd like to be able to do ...
You can save a large amount of space, especially if you have a large number of images.. Add the following to text.txt (format of the IPTC tags taken from [here](http://www.narf.ssji.net/~shtrom/wiki/tips/imagemanipulation)): ``` 2#110#Credit="My Company" 2#05#Object Name="THE_OBJECT_NAME" 2#55#Date Created="2011-02-0...
[Exiftool](http://www.sno.phy.queensu.ca/~phil/exiftool/) looks like it would be an exact match for you. I haven't tried it but I'm now tempted to go and fix all my honeymoon photos which are marked 01/01/2074 because I forgot to reset the date after the batteries died.
How do I add exif data to an image?
[ "", "php", "image-processing", "imagemagick", "exif", "" ]
How do I go about setting a `<div>` in the center of the screen using jQuery?
I like adding functions to jQuery so this function would help: ``` jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px"); this.css("le...
I put a [jquery plugin](http://plugins.jquery.com/project/autocenter) here VERY SHORT VERSION ``` $('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'}); ``` SHORT VERSION ``` (function($){ $.fn.extend({ center: function () { r...
Using jQuery to center a DIV on the screen
[ "", "javascript", "jquery", "html", "css", "layout", "" ]
How to copy file(s) from one solaris 9 machine to another solaris 9 machine using only java? We have ssh access to both machines. The java program will run on one of those two machines. Update: rsync is not really an option. can't install it easily (UNIX team is, hum, hard to deal with)
use the ssh library jsch -- <http://www.jcraft.com/jsch/>. This program is used by ant to do ssh transfers. very good -- been there a long time(> 5 years), decent documentation.
You could use Runtime.exec() to launch [rsync](http://samba.anu.edu.au/rsync/).
copy files from one solaris 9 to another using java
[ "", "java", "ssh", "" ]
Could somebody please point me in the right direction for learning how to do networking in C#/.net 3.5? Code samples and explanations are welcome. Basically I am looking for how to do asynchronous/multithreaded server/client models. I am fairly comfortable with the basics in how to accomplish this in C++ with WinSock ...
If WCF meets your needs, it's worth looking at. [ZeroC](http://www.zeroc.com) and other alternative higher level libraries exist. Otherwise there are several different ways to work closer to the socket level if that's what you need. ### TcpClient/UdpClient These provide a relatively thin wrapper around the underlyin...
In .NET 3.5 world you should definitely learn [Windows Communication Foundation](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) - .NET framework for networking. Useful link: [Synchronous and Asynchronous Operations (in WCF)](http://msdn.microsoft.com/en-us/library/ms734701.aspx) You can find useful WCF ...
networking in .net/C#
[ "", "c#", ".net", "networking", "asynchronous", "" ]
Does anyone know if it is possible to reliably determine (programattically C/C++...) whether or not a firewall or IP filtering software is installed on a Windows PC? I need to detect whether a certain server IP is being blocked in my client software by the host OS. I don't need to worry about external hardware firewal...
After reading some of your comments in reply to other answers, I think this might actually be closer to what you're looking for. It might not catch every type of firewall but any major firewall vendor should be registered with the Security Center and therefore detected with this method. You could also combine this with...
There could be a hack if you can assume following: 1. Outgoing HTTP connections are allowed 2. You can run one of your own service on another server listening on port 80 Code your service to accept an IP [and a port or maybe a url]. It must return whether it was able to connect to the IP. This way you can find out w...
Determine if IP is blocked
[ "", "c++", "windows", "security", "networking", "" ]
I'm trying to get a query working that takes the values (sometimes just the first part of a string) from a form control. The problem I have is that it only returns records when the full string is typed in. i.e. in the surname box, I should be able to type gr, and it brings up green grey graham but at present it's no...
## There is an Access Method for that! If you have your "filter" controls on the form, why don't you use the Application.buildCriteria method, that will allow you to add your filtering criterias to a string, then make a filter out of this string, and build your WHERE clause on the fly? ``` selectClause = "SELECT TabC...
You have your LIKE expression backwards. I have rewritten the query to remove the unnecessary IIF commands and to fix your order of operands for the LIKE operator: ``` SELECT TabCustomers.* FROM TabCustomers WHERE (Forms!FrmSearchCustomer!SearchMember Is Null Or Forms!FrmSearchCustomer!SearchMember=[customerid]) And ...
Returning records that partially match a value
[ "", "sql", "ms-access", "sql-like", "" ]
I have derived a TabControl with the express purpose of enabling double buffering, except nothing is working as expected. Here is the TabControl code: ``` class DoubleBufferedTabControl : TabControl { public DoubleBufferedTabControl() : base() { this.DoubleBuffered = true; this.SetStyle ...
If you read the documentation, it says, "This member is not meaningful for this control." If you want the control to be drawn utilizing double-buffering, you'll have to implement it yourself. Besides the fact that if you owner-draw the control, you would have to implement double-buffering yourself anyhow.
First of all, you can get rid of your `TabControl` code—you turn on buffering, and then immediately turn it off, so it's not actually doing anything useful. Part of your problem is that you're trying to paint just *part* of the `TabControl`. The easiest solution that gives about a 90% solution (it's still possible to...
Double buffering problem of a derived owner-drawn TabControl?
[ "", "c#", "tabcontrol", "doublebuffered", "ownerdrawn", "" ]
I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?
Check the `AUTH_USER` request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user. In an Active Directory domain, if your clients are running Internet Explorer and your web se...
I've got php mysql running on IIS - I can use `$_SERVER["AUTH_USER"]` *if* I turn on Windows Authentication in IIS -> Authentication and turn off Anonymous authentication (important) I've used this to get my user and domain: ``` $user = $_SERVER['AUTH_USER']; ``` `$user` will return a value like: `DOMAIN\username` o...
Can you get a Windows (AD) username in PHP?
[ "", "php", "windows", "authentication", "" ]
In Python, I want to make **selected** instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer bel...
You should use the `@property` decorator. ``` >>> class a(object): ... def __init__(self, x): ... self.x = x ... @property ... def xval(self): ... return self.x ... >>> b = a(5) >>> b.xval 5 >>> b.xval = 6 Traceback (most recent call last): File "<stdin>", line 1, in <module> Att...
Here's how: ``` class whatever(object): def __init__(self, a, b, c, ...): self.__foobar = 1 self.__blahblah = 2 foobar = property(lambda self: self.__foobar) blahblah = property(lambda self: self.__blahblah) ``` (Assuming `foobar` and `blahblah` are the attributes you want to be read-only.) Prepending ...
What is the easiest, most concise way to make selected attributes in an instance be readonly?
[ "", "python", "attributes", "readonly", "" ]
Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like ``` FindAllPostByTags(IList<Tag> tags) ``` that returns all Posts that have all (not just some of) the Tags in the ...
You could also just use an `IN` statement ``` DetachedCriteria query = DetachedCriteria.For<Post>(); query.CreateCriteria("Post").Add(Expression.In("TagName", string.Join(",",tags.ToArray()) ); ``` I haven't compiled that so it could have errors
I don't have a system at hand with a Castle install right now, so I didn't test or compile this, but the code below should about do what you want. ``` Junction c = Expression.Conjunction(); foreach(Tag t in tags) c = c.Add( Expression.Eq("Tag", t); return sess.CreateCriteria(typeof(Post)).Add(c).List(); ```
C# + Castle ActiveRecord: HasAndBelongsToMany and collections
[ "", "c#", ".net", "nhibernate", "hql", "castle-activerecord", "" ]
I recently wrote a DLL in C# (.Net 2.0) which contains a class that requires an IP address. A co-worker of mine altered the class to retrieve the IP from a ".dll.config" (XML) file -- This apparently is automatically generated by the "Application Settings" file he created (Settings1.settings). The benefit of this was t...
I'm addressing this exact issue in an application I'm in the midst of prototyping. Although Decker's suggestion of hacking the config files together should work I think this is a pretty inconvenient manual hack to perform as part of a build cycle. Instead of that I've decided that the cleanest solution is to just have ...
I use this technique all time time. Often I have a library assembly that requires certain settings, and I need them set both by testing projects as well as the primary "executable" assemblies -- be they web projects or Windows service projects. You're correct in that when you create a settings file for any project, it...
Settings.Default.<property> always returns default value instead of value in persistant storage (XML file)
[ "", "c#", ".net", "dll", "application-settings", "" ]
``` foreach($arrayOne as $value){ do function } ``` In the above example, I'd like to pass $arrayOne into a loop, have a function operate that removes some elements of $arrayOne and then have the loop pass over the reduced $arrayOne on the elements that are left until the loop returns false. Recommendations?
If you want to make modifications to the value of array items, use by reference. If you want to entirely remove array items, split out the key / value pairs. ``` $arrayOne = array('example', 'listing of', 'stuff'); foreach ($arrayOne as $key => &$value) { $value .= ' alteration'; if ($value == 'listing of al...
Do you just need a function to remove some elements of an array? If so, you can use [array\_filter](http://uk.php.net/array_filter).
Replacing array in foreach loop with array modified in same loop
[ "", "php", "loops", "" ]
I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end. Whe...
Sounds like a job for XMLUnit * <http://www.xmlunit.org/> * <https://github.com/xmlunit> Example: ``` public class SomeTest extends XMLTestCase { @Test public void test() { String xml1 = ... String xml2 = ... XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences // can also compar...
The following will check if the documents are equal using standard JDK libraries. ``` DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setCoalescing(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); DocumentBuilder db = dbf.newDocume...
Best way to compare 2 XML documents in Java
[ "", "java", "xml", "testing", "parsing", "comparison", "" ]
Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.
From <http://www.codeave.com/javascript/code.asp?u_log=7004>: ``` var input = document.getElementById('myTextInput'); input.focus(); input.select(); ``` ``` <input id="myTextInput" value="Hello world!" /> ```
In your input tag, place the following: ``` onFocus="this.select()" ```
how to auto select an input field and the text in it on page load
[ "", "javascript", "html", "" ]
I know you can just use CSS to hide the DIV or Silverlight Plugin, but is there a way to instantiate a Silverlight Component/App using JavaScript that doesn't show any UI element at all? There is alot of great functionality in Silverlight, like MultiThreading and compiled code, that could be utilized by traditional Aj...
Yes you can, and some of the reasons you make makes perfect sense. I did a talk on the HTML bridge at CodeCampNZ some weeks back, and have [a good collection of resources](http://jonas.follesoe.no/2008/09/01/unit-testing-presentation-model-and-the-html-bridge-at-codecamp-nz/) up on my blog. I also recommend checking o...
Yes. I think this is particularly intriguing when mixed with [other dynamic languages](http://www.codeplex.com/sdlsdk) -- but then, I'm probably biased. :) **Edit:** But you'd need to use the managed Javascript that's part of the Silverlight Dynamic Languages SDK and not the normal Javascript that's part of the browse...
Can you use Silverlight with AJAX without any UI element?
[ "", "javascript", "ajax", "silverlight", "" ]
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like `obj.attr` ? Or perhaps write get accessors ? What are the accepted naming styles for such things ? **Edit:** Can you elaborate on the best-practices of naming attributes with a single or doub...
The generally accepted way of doing things is just using simple attributes, like so ``` >>> class MyClass: ... myAttribute = 0 ... >>> c = MyClass() >>> c.myAttribute 0 >>> c.myAttribute = 1 >>> c.myAttribute 1 ``` If you do find yourself needing to be able to write getters and setters, then what you want to lo...
With regards to the single and double-leading underscores: both indicate the same concept of 'privateness'. That is to say, people will know the attribute (be it a method or a 'normal' data attribute or anything else) is not part of the public API of the object. People will know that to touch it directly is to invite d...
Python object attributes - methodology for access
[ "", "python", "oop", "object", "attributes", "" ]
Just wondering what the difference between `BeginInvoke()` and `Invoke()` are? Mainly what each one would be used for. EDIT: What is the difference between creating a threading object and calling invoke on that and just calling `BeginInvoke()` on a delegate? or are they the same thing?
Do you mean `Delegate.Invoke`/`BeginInvoke` or `Control.Invoke`/`BeginInvoke`? * `Delegate.Invoke`: Executes synchronously, on the same thread. * `Delegate.BeginInvoke`: Executes asynchronously, on a `threadpool` thread. * `Control.Invoke`: Executes on the UI thread, but calling thread waits for completion before cont...
Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want. In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially...
What's the difference between Invoke() and BeginInvoke()
[ "", "c#", ".net", "multithreading", "invoke", "begininvoke", "" ]
The Mutex class is very misunderstood, and Global mutexes even more so. What is good, safe pattern to use when creating Global mutexes? One that will work * Regardless of the locale my machine is in * Is guaranteed to release the mutex properly * Optionally does not hang forever if the mutex is not acquired * Deals ...
I want to make sure this is out there, because it's so hard to get right: ``` using System.Runtime.InteropServices; //GuidAttribute using System.Reflection; //Assembly using System.Threading; //Mutex using System.Security.AccessControl; //MutexAccessRule using System.Security.Princi...
Using the accepted answer I create a helper class so you could use it in a similar way you would use the Lock statement. Just thought I'd share. Use: ``` using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock { //Only 1 of these runs at a time RunSomeStuff(); } ``` And the helper class: ``` ...
What is a good pattern for using a Global Mutex in C#?
[ "", "c#", "concurrency", "mutex", "" ]
Is it possible to assign a custom ID to a HTTP session through Servlet API? I know that session handling from any application server, Tomcat for example, it's enough good to generate unique IDs. But I have custom unique session IDs based on information per user and time, so it won't be repeated. And I looked at every...
If you are using Tomcat, you may be able to create a custom session manager (see [this discussion](http://markmail.org/message/im3wkoeskkgjaphv#query:tomcat%20custom%20session%20Manager+page:1+mid:lgl2bdm26avvjx37+state:results)). You would then have access to the Tomcat [Session](http://tomcat.apache.org/tomcat-6.0-do...
The servlet API does not support creating your own cookie value. In fact, it does not guarantee that sessions are maintained via cookies... it specifically states that they can be maintained via a mechanism such as "URL Rewriting". It DOES guarantee that the session is maintained in some fashion, and that pretty much r...
Custom ID in session handling by Java Servlet API
[ "", "java", "session", "web-applications", "servlets", "" ]
What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that.
This should do it: ``` [^\x00-\x7F]+ ``` It matches any character which is not contained in the [ASCII character set](http://en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange) (0-127, i.e. 0x0 to 0x7F). You can do the same thing with Unicode: ``` [^\u0000-\u007F]+ ``` For unicode you can loo...
``` var words_in_text = function (text) { var regex = /([\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u05...
Regular expression to match non-ASCII characters?
[ "", "javascript", "jquery", "regex", "" ]
I have read the post [here](http://www.julienlecomte.net/blog/2007/10/28/) about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below code works fine for a small number of options, but when the number of options gets too big my "plea...
Here is a solution: ``` function appendToSelect() { $("#mySelect").children().remove(); $("#mySelect").html( '<option selected value="'+obj.data[0].value+'">' + obj.data[0].name + '</option>' ); obj.data.splice(0, 1); // we only want remaining data var appendOptions = function() { var dataChu...
It just so happens that I was posting about this a moment ago [here](https://stackoverflow.com/questions/205631/javascript-loadingbusy-indicator-or-transparent-div-over-page-on-event-click#210931). Here is a timed loop function: ``` function processLoop( actionFunc, numTimes, doneFunc ) { var i = 0; var f = functi...
How can I give control back (briefly) to the browser during intensive JavaScript processing?
[ "", "javascript", "jquery", "" ]
I am working on a stored procedure with several optional parameters. Some of these parameters are single values and it's easy enough to use a WHERE clause like: ``` WHERE (@parameter IS NULL OR column = @parameter) ``` However, in some instances, the WHERE condition is more complicated: ``` WHERE (@NewGroupId IS NUL...
The main problem is likely to be [parameter sniffing](http://omnibuzz-sql.blogspot.com/2006/11/parameter-sniffing-stored-procedures.html), and wildly different optimal execution plans depending on which of your parameters are NULL. Try running the stored proc with [RECOMPILE](http://www.sqlmag.com/Article/ArticleID/943...
I would create separate queries for the parameter being available or not. This will create simpler SQL, and the optimizer will do a better job. Like this: ``` if (@parameter IS NULL) then begin select * from foo end else begin select * from foo where value = @parameter end ``` In you have to many parameters t...
Working with optional stored procedure parameters
[ "", "sql", "database", "" ]
The javascript `Date("mm-dd-yyyy")` constructor doesn't work for FF. It works fine for IE. * IE : `new Date("04-02-2008")` => `"Wed Apr 2 00:00:00 EDT 2008"` * FF2 : `new Date("04-02-2008")` => `Invalid Date` So let's try another constructor: `Date("yyyy", "mm", "dd")`. * IE: `new Date("2008", "04", "02");` => `"Fri...
It is the [definition of the Date object](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date) to use values 0-11 for the `month` field. I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the co...
nice trick indeed, which I just found out the hard way (by thinking through it). But I used a more natural date string with a hyphen :-) ``` var myDateArray = "2008-03-02".split("-"); var theDate = new Date(myDateArray[0],myDateArray[1]-1,myDateArray[2]); alert(theDate); ```
Javascript Date() constructor doesn't work
[ "", "javascript", "date", "" ]
Consider the following interface in Java: ``` public interface I { public final String KEY = "a"; } ``` And the following class: ``` public class A implements I { public String KEY = "b"; public String getKey() { return KEY; } } ``` Why is it possible for class A to come along and override ...
Despite the fact that you are shadowing the variable it's quite interesting to know that you can change final fields in java as you can read [here](http://www.javaspecialists.co.za/archive/Issue096.html): > **Java 5 - "final" is not final anymore** > > Narve Saetre from Machina Networks in Norway sent me a note yester...
You are hiding it, it's a feature of "Scope". Any time you are in a smaller scope, you can redefine all the variables you like and the outer scope variables will be "Shadowed" By the way, you can scope it again if you like: ``` public class A implements I { public String KEY = "b"; public String getKey() { ...
Why can final constants in Java be overridden?
[ "", "java", "interface", "overriding", "final", "" ]
Is it possible with Axis2 and Eclipse to generate a Web Service client and have it use java types that you already have in packages instead of creating it's own types. Reason being of course if I have type A already created and it creates it's own Type A I can't just assign variable of type A to variable of type B. Th...
If you really want to reuse existing classes, you can call the Axis2 API directly without generating a client using wsdl2java. Below is some relatively simple code to call a web service. You just need to fill in the web service endpoint, method QName, expected return Class(es), and arguments to the service. You could r...
You are generating the web service client from wsdl, correct? The only thing that the wsdl2java tool knows about is the information in the wsdl, so it won't know about any types that you have already created. If you can get the type information into the wsdl you may get it to work, although I have never tried. If yo...
Axis2 Web Service Client Generation - Types without modifying the client
[ "", "java", "code-generation", "apache-axis", "wsdl2java", "" ]
OK, so I'm trying to teach myself the CakePHP framework, and I'm trying to knock up a simple demo app for myself. I have the controllers, views and models all set up and working, but I want to do something slightly more than the basic online help shows. I have a guitars\_controller.php file as follows... ``` <?php c...
These actions are model agnostic so can be put in your app/app\_controller.php file ``` <?php class AppController extends Controller { function index() { $this->set(Inflector::variable($this->name), $this->{$this->modelClass}->findAll()); $this->pageTitle = 'All '.Inflector::humanize($this->name); ...
You can set this in the controller: ``` function view($id = null) { $guitar = $this->Guitar->read(null, $id); $this->set('guitar', $guitar); $this->pageTitle = $guitar['Guitar']['name']; } ``` Or in the view: ``` <? $this->pageTitle = $guitar['Guitar']['name']; ?> ``` The value set in the view will over...
CakePHP - How do i set the page title to an item name?
[ "", "php", "cakephp", "" ]
Ruby can add methods to the Number class and other core types to get effects like this: ``` 1.should_equal(1) ``` But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Rather than talking about different definitions of monkey...
What exactly do you mean by Monkey Patch here? There are [several slightly different definitions](http://wikipedia.org/wiki/Monkey_patch). If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes: ``` class Foo: pass # dummy class Foo.bar = lambda self: 42 x = Foo() print x...
No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process. (Multiple...
Can you monkey patch methods on core types in Python?
[ "", "python", "programming-languages", "monkeypatching", "fluent-interface", "" ]
I'm using .NET 3.5 and I have a class, A, marked as internal sealed partial and it derives from System.Configuration.ApplicationSettingsBase. I then use an instance of this class in the following manner: ``` A A_Instance = new A(); A_Instance.Default.Save(); ``` Why would the Visual C# compiler be complaining: ``` e...
You are probably looking for this: ``` private static ServerSettings defaultInstance = ((ServerSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ServerSettings()))); public static ServerSettings Default { get { return defaultInstance; } } ``` This is the code that gets generate...
.NET doesn't provide a 'Default' member in ApplicationSettingsBase from which to access any methods. What I failed to notice was that 'Default' was being used as a singleton of A. Thus, the sample code provided by gdean2323 gave me some guidance to the fix. The code to fix the problem required me adding the following c...
How come I can't see member 'Default' on a class derived from ApplicationSettingsBase?
[ "", "c#", ".net", "" ]
I've got an error in my build which says: > Error 12 Cannot implicitly convert > type > 'System.Collections.Generic.IEnumerator< BaseClass>' > to > 'System.Collections.Generic.IEnumerator< IParentClass>'. > An explicit conversion exists (are you > missing a cast?) Is it wrong to simply cast it away? This is my code:...
No you can't, because generics aren't covariant in C# at the moment. .NET itself has some support (for delegates and interfaces) but it's not really used yet. If you were returning `IEnumerable<BaseClass>` instead of `IEnumerator<BaseClass>` (and assuming .NEt 3.5) you could use `Enumerable.Cast` - but you'll currentl...
No, you can't, at least in C# 3.0 and below interface variance is not supported. See Eric Lippert's excellent series on this, and specifically [this one](http://blogs.msdn.com/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx).
Is it wrong to cast an enumerator of a child class to an enumerator of a parent class?
[ "", "c#", ".net", "generics", "covariance", "" ]
I have a native VC++ project that uses a dll (which is not in a project). Now, I must to put the dll in one the "Search Path Used by Windows to Locate a DLL" [link](http://msdn.microsoft.com/en-us/library/7d83bc18(VS.80).aspx) but I don't want the dll to sit in the exectuable or current or windows or system directory....
Summing up all the techniques I have found: * If you use a managed project as the startup project (which is actually my case) use Enviroment class string temp = "myFullDirectoryPathToDll"; string temp2 =Environment.GetEnvironmentVariable("PATH") + ";" + temp; Environment.SetEnvironmentVariable("PATH", temp2); this...
Here are a few suggestions: * You could embed the dll as a resource in your main executable and then extract it to a temporary directory and load it from their using LoadLibrary and then get the relevant function addresses using GetProcAddress. * You could modify you main processes search path using [SetDllDirectory()...
Native VC++ using external (not project) dll reference how to specify path to dll
[ "", "c++", "dll", "visual-studio-2005", "native", "" ]
For an `std::map<std::string, std::string> variables`, I'd like to do this: ``` BOOST_CHECK_EQUAL(variables["a"], "b"); ``` The only problem is, in this context `variables` is `const`, so `operator[]` won't work :( Now, there are several workarounds to this; casting away the `const`, using `variables.count("a") ? va...
``` template <typename K, typename V> V get(std::map<K, V> const& map, K const& key) { std::map<K, V>::const_iterator iter(map.find(key)); return iter != map.end() ? iter->second : V(); } ``` Improved implementation based on comments: ``` template <typename T> typename T::mapped_type get(T const& map, typenam...
Casting away const is wrong, because operator[] on map<> will create the entry if it isn't present with a default constructed string. If the map is actually in immutable storage then it will fail. This must be so because operator[] returns a non-const reference to allow assignment. (eg. m[1] = 2) A quick free function...
Idiomatic C++ for reading from a const map
[ "", "c++", "stl", "" ]
In asp.net, you can retrieve MULTIPLE datatables from a single call to the database. Can you do the same thing in php? Example: ``` $sql ="select * from t1; select * from t2;"; $result = SomeQueryFunc($sql); print_r($result[0]); // dump results for t1 print_r($result[1]); // dump results for t2 ``` Can you do someth...
This is called "multi-query." The mysql extension in PHP does not have any means to enable multi-query. The mysqli extension does allow you to use multi-query, but only through the multi\_query() method. See <http://php.net/manual/en/mysqli.multi-query.php> Using multi-query is not recommended, because it can increase...
This should be possible with newer MySQL and the mysqli (improved) php extension. I'm not sure if any DB abstraction layers support this. See relevant [MySQL docs](http://dev.mysql.com/doc/refman/5.0/en/c-api-multiple-queries.html) and [PHP docs](http://php.net/manual/en/mysqli.multi-query.php).
Multiple Data Tables in PHP/MySQL?
[ "", "php", "mysql", "dataset", "" ]