Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)
```
static String intToString(int num, int digits) {
StringBuffer s = new StringBuffer(digits);
int zeroes = ... | String.format (<https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax>)
In your case it will be:
```
String formatted = String.format("%03d", num);
```
* 0 - to pad with zeros
* 3 - to set width to 3 | Since Java 1.5 you can use the `String.format` method. For example, to do the same thing as your example:
```
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
```
In this case, you're creating the format string using the width specified in digits, then applying... | Add leading zeroes to number in Java? | [
"",
"java",
""
] |
I'd like to strip out occurrences of a specific tag, leaving the inner XML intact. I'd like to do this with one pass (rather than searching, replacing, and starting from scratch again). For instance, from the source:
```
<element>
<RemovalTarget Attribute="Something">
Content Here
</RemovalTarget>
</elem... | You'll have to skip the deferred execution with a call to ToList, which probably won't hurt your performance in large documents as you're just going to be iterating and replacing at a much lower big-O than the original search. As @jacob\_c pointed out, I should be using element.Nodes() to replace it properly, and as @P... | Have you considered using XSLT? Seems like the perfect soution, as you are doing exactly what XSLT is meant for, transforming one XML doc into another. The templating system will delve into nested nastiness for you without problems.
[Here](http://www.w3schools.com/xsl/xsl_transformation.asp) is a basic example | strip out tag occurrences from XML | [
"",
"c#",
".net",
"xml",
"linq",
""
] |
I am working on a program which manipulates images of different sizes. Many of these manipulations read pixel data from an input and write to a separate output (e.g. blur). This is done on a per-pixel basis.
Such image mapulations are very stressful on the CPU. I would like to use multithreading to speed things up. Ho... | If your compiler supports [OpenMP](http://openmp.org/wp/) (I know [VC++ 8.0 and 9.0](http://msdn.microsoft.com/en-us/library/tt15eb9t(VS.80).aspx) do, as does gcc), it can make things like this much easier to do.
You don't just want to make a lot of threads - there's a point of diminishing returns where adding new thr... | **Don't embark on threading lightly!** The race conditions can be a major pain in the arse to figure out. Especially if you don't have a lot of experience with threads! **(You've been warned: Here be dragons! Big hairy non-deterministic impossible-to-reliably-reproduce dragons!)**
[Do you know what deadlock is? How ab... | Multithreaded image processing in C++ | [
"",
"c++",
"multithreading",
"optimization",
"image-processing",
"parallel-processing",
""
] |
In writing the code that throws the exception I asked about [here](https://stackoverflow.com/questions/259800/is-there-a-built-in-net-exception-that-indicates-an-illegal-object-state), I came to the end of my message, and paused at the punctuation. I realized that nearly every exception message I've ever thrown probabl... | A conversational tone in system messages makes the software look unprofessional and sloppy. Exclamation points, insults, and slang don't really have a place in polished exception messages.
Also, I tend to use different styles in Java for runtime exceptions and checked exceptions, since runtime exceptions are addressed... | I try to mirror the tone, grammar and punctuation style of the framework against which I'm coding. You never know when one of these messages might actually make it out in front of a client or user, so I keep everything professional, non-judgmental and specific enough for troubleshooting -- without being so specific as ... | What style do you use for exception messages? | [
"",
"c#",
".net",
"exception",
"logging",
"throw",
""
] |
How do you draw the following dynamic **3D** array with OpenGL **glDrawPixels()**?
You can find the documentation here: <http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html>
```
float ***array3d;
void InitScreenArray()
{
int i, j;
int screenX = scene.camera.vres;
int scree... | Uh ... Since you're allocating *each single pixel* with a separate `malloc()`, you will have to draw each pixel with a separate call to `glDrawPixels()`, too. This is (obviously) insane; the idea of bitmapped graphics is that the pixels are stored in an adjacent, compact, format, so that it is quick and fast (*O(1)*) t... | Thanks unwind. I got the same advice on [gamedev.net](http://www.gamedev.net/community/forums/topic.asp?topic_id=513674) so I have implemented the following algorithm:
```
typedef struct
{
GLfloat R, G, B;
} color_t;
color_t *array1d;
void InitScreenArray()
{
long screenX = scene.camera.vres;
long... | OpenGL glDrawPixels on dynamic 3D arrays | [
"",
"c++",
"arrays",
"opengl",
"graphics",
""
] |
I got a web application, the problem is that the text in the label will not update on the first click, I need to click the button twice, I debugged to code, and I found out that the label does not recive the data until after the second click,
Here is my code:
```
System.Data.SqlClient.SqlCommand command = new System.... | To be very clear. The button click event happens after the Page\_Load event meaning that the filtering does not get applied on the first postback. It has been updated on the second postback and you see the filtering. The simplest change to get your code to work is to move all the code in your Page\_Load event into OnPr... | Microsoft's overview of the [Page Life Cycle](http://msdn.microsoft.com/en-us/library/ms178472.aspx) may be helpful in understanding the flow (and resolving your issue). | ASP.NET C#, need to press a button twice to make something happen | [
"",
"c#",
"asp.net",
""
] |
I have this code :-
```
using (System.Security.Cryptography.SHA256 sha2 =
new System.Security.Cryptography.SHA256Managed())
{ .. }
```
Do I need to put this line of code, just BEFORE I leave that dispose scope .. or does the dispose 'call' that already.
```
sha2.Clear();
``` | Since AFAIK the Clear() method just calls Dispose, the using block should be enough to ensure that the resources used are released. | IMHO if calling Dispose() is not enough to dispose off an object then either there is a serious bug in the code or a serious flaw in the design. So don't worry about taking any additional steps in your own code! | Is disposing this object, enough? or do i need to do more? | [
"",
"c#",
".net",
"dispose",
"sha2",
""
] |
When I run a wxPython application, it prints the string “Redirecting output to win32trace remote collector”and I must open PythonWin's trace collector tool to view that trace output.
Since I'm not interested in collecting this output, how should I disable this feature? | You can even pass that when you instantiate your wx.App():
```
if __name__ == "__main__":
app = wx.App(redirect=False) #or 0
app.MainLoop()
```
[wxPython wx.App docs](http://wxpython.org/docs/api/wx.App-class.html#__init__) | This message deceived me into thinking win32trace was preventing me from seeing uncaught exceptions in the regular console (of my IDE). The real issue was that wxPython by default redirects stdout/stderr to a popup window that quickly disappeared after an uncaught exception. To solve *that* problem, I simply had to pas... | How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin? | [
"",
"python",
"windows",
"wxpython",
""
] |
Where can I find a free, lightweight YUI-like compressor for PHP?
I am sure it will decrease the file size but will compressing PHP code boost its performance?
Is this the same thing as an obfuscator? | There is a product called PHP Encoder by ionCube (<http://www.ioncube.com/sa_encoder.php>) which is enterprise grade compression and obfuscater.
PHP Encoder is a PHP extension to create and run compiled bytecodes for accelerated runtime performance and maximum security.
It will shrink the file size, and speed up runt... | Compressing JavaScript has benefits because the script has to be sent over the Net to the client before it can be interpreted -- the smaller the file size, the faster it reaches the end user. PHP is interpreted directly on the server, so compressing the code won't affect how fast it runs.
If it's speed gains you want,... | Where can I find a free, lightweight YUI-like compressor for PHP? | [
"",
"php",
"yui",
""
] |
I've been trying to deal with some delimited text files that have non standard delimiters (not comma/quote or tab delimited). The delimiters are random ASCII characters that don't show up often between the delimiters. After searching around, I've seem to have only found no solutions in .NET will suit my needs and the c... | Use the [File Helpers API](http://filehelpers.sourceforge.net/). It's .NET and open source. It's extremely high performance using compiled IL code to set fields on strongly typed objects, and supports streaming.
It supports all sorts of file types and custom delimiters; I've used it to read files larger than 4GB.
If ... | Windows and high performance I/O means, use [IO Completion](http://blogs.msdn.com/kavitak/archive/2003/12/15/Async-I_2F00_O-and-I_2F00_O-completion-ports.aspx) ports. You may have todo some extra plumbing to get it working in your case.
This is with the understanding that you want to use C#/.NET, and according to [Joe... | What is the fastest way to parse text with custom delimiters and some very, very large field values in C#? | [
"",
"c#",
"parsing",
"bulk",
"csv",
""
] |
In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:
```
import subprocess
subprocess.Popen('explorer "C:\path\of\folder"')
```
but I have no solution for files. | From [Geoff Chappell's *The Windows Explorer Command Line*](http://www.geoffchappell.com/studies/windows/shell/explorer/cmdline.htm)
```
import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
``` | A nicer and safer solution (only in Windows unfortunately) is [os.startfile()](https://docs.python.org/3.6/library/os.html#os.startfile).
When it's given a folder instead of a file, it will open Explorer.
Im aware that i do not completely answer the question since its not selecting a file, but using `subprocess` is a... | Open explorer on a file | [
"",
"python",
"windows",
"explorer",
""
] |
Did the recent purchase of MySQL by Sun and the subsequent buggy releases kill the MySQL brand?
I whole heartedly embraced MySQL when it first came out as I used to be a poor developer and all the RDBMs were too expensive. I have fond feelings for MySQL and their being able to compete with Oracle and SQL Server. I cre... | Having worked with both, I have to say that the limitations and/or bugs in MySQL were a big turn off for me... I don't like PHP, and while I respect the open source community for their advances with these two technologies I just can't see the elegance in the way either of them have been put together. But don't let my p... | So far no-one knows what Oracle is going to do to MySQL, not even Oracle.
I've done extensive testing of MySQL and would say that in terms of performance it is about at SQL Server 7.0 level. That is fine if all you need is the performance of SQL Server 7.0
At the enterprise level is simply doesn't compete. If you loo... | MySQL versus SQL Server Express | [
"",
"sql",
"mysql",
"sql-server",
""
] |
I'm hearing that some people believe storing info on the server in a session is a bad idea, that its not secure.
As a result, in a multi-page business process function, the application is writing data to a db, then retrieving the info when its needed.
Is there something necessarily unsafe about storing private inf... | There's not a security risk in storing attributes in a Session, as long as the session itself is safe from [hijacking](http://www.owasp.org/index.php/Session_hijacking_attack).
There are some serious issues involving concurrency and sessions. Since its extremely common for multiple threads to be making requests concur... | HTTP sessions themselves aren't inherently unsafe. However, depending on your application server / container, the mechanism in which session cookies are passed back to the browser (and lack of transport layer security - SSL) can allow malicious parties to perform a variety of attacks (cross-site scripting, session hija... | Java session variables | [
"",
"java",
"session",
"servlets",
"variables",
"jakarta-ee",
""
] |
When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:
```
f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
```
Is there an elegant way or idiom for retrieving text lines ... | The *idiomatic* way to do this in Python is to use **rstrip('\n')**:
```
for line in open('myfile.txt'): # opened in text-mode; all EOLs are converted to '\n'
line = line.rstrip('\n')
process(line)
```
Each of the other alternatives has a gotcha:
* **file('...').read().splitlines()** has to load the whole f... | Simple. Use **splitlines()**
```
L = open("myFile.txt", "r").read().splitlines();
for line in L:
process(line) # this 'line' will not have '\n' character at the end
``` | End-line characters from lines read from text file, using Python | [
"",
"python",
""
] |
Presently I'm starting to introduce the concept of Mock objects into my Unit Tests. In particular I'm using the Moq framework. However, one of the things I've noticed is that suddenly the classes I'm testing using this framework are showing code coverage of 0%.
Now I understand that since I'm just mocking the class, i... | You are not using your mock objects correctly. When you are using mock objects you meant to be testing how your code interacts with other objects without actually using the real objects. See the code below:
```
using Moq;
using NUnitFramework;
namespace MyNameSpace
{
[TestFixture]
public class MyC... | Big mistake is mocking the [System Under Test](https://en.wikipedia.org/wiki/System_under_test "System Under Test") (SUT), you test something else. You should mock only SUT dependencies. | How can I use Mock Objects in my unit tests and still use Code Coverage? | [
"",
"c#",
".net",
"unit-testing",
"moq",
"code-coverage",
""
] |
I'm working on some upgrades to an internal web analytics system we provide for our clients (in the absence of a preferred vendor or Google Analytics), and I'm working on the following query:
```
select
path as EntryPage,
count(Path) as [Count]
from
(
/* Sub-query 1 */
select
... | For starters,
```
where pv1.Domain = isnull(@Domain, pv1.Domain)
```
won't SARG. You can't optimize a match on a function, as I remember. | To continue from doofledorf.
Try this:
```
where
(@Domain is null or pv1.Domain = @Domain) and
v1.Campaign = @Campaign
```
Ok, I have a couple of suggestions
1. Create this covered index:
```
create index idx2 on [PageViews]([SessionID], Domain, Created, Path)
```
2. If you can amend the Sessions t... | T-SQL Query Optimization | [
"",
"sql",
"sql-server",
""
] |
I wonder what options there are for .NET (or C# specifically) code coverage, especially in the lower priced segment?
I am not looking for recommendations, but for a comparison of products based on facts. I know the following:
* [NCover](http://www.ncover.com/)
+ Seems to be very popular and looks quite good
+ Sup... | I use the version of NCover that comes with [TestDriven.NET](http://www.testdriven.net). It will allow you to easily right-click on your unit test class library, and hit *Test With→Coverage*, and it will pull up the report. | An alternative to NCover can be [PartCover](https://sourceforge.net/projects/partcover/), is an open source code coverage tool for .NET very similar to NCover, it includes a console application, a GUI coverage browser, and XSL transforms for use in [CruiseControl.NET](http://en.wikipedia.org/wiki/CruiseControl).
It is... | What can I use for good quality code coverage for C#/.NET? | [
"",
"c#",
".net",
"code-coverage",
""
] |
I'm build an UserControl and I'm not sure how to handle exceptions, the Control itself is not very complicated, the User chose an image from disk so they can authorize it, I don't know exactly how the control will be used so if I use a MessageBox I might block the application, and if I just re-throw it I might crash it... | this is a common problem facing developers who build libraries. Try to weed out bugs and decide for the remaining error cases if it's an expected error (your control should not throw an exception but rather gracefully handle the error) or an unexpected exceptional condition (your control must throw an exception as soon... | unhandled exceptions should definitely be thrown so that the people using your control can see what's wrong. | Correct way to Handle Exceptions in UserControl | [
"",
"c#",
"winforms",
".net-3.5",
""
] |
I've heard that there are some free applications that will check the vulnerability of a PHP website, but I don't know what to use. I'd like a free program (preferably with a GUI) for Windows that will analyze my site an give me a report.
Anyone know of a solution? | There are only certain security holes you can check for with any program. You can check your PHP configuration, Apache configuration, passwords, common bugs, etc. but you can't really check programatically for logic errors which might cause security holes.
Your best bet would be to do a thorough code review of the web... | [Top 10 Web Vulnerability Scanners](http://sectools.org/web-scanners.html) from Insecure.org (listing from 2006). Their number one, Nikto2, can be found [here](http://www.cirt.net/nikto2). | How can I check website security for free? | [
"",
"php",
"security",
""
] |
With Php when does an included file get included? Is it during a preprocessing stage or is it during script evaluation?
Right now I have several scripts that share the same header and footer code, which do input validation and exception handling. Like this:
```
/* validate input */
...
/* process/do task */
...
/* ha... | [PHP.net: include](http://fi.php.net/include/) gives a basic example:
```
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
```
so include happens when its executed in code.
Edit: fixed url. | PHP doesn't have a preprocessor. Starting a line with an '#' makes the line a comment. You have to do this to include a file:
```
include ("exception_handling.php");
include 'exception_handling.php'; // or this, the parentheses are optional
```
Read this for more information: <http://php.net/include> | In Php when is Include/Require evaluated? | [
"",
"php",
"include",
""
] |
I'm trying to convert a character code to a character with chr(), but VBScript isn't giving me the value I expect. According to VBScript, character code 199 is:
```
�
```
However, when using something like Javascript's String.fromCharCode, 199 is:
```
Ç
```
The second result is what I need to get out of VBScript'... | **Edited to reflect comments**
`Chr(199)` returns a 2-byte character, which is being interpreted as 2 separate characters.
* use `ChrW(199)` to return a `Unicode` string.
* use `ChrB(199)` to return it as a single-byte character | Encoding is the problem. Javascript may be interpreting as latin-1; VBScript may be using a different encoding and getting confused. | VBScript chr() appears to return wrong value | [
"",
"javascript",
"vbscript",
"fromcharcode",
"chr",
""
] |
How do you organize your stored procedures so you can easily find them and keep track of their dependencies? | I tend to name them according to a convention. Typically {TableName}\_{operation}{extra} where the extra part is optional.
For example: Product\_Get, Product\_Add, Product\_Delete, Product\_Update, Product\_GetByName | I'm strongly considering creating database projects so that I can version the stored procedures and avoid the confusion when deploying from development to production. Once they start getting out of synch with a large project, things can get difficult fast. | How do you manage and organize your stored procedures? | [
"",
"sql",
"stored-procedures",
""
] |
Say I have some code like
```
namespace Portal
{
public class Author
{
public Author() { }
private void SomeMethod(){
string myMethodName = "";
// myMethodName = "Portal.Author.SomeMethod()";
}
}
}
```
Can I find out the name of the method I am using? In my exam... | ```
MethodInfo.GetCurrentMethod().Name
``` | System.Reflection.MethodBase.GetCurrentMethod().Name | Can I find out the name of the method I am using? | [
"",
"c#",
"oop",
"reflection",
""
] |
I'm currently using the Yahoo YUI javascript library in a couple of my projects.
However, I'm a little concerned about three things. First, they laid off 10% of their employees. Second, their stock price keeps falling: especially after ignoring the MS takeover earlier this year. Third, what if someone does buy them?
... | Yahoo is a major company that won't end in the next couple of year.
The Yahoo! library is open source so you will have other people to continue to improve it IF Yahoo would go bankrupt.
No technology is 100% safe for 10 years perspective, I think you aren't in danger with it.
In 10 years Javascript will be completel... | As a member of the YUI team, I would add the following to this conversation: Almost everyone who has ever worked on the team is still with Yahoo and still working on YUI -- a remarkable consistency for a project that is now almost four years old. No one can predict the future of Yahoo at this point (or of any other com... | To YUI or not to YUI? | [
"",
"javascript",
"yui",
"yahoo",
""
] |
Per the Java documentation, the [hash code](http://java.sun.com/javase/6/docs/api/java/lang/String.html#hashCode()) for a `String` object is computed as:
> ```
> s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
> ```
>
> using `int` arithmetic, where `s[i]` is the
> *i*th character of the string, `n` is the length of
> th... | According to Joshua Bloch's [Effective Java, Second Edition](https://rads.stackoverflow.com/amzn/click/com/0321356683) (a book that can't be recommended enough, and which I bought thanks to continual mentions on Stack Overflow):
> The value 31 was chosen because it is an odd prime. If it were even and the multiplicati... | Goodrich and Tamassia computed from over 50,000 English words (formed as the union of the word lists provided in two variants of Unix) that using the constants 31, 33, 37, 39, and 41 will produce fewer than 7 collisions in each case. This may be the reason that so many Java implementations choose such constants.
See s... | Why does Java's hashCode() in String use 31 as a multiplier? | [
"",
"java",
"string",
"algorithm",
"hash",
""
] |
What I'd like to do is produce an HTML/CSS/JS version of the following. The gridlines and other aspects are not important. It's more of a question how to do the background databars.
[](https://i.stack.imgur.com/tPLAD.png)
(source: [tech-recipes.com](http://blogs.tech-r... | Make the bars as background images and position them to show values. eg. with a fixed column width of 100px:
```
<div style="background: url(bg.gif) -50px 0 no-repeat;">5</div>
<div style="background: url(bg.gif) -20px 0 no-repeat;">8</div>
```
If your columns have to be flexible size (not fixed, and not known at the... | A javascript-based solution like this [cross-browser gradient](http://slayeroffice.com/code/gradient/) might be a good start.
With some DHTML, you can make a [bar with a given length](http://slayeroffice.com/code/gradientProgressBar/). | How could you implement something like Excel 2007's databars in HTML/CSS/JS? | [
"",
"javascript",
"excel",
"user-interface",
""
] |
I'm trying to use some extension methods that I use to apply consistent formatting to DateTime and Int32 - which works absolutely fine in code behind, but I'm having issues with databinding.
I get:
```
'System.DateTime' does not contain a definition for 'ToCustomShortDate'
```
for
```
<%# ((ProductionDetails)Contai... | Found the issue! I was including the namespace correcly as I thought - but the real issue was that the app was only INCLUDING the .NET 3.5 assemblies and not being compiled using the 3.5 compiler, was missing some entries from web.config which I realised when I created an empty project and tried it (successfully) in th... | Regarding the extenstion method i implemented above should my namespace look like this?
```
namespace MyNamespace.Formatting
``` | Using extension methods within inline databinding context | [
"",
"c#",
"asp.net",
"data-binding",
"gridview",
"extension-methods",
""
] |
I am testing against the following test document:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>hi there</title>
</h... | The problem is the namespaces. When parsed as XML, the img tag is in the <http://www.w3.org/1999/xhtml> namespace since that is the default namespace for the element. You are asking for the img tag in no namespace.
Try this:
```
>>> tree.getroot().xpath(
... "//xhtml:img",
... namespaces={'xhtml':'http://www... | [XPath considers all unprefixed names to be in "no namespace"](http://www.w3.org/TR/xpath#node-tests).
In particular the spec says:
"A QName in the node test is expanded into an expanded-name using the namespace declarations from the expression context. This is the same way expansion is done for element type names in... | Why doesn't xpath work when processing an XHTML document with lxml (in python)? | [
"",
"python",
"xml",
"xhtml",
"xpath",
"lxml",
""
] |
I have a WCF Service that should not enter the faulted state. If there's an exception, it should be logged and the service should continue uninterrupted. The service has a one-way operation contract and is reading messages from an MSMQ.
My problems are twofold:
1. The service appears to be swallowing
an exception/... | Most, if not all exceptions can be seen in the WCF Trace ([Configuring Tracing](http://msdn.microsoft.com/en-us/library/ms733025.aspx)) and the trace is best viewed with the [Service Trace Viewer](http://msdn.microsoft.com/en-us/library/ms733025.aspx).
Obviously, this is not something you should have running all day i... | The official documentation on how to handle Faults is here:
* [**Handling Exceptions and
Faults**](http://msdn.microsoft.com/en-us/library/ms789039.aspx)
* [**Understanding State
Changes**](http://msdn.microsoft.com/en-us/library/ms789041.aspx)
with the main page being at [Channel Model Overview](http://msdn.micr... | How do I prevent a WCF service from enter a faulted state? | [
"",
"c#",
".net",
"wcf",
"msmq",
""
] |
I have a problem when assigning functions to the click event of a button in IE 7 with jQuery. Something like the following works fine in Opera but produces an infinite loop in IE:
```
function updateIndputFields(index, id) {
$("#reloadBtn").click(function(){ updateIndputFields(index, id) });
}
```
As I understand ... | I think the key to your answer is in unbinding the event that you have already bound to the click event. I used this on IE and, if I understand what you're trying to do, it seems to do what you need:
```
<script type="text/javascript">
function updateIndputFields(index, id) {
$('#output').append('<p>' + index + ' : ' ... | or just use [.one](http://docs.jquery.com/Events/one#typedatafn) to bind the event | jQuery callbacks firing too early | [
"",
"javascript",
"jquery",
"internet-explorer",
"callback",
""
] |
I am currently looking at the "unload" event of a window to try to determine how the "unload" event was triggered, but am having little success. Is there a way to determine how the javascript event was triggered?
* Page Refresh
* Back Button (or navigate away from the page)
* Closing the Browser
Essentially I need to... | No, and if there was it would be browser dependent.
What kind of code are you trying to run when the user closes the page?
Is it to logout the user?
Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).
If it is ... | Yes, there is a solution!
I've designed a solution based on onBeforeUnload+onLoad events, HTML5 local storage and client/server communication. See the details on <https://stackoverflow.com/a/13916847/698168>. | Is there a way in javascript to detect if the unload event is caused via a refresh, the back button, or closing the browser? | [
"",
"javascript",
"events",
""
] |
I've been using this function but I'd like to know what's the most efficient and accurate way to get it.
```
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
``` | ```
function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.
return new Date(year, month, 0).getDate();
}
console.log(daysInMonth(2, 1999)); // February in a non-leap year.
console.log(daysInMonth(2, 2000)); // February in a leap year.
```
Day 0 is the last day in the previous month. Because ... | Some answers (also on other questions) had leap-year problems or used the Date-object. Although javascript's `Date object` covers approximately 285616 years (100,000,000 days) on either side of January 1 1970, I was fed up with all kinds of unexpected date [inconsistencies](http://people.cs.nctu.edu.tw/~tsaiwn/sisc/run... | What is the best way to determine the number of days in a month with JavaScript? | [
"",
"javascript",
"date",
""
] |
I want to create a compiled JavaScript file for my website. For development I would prefer to keep the JavaScript in separate files and just as part of my automated scripts concatenate the files into one and run the compressor over it.
My problem is that if I use the old DOS copy command it also puts in the EOF marker... | I recommend using Apache Ant and YUI Compressor.
<http://ant.apache.org/>
<http://yui.github.com/yuicompressor/>
Put something like this in the Ant build xml.
It will create two files, application.js and application-min.js.
```
<target name="concatenate" description="Concatenate all js files">
<concat destfile=... | To copy without EOF use binary mode:
```
copy /B *.js compiled.js /Y
```
If the resulting file still has EOFs, that might have come from one of original files,
it can be fixed by this variant:
```
copy /A *.js compiled.js /B /Y
```
/A removes trailing EOFs from original files if any and /B prevents appending EOF to... | How do I concatenate JavaScript files into one file? | [
"",
"javascript",
"batch-file",
"compression",
""
] |
I'm building a project along with a Dll.
The Dll must support native code so I declared it as a /clr.
My project was initialy also a /clr project and everything was fine. However I'd like to include some NUnit testing so I had to switch my main project from /clr to /clr:pure.
Everything still compiles but any Dll cal... | Ok everything is working now
In fact, it has been working from the beginning.
Moral : don't try to cast a char\* into a std::string
Weird thing : its ok in /clr until you return from the function. It crashes right away in /clr:pure | Basically you are doing something that's not supported; /clr:pure and native DLL exports. As quoted from [this MSDN article](http://msdn.microsoft.com/en-us/library/85344whh.aspx) "pure assemblies cannot export functions that are callable from native functions because entry points in a pure assembly use the \_\_clrcall... | Using mixed DLLs from /clr:pure projects | [
"",
"c++",
"dll",
"visual-studio-2005",
"clr",
"mixed-mode",
""
] |
I have a JEdit (BeanShell) macro which opens a specific file then immediately saves the file to my c:\temp folder (so that I don't accidentally update the real file).
Here is the bean shell code:
```
logFilePath = "c:\\temp\\aj.txt";
jEdit.openFile( view , logFilePath );
_buffer = jEdit.getBuffer(logFilePath);
_buffe... | You can try [this solution](http://community.jedit.org/?q=node/view/4026), calling `VFSManager.waitForRequests();`. | ### This Works
This is the code pointed to by [Serhii's answer](https://stackoverflow.com/questions/295956/jedit-macro-open-and-save-file#296361), above.
Add `VFSManager.waitForRequests();` after the `jEdit.openFile()` command.
### Full Code
```
logFilePath = "c:\\temp\\aj.txt";
jEdit.openFile( view , logFilePa... | JEdit Macro - Open and Save File | [
"",
"java",
"macros",
"jedit",
"beanshell",
""
] |
I have a object of type `ICollection<string>`. What is the best way to convert to `string[]`.
How can this be done in .NET 2?
How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3? | You could use the following snippet to convert it to an ordinary array:
```
string[] array = new string[collection.Count];
collection.CopyTo(array, 0);
```
That should do the job :) | If you're using C# 3.0 and .Net framework 3.5, you should be able to do:
```
ICollection<string> col = new List<string>() { "a","b"};
string[] colArr = col.ToArray();
```
of course, you must have "using System.Linq;" at the top of the file | ICollection<string> to string[] | [
"",
"c#",
"generics",
"collections",
".net-2.0",
""
] |
After moving to .NET 2.0+ is there ever a reason to still use the systems.Collections namespace (besides maintaining legacy code)? Should the generics namespace always be used instead? | For the most part, the generic collections will perform faster than the non-generic counterpart and give you the benefit of having a strongly-typed collection. Comparing the collections available in System.Collections and System.Collections.Generic, you get the following "migration":
```
Non-Generic ... | In some circumstances the generic containers perform better than the old ones. They should at least perform as well as the old ones in all circumstances. And they help to catch programming errors. It's a rare combination of a more helpful abstraction and better performance, so there isn't much of a reason to avoid them... | Generics and System.Collections | [
"",
"c#",
".net",
"generics",
"collections",
""
] |
I have a class that inherits a generic dictionary and an inteface
```
public class MyDictionary: Dictionary<string, IFoo>, IMyDictionary
{
}
```
the issue is that consumers of this class are looking for the '.Keys' and ".Values" properties of the interface so i added:
```
/// <summary>
///
/// </summary... | Another option would be to change the types on the interface to be:
```
public interface IMyDictionary
{
/// <summary>
///
/// </summary>
Dictionary<string, IFoo>.KeyCollection Keys { get; }
/// <summary>
///
/// </summary>
Dictionary<string, IFoo>.ValueCollection Values { get; }
}
`... | Dictionary<string, IFoo> implements the IDictionary<TKey,TValue> interface which already provides the Keys and Values properties. There shouldn't be a need to create your own properties, but the way to get around the compiler warning is to add the `new` keyword at the beginning of your property declarations in your cla... | Class inherits generic dictionary<string, IFoo> and Interface | [
"",
"c#",
"generics",
"collections",
"interface",
""
] |
I would like to check my JavaScript files without going to [JSLint](http://www.jslint.com/) web site.
Is there a desktop version of this tool for Windows? | From <http://www.jslint.com/lint.html>:
> The analysis is done by a script
> running on your machine. Your script
> is not sent over the network.
>
> It is also available as a [Konfabulator
> widget](http://www.widgetgallery.com/?search=jslint). You can check a file by
> dragging it and dropping it on the
> widget. Yo... | You can also use JavaScript Lint on your machine,
get it from here
[JavaScript Lint](http://www.javascriptlint.com)
There are instructions on how to integrate it into many editors/IDE's on the above site.
I use it in UltraEdit and it works great.
From the above site
> > You can run JavaScript Lint several ways:
... | Is there an offline version of JSLint for Windows? | [
"",
"javascript",
"jslint",
""
] |
I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server us... | If you're even considering Pyro, check out [RPyC](http://rpyc.wikidot.com/) first, and re-consider XML-RPC.
Regarding Twisted: try leaving the reactor up instead of stopping it, and just `ClientCreator(...).connectTCP(...)` each time.
If you `self.transport.loseConnection()` in your Protocol you won't be leaving open... | For a synchronous client, Twisted probably isn't the right option. Instead, you might want to use the socket module directly.
```
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.send(output)
data = s.recv(size)
s.close()
```
The `recv()` call might need to be re... | How can I do synchronous rpc calls | [
"",
"python",
"twisted",
""
] |
I've seen some nice screenshot popups around the web, do you know of any library to do that? I could write my own, but... if there's something free I can save time.
Thanks! | Sounds like you want a lightbox.
jQuery lightbox gets my vote.
<http://leandrovieira.com/projects/jquery/lightbox/>
Dead simple - no point me writing examples, its all there on the site. | Here is a collection of some Javascript libraries from [Smashing Magazine - 30 Scripts For Galleries, Slideshows and Lightboxes](http://www.smashingmagazine.com/2007/05/18/30-best-solutions-for-image-galleries-slideshows-lightboxes/) (I excluded CSS-based, see website for full list):
* [JonDesign’s SmoothGallery](http... | What javascript library do you recommend to display/popup screenshots on a webpage? | [
"",
"javascript",
"screenshot",
""
] |
I need to round decimal numbers to six places using JavaScript, but I need to consider legacy browsers so I [can't rely on Number.toFixed](http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference)
> The big catch with toExponential, toFixed, and toPrecision is that they are fairly modern constructs not su... | Try this:
```
if (!Number.prototype.toFixed)
Number.prototype.toFixed = function(precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(this * power)/power);
}
``` | I think Firefox 1.5 and IE 5 are pretty much no longer used, or by a very minor quantity of people.
It is a bit like coding to support Netscape Navigator... :-)
Unless some other major browser (Opera? Safari? unlikely...) doesn't support this, or if your Web logs show lot of legacy browser use, you can probably jus... | How to write a prototype for Number.toFixed in JavaScript? | [
"",
"javascript",
"rounding",
"precision",
""
] |
Seems likes it might be useful to have the assert display a message when an assertion fails.
Currently an `AssertionError` gets thrown, can you specify a custom message for it?
Can you show an example mechanism for doing this (other than creating your own exception type and throwing it)? | You certainly can:
```
assert x > 0 : "x must be greater than zero, but x = " + x;
```
See [Programming with Assertions](https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html) for more information. | ```
assert (condition) : "some message";
```
I'd recommend putting the conditional in brackets
```
assert (y > x): "y is too small. y = " + y;
```
Imagine if you came across code like this...
```
assert isTrue() ? true : false : "some message";
```
Don't forget this has nothing to do with asserts you'd write in JU... | Can java's assert statement allow you to specify a message? | [
"",
"java",
"assert",
""
] |
which one of the two is more spread? I want to read out the version number from <http://freshmeat.net/projects-xml/mysql/mysql.xml?branch_id=46519> but I want to use the one which more people have.
If you know another way to get the latest stable version number from mysql please tell me ;) | For this kind of task, reading the document into a [`DomDocument`](https://www.php.net/domdocument) and using [`DomXPath`](http://docs.php.net/manual/it/domxpath.query.php) is probably more suitable.
To answer your question, both libraries (as well as `DomDocument` + `DomXPath`) are standard outfit with PHP5, so they ... | It has to be SimpleXML. It [is enabled by default](https://www.php.net/manual/en/simplexml.installation.php), is quicker to load XML documents than the Dom methods, has a smaller memory foot-print than the Dom methods, and has much simpler [xpath methods](https://www.php.net/manual/en/function.simplexml-element-xpath.p... | SimpleXML or XMLReader? | [
"",
"php",
"xml",
""
] |
I've rewritten my family web site using JavaScript (JQuery) making Ajax calls to PHP on the back end. It's your standard "bunch of image thumbnails and one main image, and when you click on a thumbnail image the main image changes" kind of thing. Everything is working as expected when using Firefox, but on IE, when I c... | Debugging through your site here's what it looks is happening:
After the first image is pocessed, the resize event is being thrown, so this code gets called:
```
$(window).bind("resize", function(){
ResizeWindow( 'nicholas-1' )
});
```
which as you know reloads your gallery. Now I can't tell you why this is occ... | You could use [Fiddler](http://www.fiddlertool.com/), a free debugging proxy for Internet Explorer. It was a great help for me many times when I had to debug specific,server-related problems on IE.
Here is an [Introduction to Fiddler on MSDN](http://i.msdn.microsoft.com/Bb250446.ie_introfiddler_fig04(en-us,VS.85).gif)... | How can I find the source of rogue Ajax requests on IE? | [
"",
"javascript",
"jquery",
"ajax",
"internet-explorer",
""
] |
what is the value of using IDictionary here? | The value of using an interface is always the same: you don't have to change client code when switching to another backend implementation.
Consider that profiling your code later shows that a hash table implementation (used in the `Dictionary` class) isn't suited for your task and that a binary search tree would perfo... | IDictionary enables looser coupling.
Say you have a method like this:
```
void DoSomething(IDictionary<string, string> d)
{
//...
}
```
You can use it like this:
```
Dictionary<string, string> a = new Dictionary<string, string>();
SortedDictionary<string, string> b = new SortedDictionary<string, string>();
DoSom... | IDictionary<string, string> versus Dictionary<string, string> | [
"",
"c#",
"generics",
"collections",
""
] |
I am currently in the process of rewriting an application whereby teachers can plan curriculum online.
The application guides teachers through a process of creating a unit of work for their students. The tool is currently used in three states but we have plans to get much bigger than that.
One of the major draw cards... | I don't know that you actually need 4 tables for this.
If you have a single table that tracks the parent\_id and a level you can have infinite levels.
> **outcome**
>
> id, parent\_id, level, name
You can use recursion to track through the tree for any particular element (you don't actually need level, but it can be... | I agree with the other poster - nested sets is the way to go I think.
See here:
<http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/>
It explains the theory and compares it to what you are already using - which is a twist on adjacency really. It shows +/- of them all, and should help you reach a dec... | Best way to represt n/ depth tree for use in PHP (MySQL / XML / ?) | [
"",
"php",
"mysql",
"xml",
"search",
"tree",
""
] |
With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function? | I see two options in this case:
## Garbage collector
```
import gc
for obj in gc.get_objects():
if isinstance(obj, some_class):
dome_something(obj)
```
This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control.
## Use a mixin and wea... | You'll want to create a static list on your class, and add a `weakref` to each instance so the garbage collector can clean up your instances when they're no longer needed.
```
import weakref
class A:
instances = []
def __init__(self, name=None):
self.__class__.instances.append(weakref.proxy(self))
... | Printing all instances of a class | [
"",
"python",
"class",
""
] |
Suppose I have a class 'Application'. In order to be initialised it takes certain settings in the constructor. Let's also assume that the number of settings is so many that it's compelling to place them in a class of their own.
Compare the following two implementations of this scenario.
Implementation 1:
```
class A... | I think it's fine. This is basically the builder pattern, and using nested classes works pretty well. It also lets the builder access private members of the outer class, which can be very useful. For instance, you can have a Build method on the builder which calls a private constructor on the outer class which takes an... | You can use namespaces to relate things that are... related.
For example:
```
namespace Diner
{
public class Sandwich
{
public Sandwich(Filling filling) { }
}
public class Filling { }
}
```
The advantage of this over using classes as if they were namespaces is that you can optionally use `us... | "Public" nested classes or not | [
"",
"c#",
"class-design",
"nested-class",
""
] |
I have often heard this term being used, but I have never really understood it.
What does it mean, and can anyone give some examples/point me to some links?
EDIT: Thanks to everyone for the replies. Can you also tell me how the canonical representation is useful in equals() performance, as stated in Effective Java? | Wikipedia points to the term [Canonicalization](http://en.wikipedia.org/wiki/Canonicalization).
> A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distin... | I believe there are two related uses of canonical: forms and instances.
A **canonical form** means that values of a particular type of resource can be described or represented in multiple ways, and one of those ways is chosen as the favored canonical form. (That form is *canonized*, like books that made it into the bi... | What does the term "canonical form" or "canonical representation" in Java mean? | [
"",
"java",
""
] |
I want a query that returns a list of all the (user) stored procedures in a database by name, with the number of lines of code for each one.
i.e.
```
sp_name lines_of_code
-------- -------------
DoStuff1 120
DoStuff2 50
DoStuff3 30
```
Any ideas how to do this? | ```
select t.sp_name, sum(t.lines_of_code) - 1 as lines_ofcode, t.type_desc
from
(
select o.name as sp_name,
(len(c.text) - len(replace(c.text, char(10), ''))) as lines_of_code,
case when o.xtype = 'P' then 'Stored Procedure'
when o.xtype in ('FN', 'IF', 'TF') then 'Function'
end as type_desc
f... | FWIW, here's another one:
```
SELECT o.type_desc AS ROUTINE_TYPE
,QUOTENAME(s.[name]) + '.' + QUOTENAME(o.[name]) AS [OBJECT_NAME]
,(LEN(m.definition) - LEN(REPLACE(m.definition, CHAR(10), ''))) AS LINES_OF_CODE
FROM sys.sql_modules AS m
INNER JOIN sys.objects AS o
ON m.[object_id] = o.[OBJEC... | Query to list SQL Server stored procedures along with lines of code for each procedure | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
"lines-of-code",
""
] |
I want a pure virtual parent class to call a child implementation of a function like so:
```
class parent
{
public:
void Read() { //read stuff }
virtual void Process() = 0;
parent()
{
Read();
Process();
}
}
class child : public parent
{
public:
virtual void Process() { //pr... | Title of the following article says it all: [Never Call Virtual Functions during Construction or Destruction](http://www.artima.com/cppsource/nevercall.html). | Alternatively, make a factory method for creating the objects and make the constructors private, the factory method can then Initialize the object after construction. | C++ Parent class calling a child virtual function | [
"",
"c++",
"inheritance",
"virtual",
""
] |
I have a sql database that stores some documents.
A user can sign into the application, and view a list of their documents.
When clicking a linkbutton download in a gridview of their docs, I get the file from the database, write it to the file system, and then execute this code.
```
System.IO.FileInfo file = new... | How are you sending the actual content of the file??
I usually use [Response.TransmitFile](http://msdn.microsoft.com/en-us/library/12s31dhy(VS.80).aspx) method, it basically opens the file and sends its content to the Response.OutputStream | Instead of
Response.AppendHeader("Content-Disposition",
"inline; " +
"filename=
use
Response.AddHeader("content-disposition:", "attachment;filename= | C# ASP.NET 3.5 content-disposition file download problems | [
"",
"c#",
"asp.net",
"content-disposition",
""
] |
Using strictly SQL (no PHP or anything else), is it possible to create a table **and insert default data into that table** only if that table doesn't exist? | Use the CREATE TABLE ... SELECT format:
```
create table if not exists tablename as
select * from defaultdata;
``` | Here is one way of doing it:
```
CREATE TABLE IF NOT EXISTS T (
ID int(10) unsigned NOT NULL primary key,
NAME varchar(255) NOT NULL
);
REPLACE INTO T SELECT 1, 'John Doe';
REPLACE INTO T SELECT 2, 'Jane Doe';
```
REPLACE is a MySQL extension to the SQL standard that either inserts, or deletes and inserts. | MySQL inserting data only if table doesn't exist | [
"",
"mysql",
"sql",
"database",
""
] |
I'm looking for ideas on how to implement audit trails for my objects in C#, for the current project,basically I need to:
1. Store the old values and new values of a given object.
2. Record creation of new objects.
3. Deletion of old object.
Is there any generic way of doing this,like using C# Generics,so that I don'... | Question is pretty similar to
[How do you implement audit trail for your objects (Programming)?](https://stackoverflow.com/questions/148291/how-do-you-implement-audit-trail-for-your-objects-programming)
We've implemented a similar solution, using AOP (aspectJ implementation). Using this particular points can be captur... | You could implement something similiar to INotifyPropertyChanged with a slight difference. I've extracted most of INotifyPropertyChanged and changed it to be generic and store new and old values. You can then have some sort of a management class that can listen to this and onSaving and onDeleting you can deal with the ... | Implementing Audit Trail for Objects in C#? | [
"",
"c#",
"object",
"audit-trail",
""
] |
I am looking for the best way to make my desktop java program run in the background (**daemon/service**?) across most platforms (Windows, Mac OS, Linux [Ubuntu in particular]).
By "best way" I am hoping to find a way that will:
1. require a **minimum** amount of platform-specific code.
2. not require the user to do a... | You can use the [SystemTray](http://java.sun.com/javase/6/docs/api/java/awt/SystemTray.html) classes and install your app as any other in the default platform.
For windows it could be an scheduled task that run at startup.
For Linux and OSX I don't know (besides crontab wich is somehow too technical) but I'm pretty su... | You can run a Java application as a service (Windows) or daemon (Linux) using the [Apache Commons daemon code](http://commons.apache.org/daemon/index.html).
## Structure
Daemon is made of 2 parts. One written in C that makes the interface to the operating system and the other in Java that provides the Daemon API.
##... | java background/daemon/service cross platform best practices | [
"",
"java",
"cross-platform",
"desktop-application",
"daemon",
""
] |
Given the [iPhone's 25k limit for caching of files](http://www.niallkennedy.com/blog/2008/02/iphone-cache-performance.html), I'm wondering if there's interest in an iPhone optimized javascript library that makes caching a top level goal. Since it'd be iPhone only it could get rid of most cross-browser cruft and rely on... | Newer update: looks like [Zepto](http://zeptojs.com/) is the way to go these days.
Found [XUI](http://github.com/brianleroux/xui/tree/master), looks like what I was looking for, although I haven't given it a try yet. | You should check out QuickConnectiPhone. It may do what you want. It can be found at <https://sourceforge.net/projects/quickconnect/>. It also lets you write your app in JavaScript, CSS, and HTML and yet install it on a device.
There is an API that will allow you to make calls down to the Objective-C layer as well for... | Minimalist cacheable jQuery/javascript library for iPhone? | [
"",
"javascript",
"jquery",
"iphone",
"dojo",
""
] |
Is it safe to use MS SQL's WITH (NOLOCK) option for select statements and insert statements if you never modify a row, but only insert or delete rows?
I..e you never do an UPDATE to any of the rows. | If you're asking whether or not you'll get data that may no longer be accurate, then it depends on your queries. For example, if you do something like:
```
SELECT
my_id,
my_date
FROM
My_Table
WHERE
my_date >= '2008-01-01'
```
at the same time that a row is being inserted with a date on or after 20... | Not in general. (i.e. UPDATE is not the only locking issue)
If you are inserting (or deleting) records and a select could potentially specify records which would be in that set, then yes, NOLOCK will give you a dirty read which may or may not include those records.
If the inserts or deletes would never potentially be... | Is it safe to use MS SQL's WITH (NOLOCK) option for select statements and insert statements if | [
"",
"sql",
"sql-server-2005",
""
] |
I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript.
for example, if i have this form:
```
<form id="someform">
<select name="option1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="option2">
<option value="1">1</... | If you're using Prototype, this is easy. First, you can use the [toQueryParams](http://prototypejs.org/api/string/toQueryParams) method on the String object to get a Javascript object with name/value pairs for each parameter.
Second, you can use the Form.Elements.setValue method (doesn't seem to be documented) to tran... | Try this:
```
Event.observe(window, 'load', function() {
var loc = window.location.search.substr(1).split('&');
loc.each(function(param) {
param = param.split('=');
key = param[0];
val = param[1];
$(key).value = val;
});
});
```
The above code assumes that you assign id values as well ... | Generic way to fill out a form in javascript | [
"",
"javascript",
"html",
"forms",
"prototypejs",
""
] |
I am making a C# app for a class project. I want to ensure a string has one of three values. Normally, in a web app, I would do validation with javascript on the client side. However, this is currently a console app. I know that I should do the validation early, but what are some good rules of thumb for validation? | Each module should do its own validation and never trust what the calling code gives it. This typically means that validation should happen at each layer of your application. You especially do not want to trust any validation to occurs on the client side, because that can lead to security holes. Code that runs on the c... | If you're doing MVC, chances are you're working from the ground up using TDD.
I'm not sure if this is the best way, but the way I do things is..
* Make my business objects.
* Define some kind of validation framework, so business objects can return a list of errors on it's current state and test those using unit testi... | Where is the best place in an app to do validation? Rules of thumb? | [
"",
"c#",
"validation",
"model-view-controller",
""
] |
How do i check in C++ if a file is a regular file (and is not a directory, a pipe, etc.)? I need a function isFile().
```
DIR *dp;
struct dirent *dirp;
while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
cout << "IS A FILE!" << endl;
i++;
}
```
I've tried comparing dirp->d\_type with (unsigned char)0x8,... | You need to call stat(2) on the file, and then use the S\_ISREG macro on st\_mode.
Something like (adapted from [this answer](https://stackoverflow.com/a/3828537/6451573)):
```
#include <sys/stat.h>
struct stat sb;
if (stat(pathname, &sb) == 0 && S_ISREG(sb.st_mode))
{
// file exists and it's a regular file
}
`... | You can use the portable [`boost::filesystem`](http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/index.htm) (The standard C++ library could not have done this up until recent introduction of [std::filesystem](http://en.cppreference.com/w/cpp/filesystem/is_regular_file) in C++17):
```
#include <boost/filesystem/... | How do i check if a file is a regular file? | [
"",
"c++",
"c",
"filesystems",
"dirent.h",
""
] |
Thanks for a [solution in C](https://stackoverflow.com/questions/327893/how-to-write-a-compare-function-for-qsort-from-stdlib),
now I would like to achieve this in C++ using std::sort and vector:
```
typedef struct
{
double x;
double y;
double alfa;
} pkt;
```
`vector< pkt > wektor;` filled up using push\_back(... | `std::sort` takes a different compare function from that used in `qsort`. Instead of returning –1, 0 or 1, this function is expected to return a `bool` value indicating whether the first element is less than the second.
You have two possibilites: implement `operator <` for your objects; in that case, the default `sort... | In C++, you can use functors like `boost::bind` which do this job nicely:
```
#include <vector>
#include <algorithm>
struct pkt {
double x;
double y;
double alfa;
pkt(double x, double y, double alfa)
:x(x), y(y), alfa(alfa) { }
};
int main() {
std::vector<pkt> p;
p.push_back(pkt(10., ... | How to use std::sort with a vector of structures and compare function? | [
"",
"c++",
"sorting",
"stl",
"vector",
""
] |
Given a word, I've to replace some specific alphabets with some specific letters such as 1 for a, 5 for b etc. I'm using regex for this. I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations. Here is what I'm doing:
```
String word = "foobooandfoo";
String... | I think this is a case where clarity and performance happily coincide. I would use a lookup table to do the "translation".
```
public static void translate(StringBuilder str, char[] table)
{
for (int idx = 0; idx < str.length(); ++idx) {
char ch = str.charAt(idx);
if (ch < table.length) {
c... | I'd actually say that the code is pretty OK in most applications although it's theoretically inferior to other methods. If you don't want to use the `Matcher`, try it like this:
```
StringBuilder result = new StringBuilder(word.length());
for (char c : word.toCharArray()) {
switch (c) {
case 'a': case 'o'... | How to rewrite this block of code using a StringBuilder in Java? | [
"",
"java",
"string",
"stringbuilder",
""
] |
I have a collection of HTML documents for which I need to parse the contents of the <meta> tags in the <head> section. These are the only HTML tags whose values I'm interested in, i.e. I don't need to parse anything in the <body> section.
I've attempted to parse these values using the XPath support provided by JDom. H... | You can likely use the [Jericho HTML Parser](http://jerichohtml.sourceforge.net/doc/index.html). In particular, have a look at [this](http://jerichohtml.sourceforge.net/samples/console/src/FindSpecificTags.java) to see how you can go about finding specific tags. | If it suits your application you can use [Tidy](http://tidy.sourceforge.net/) to convert HTML to valid XML, and then use as much XPath as you like! | parse meta tags in Java | [
"",
"java",
"html",
"xml",
"parsing",
""
] |
Is there a built in Javascript function to turn the text string of a month into the numerical equivalent?
Ex.
I have the name of the month "December" and I want a function to return "12". | You can append some dummy day and year to the month name and then use the [Date](http://www.cev.washington.edu/lc/CLWEBCLB/jst/js_datetime.html) constructor:
```
var month = (new Date("December 1, 1970").getMonth() + 1);
``` | Out of the box, this is not something supported in native JS. As mentioned, there are locale considerations, and different date conventions which you need to cater to.
Do you have any easing assumptions you can use? | Is there a built in Javascript function to turn the text string of a month into the numerical equivalent? | [
"",
"javascript",
""
] |
I'm trying to load javascript code with a user web control into a page via a the Page.LoadControl method during an asyncron post back of an update panel.
I've tried the specially for that scenario designed methods of the scriptmanager, but the javascript just doens't get returned to the user.
To explain my scenario a... | For that you can do
```
string scr;
scr = "<script src='/scripts/myscript.js'></script>"
Page.ClientScript.RegisterStartupScript(GetType(Page), "key", scr, false)
```
HTH | **If you don't want to hard-code your JavaScript**, but instead include it from a file, call [ScriptManager.RegisterClientScriptInclude](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerclientscriptinclude.aspx) and then call your initialization function in [ScriptManager.RegisterStartupScrip... | ASP.NET inject javascript in user control nested in update panel | [
"",
"asp.net",
"javascript",
"updatepanel",
"custom-server-controls",
""
] |
I'm currently building a Gridview that has expandable rows. Each row contains a dynamically created Panel of Form elements. Right now, I have a javascript function that expands (or in my case, makes visible) the panel when an Image is clicked on the Gridview row.
My question is... is there a more efficient way of doin... | Actually worked this recently into an AJAX Handler returning the form structure. It's on demand, and works well. Simply call $ajax via jQuery, return an HTML structure, inject into DIV. It's a bit limiting on actual functionality, so be careful. | Actually, it isn't performing badly since my original SQL query can populate every single row and I have enabled paging on the Gridview. I'm just wondering if they can be built on the fly using PageMethods or some sort of JSON/AJAX solution. I haven't seen anything, but... worth a try in searching for it. | ASP.net 2.0 Gridview with Expanding Panel Rows -- How to build Panel "on the fly" | [
"",
"asp.net",
"javascript",
"gridview",
"panel",
"expandable",
""
] |
I'm new to C# and .Net in general so this may be a naive thing to ask. But anyway, consider this C# code:
```
class A {
public int Data {get; set;}
}
class B {
public A Aval {get; set;}
}
```
The B.Aval property above is returning a reference to its internal A object. As a former C++ programmer, I find this ... | You're absolutely right - you should only return objects from properties where either the object is immutable, or you're happy for the caller to modify it to whatever extent they can. A classic example of this is returning collections - often it's much better to return a read-only wrapper round a collection than to ret... | This isn't encapsulation - it's an act of abstraction through object composition or aggregation depending on how the internal object lifetimes are created/managed.
In composition patterns it is perfectly acceptable to access composite state e.g. the instance of A in the instance of B.
> <http://en.wikipedia.org/wiki/... | C# and Data Hiding | [
"",
"c#",
".net",
""
] |
I am trying to test a class that manages data access in the database (you know, CRUD, essentially). The DB library we're using happens to have an API wherein you first get the table object by a static call:
```
function getFoo($id) {
$MyTableRepresentation = DB_DataObject::factory("mytable");
$MyTableRepresentatio... | I agree with both of you that it would be better not to use a static call. However, I guess I forgot to mention that DB\_DataObject is a third party library, and the static call is *their* best practice for their code usage, not ours. There are other ways to use their objects that involve constructing the returned obje... | When you cannot alter the library, alter your access of it. Refactor all calls to DB\_DataObject::factory() to an instance method in your code:
```
function getFoo($id) {
$MyTableRepresentation = $this->getTable("mytable");
$MyTableRepresentation->get($id);
... do some stuff
return $somedata
}
function getTab... | Mock Objects in PHPUnit to emulate Static Method Calls? | [
"",
"php",
"static",
"mocking",
"phpunit",
""
] |
On a Unix system, where does gcc look for header files?
I spent a little time this morning looking for some system header files, so I thought this would be good information to have here. | ```
`gcc -print-prog-name=cc1plus` -v
```
This command asks gcc which **C++** preprocessor it is using, and then asks that preprocessor where it looks for includes.
You will get a reliable answer for your specific setup.
Likewise, for the **C** preprocessor:
```
`gcc -print-prog-name=cpp` -v
``` | In addition, gcc will look in the directories specified after the `-I` option. | Where does gcc look for C and C++ header files? | [
"",
"c++",
"c",
"gcc",
"header",
""
] |
The title basically spells it out. What interfaces have you written that makes you proud and you use a lot. I guess the guys that wrote `IEnumerable<T>` and not least `IQueryable<T>` had a good feeling after creating those. | I'm pleased with the design of the interface at the heart of [Push LINQ](http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx). It's a very simple interface, but with it you can do all kinds of interesting things. Here's the definition (from memory, but ... | Strictly an interface? Or just an API? I'm kinda pleased with how the [generic operator](http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html) stuff worked out (available [here](http://www.yoda.arachsys.com/csharp/miscutil/)) - I *regularly* see people asking about using operators with generics, so I... | Whats the best (most useful) interface you have written? | [
"",
"c#",
"interface",
""
] |
I would like to write a program that will identify a machine( for licensing purposes), I tought about getting the following information and to compile an xml file with this data:
1. MAC address.
2. CPU data (serial, manufacture, etc)
3. MotherBoard Identification. (serial, manufacture, etc)
can someone refer me to a ... | Using [WMI](http://msdn.microsoft.com/en-us/library/aa394582.aspx) and getting the motherboard's serial number should be enough (the other options are less secure, since an old computer may not have a network adapter and/or the CPU can be changed more likely than the motherboard). | GetAdaptersInfo() will give you the MAC address. Here's an example of how to use it for this purpose.
```
/** *************************************
return string containing first MAC address on computer
NOTE: requires adding Iphlpapi.lib to project
*/
string GetMac()
{
char data[4096];
ZeroMemory( data... | Get machine properties | [
"",
"c++",
"winapi",
""
] |
I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.
How can I do it?
---
When I click the submit button for the textbox below, the message box must show *Lorem ipsum*. Because "Lorem ipsum" is se... | OK, here is the code I have:
```
function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{ // Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
... | Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:
```
document.querySelector('textarea').addEventListener('mouseup', function () {
window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
// window.getSelection(... | How to get selected text from a textbox control with JavaScript | [
"",
"javascript",
"html",
"textarea",
"textselection",
"selectedtext",
""
] |
Why do you think Microsoft wants us to go through IEnumerable to get to IEnumerator? Isn't the presence or absence of a valid cast to IEnumerator for a given type enough to determine if the type is enumerable or not?
For example whats wrong with the following?
```
class MyClass : IEnumerator
{
...
}
MyClass myOb... | You might have two threads enumerating - each needs its own enumerator.
IEnumerable.GetEnumerator returns an enumerator that is initially positioned before the first element of the collection. If you only had IEnumerator, you'd have to remember to reset yourself before using it, even in a single-threaded scenario. | An IEnumerator holds state information necessary to perform enumeration, such as array index etc.
The enumeration state information is NOT part of the enumerable object, therefore casting would not be powerful enough.
Also, the enumerator/enumerable separation allows several enumerations to be performed simultaneousl... | What's the rationale behind IEnumerable? | [
"",
"c#",
".net",
""
] |
This is a second-hand question from an OS development site, but it made me curious since I couldn't find a decent explanation anywhere.
When compiling and linking a free-standing C++ program using gcc, sometimes a linker error like this occurs:
```
out/kernel.o:(.eh_frame+0x11): undefined reference to `__gxx_personal... | It is used in the stack unwiding tables, which you can see for instance in the assembly output of [my answer to another question](https://stackoverflow.com/questions/307610/how-do-exceptions-work-behind-the-scenes-in-c#307716). As mentioned on that answer, its use is defined by the [Itanium C++ ABI](https://itanium-cxx... | It's part of the exception handling. The gcc EH mechanism allows to mix various EH models, and a personality routine is invoked to determine if an exception match, what finalization to invoke, etc. This specific personality routine is for C++ exception handling (as opposed to, say, gcj/Java exception handling). | What is __gxx_personality_v0 for? | [
"",
"c++",
"gcc",
"linker",
"kernel",
""
] |
What are the tensions between multithreading and exception-safety in C++? Are there good guidelines to follow? Does a thread terminate because of an uncaught exception? | I believe the C++ standard does not make any mention of multithreading - multithreading is a platform-specific feature.
I'm not exactly sure what the C++ standard says about uncaught exceptions in general, but according to [this page](http://www.devx.com/tips/Tip/14240), what happens is platform-defined, and you shoul... | C++0x will have [Language Support for Transporting Exceptions between Threads](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2179.html) so that when a worker thread throws an exception the spawning thread can catch or rethrow it.
From the proposal:
```
namespace std {
typedef unspecified exception_ptr... | Writing Multithreaded Exception-Safe Code | [
"",
"c++",
"multithreading",
"exception",
"c++11",
""
] |
Am looking for checkpointing library for C#. Any ideas ?
see <http://en.wikipedia.org/wiki/Application_checkpointing> | This should be possible to implement using transactions (commit/rollback) or undo. If you design your classes and operations correctly it will work, it will require some hard work and discipline using the classes of course. You'll also need to be careful about exceptions.
The [System.Transactions namespace](http://msd... | If I understand you correctly (and the question is pretty vague so I'm not sure of this at all) then Windows Workflow Foundation certainly has this capability. However, it's almost certainly overkill for what you're asking.
---
Okay, you added a link that better explains what you mean by checkpointing.
With that in ... | checkpointing library for C# | [
"",
"c#",
""
] |
When you assign a date to a named SQL parameter Hibernate automatically converts it to GMT time. How do you make it use the current server timezone for all dates?
Lets say you have a query:
```
Query q = session.createQuery("from Table where date_field < :now");
q.setDate("now", new java.util.Date());
```
"now" will... | As it turned out Hibernate doesn't convert dates to GMT automatically, it just cuts off time if you use `query.setDate()`, so if you pass "2009-01-16 12:13:14" it becomes "2009-01-16 00:00:00".
To take time into consideration you need to use `query.setTimestamp("date", dateObj)` instead. | Hibernate is ignorant of timezones. Any timezone conversion should be done prior to executing the query.
E.g., if your database server is set to CST, but the user is on EST, you'll need to add 1 hour to any timestamps which are the input to a query. | How to assign Date parameters to Hibernate query for current timezone? | [
"",
"java",
"hibernate",
"timezone",
""
] |
I had the following piece of code (simplified for this question):
```
struct StyleInfo
{
int width;
int height;
};
typedef int (StyleInfo::*StyleInfoMember);
void AddStyleInfoMembers(std::vector<StyleInfoMember>& members)
{
members.push_back(&StyleInfo::width);
members.push_back(&StyleInfo::height);
... | Remember a pointer to a member is just used like a member.
```
Obj x;
int y = (x.*)ptrMem;
```
But like normal members you can not access members of subclasses using the member access mechanism. So what you need to do is access it like you would access a member of the object (in your case via the size member).
`... | Is it definitely possible? I honestly don't know, never having played much with pointer-to-member.
Suppose you were using non-POD types (I know you aren't, but the syntax would have to support it). Then pointer-to-member might have to encapsulate more than just an offset from the base pointer. There might be indirecti... | Pointer-to-data-member-of-data-member | [
"",
"c++",
""
] |
I am doing some simple sanity validation on various types. The current test I'm working on is checking to make sure their properties are populated. In this case, populated is defined as not null, having a length greater than zero (if a string), or not equal to 0 (if an integer).
The "tricky" part of this test is that ... | Make a HashSet "exactNames" with PropertyOne, PropertyTwo etc, and then a List "partialNames" with ValueOne, ValueTwo etc. Then:
```
var matchingProperties = pi.Where(exactNames.Contains(pi.Name) ||
partialNames.Any(name => pi.Name.Contains(name));
foreach (PropertyInfo property in matchingP... | Your idea help speed up my program, thank you. However, you had some syntax issues, plus you were matching items found in the lists and I needed items not in the list. Here is the code I ended up using.
```
List<System.Reflection.PropertyInfo> pi = type.GetProperties().ToList();
var matchingProperties = pi.Where( pro... | Filtering an Objects Properties by Name | [
"",
"c#",
"string",
"properties",
""
] |
I'm working on a project where a program running on the mobile phone needs to communicate with a program running on the PC it's connected to. Ideally, I'd like to use USB, WiFi, whatever to communicate.
The two programs should be able to communicate things like battery life, text messages, etc... But I can work on tha... | "Best" is really subjective and highly dependent on a lot of factors like devices, topology, firewall presence, need for security, etc, etc.
Where do you need the comms to originate and will you have an ActiveSync connection? If the PC initiates the comms and you have ActiveSync, then RAPI is the transport you'd use a... | Assuming you have a wifi connection, one way for your Windows Mobile program to communicate with your PC would be to use WCF on the .NET compact framework 3.5.
You'd create a new WCF application to run you your PC, and expose an interface exposing functions you want to call from your Windows Mobile Device.
WCF on Win... | Windows Mobile (C#) - Communicating between phone and PC | [
"",
"c#",
"windows-mobile",
""
] |
I need to activate a JButton ActionListener within a JDialog so I can do some unit testing using JUnit.
Basically I have this:
```
public class MyDialog extends JDialog {
public static int APPLY_OPTION= 1;
protected int buttonpressed;
protected JButton okButton;
public MyDialog(Frame f) {
... | `AbstractButton.doClick`
Your tests might run faster if you use the form that takes an argument and give it a shorter delay. The call blocks for the delay. | If you have non-trivial code directly in your event handler that needs unit testing, you might want to consider adopting the [MVC pattern](http://en.wikipedia.org/wiki/Model-view-controller) and moving the code to the controller. Then you can unit test the code using a mock View, and you never need to programmatically ... | How do I activate JButton ActionListener inside code (unit testing purposes)? | [
"",
"java",
"unit-testing",
"swing",
"junit",
""
] |
I have a base class that has a private static member:
```
class Base
{
private static Base m_instance = new Base();
public static Base Instance
{
get { return m_instance; }
}
}
```
And I want to derive multiple classes from this:
```
class DerivedA : Base {}
class DerivedB : Base {}
class Der... | There's one really icky way of doing this:
```
class Base
{
// Put common stuff in here...
}
class Base<T> : Base where T : Base<T>, new()
{
private static T m_instance = new T();
public static T Instance { get { return m_instance; } }
}
class DerivedA : Base<DerivedA> {}
class DerivedB : Base<DerivedB... | Static methods does not support polymorphism, therefore, such a thing is not possible.
Fundamentally, the Instance property has no idea how you're using it. And a single implementation of it will exist, as it's static. If you really wanted to do this, this "not recommended" solution is available (I got the idea from J... | Deriving static members | [
"",
"c#",
"design-patterns",
"oop",
""
] |
I've got about 200k images in a bucket. They all have expires headers of 2050 but I've read you shouldn't send an expires header older than a year. I want to schedule a script to run every month and set the headers to 6 months away. Anything out there? Obviously I'd like to avoid iterating 200k objects. | *Disclaimer:* I am the developer of this tool, but I think it may answer your question.
[CloudBerry Explore](http://cloudberrylab.com)r freeware will be able to do it in the next release. | S3 doesn't appear to support bulk updates, as its API's contain no such operations. Some third-party tools claim bulk update capability; however, I wager that they merely automate iteration. | Can I set the expires header on all objects in an Amazon S3 bucket all at once? | [
"",
"c#",
".net",
"amazon-s3",
"amazon-web-services",
"cloud",
""
] |
```
void addNewNode (struct node *head, int n)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp -> data = n;
temp -> link = head;
head = temp;
}
```
The code give above is the popularly wrong version of a function for adding a new node at the head of a linked list.
Generally the c... | The flaw is that you're relying on the caller to perform the last step of updating the head pointer to the list.
If the caller neglects to do this, the compiler will not complain, and for all intents and purposes the list will appear to not have changed (and you'll have leaked the memory for a node). | This is how linked lists work in most functional languages. For example, in ML you might do something like this:
```
val ls = [1, 2, 3, 4]
val newList = 0 :: ls
```
The `::` syntax is actually a function which takes two parameters (`0` and `ls`) and returns a new list which has `0` as the first element. Lists in ML a... | New approach for adding a new Node to a Linked List | [
"",
"c++",
"c",
"data-structures",
"pointers",
""
] |
jQuery selectors are wonderful, but I sometimes I find myself typing them over and over, and it gets a little annoying.
```
$('#mybutton').click(function() {
$('#message-box').doSomething();
$('#message-box').doSomethingElse();
$('#message-box').attr('something', 'something');
});
```
So often I like to... | You should chain them:
```
$('#mybutton').click(function() {
$('#message-box').doSomething().doSomethingElse().attr('something', 'something');
});
```
If you need to do something over and over again and the functions don't return the jQuery object saving them in a var is faster. | I usually chain them as per Pims answer, however sometimes when theres a lot of operations to be done at once, chaining can cause readability issues. In those cases I cache the selected jQuery objects in a variable. | Always use jquery selectors or cache them in variables? | [
"",
"javascript",
"jquery",
"performance",
""
] |
i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.
this is the code:
``... | As it's a MemoryStream, you really don't *need* to close the stream - nothing bad will happen if you don't, although obviously it's good practice to dispose anything that's disposable anyway. (See [this question](https://stackoverflow.com/questions/234059) for more on this.)
However, you *should* be disposing the Bitm... | **A generic error occurred in GDI+.**
May also result from **incorrect save path**!
Took me half a day to notice that.
So make sure that you have double checked the path to save the image as well. | Image.Save(..) throws a GDI+ exception because the memory stream is closed | [
"",
"c#",
"image",
"exception",
"gdi+",
""
] |
I get the following error while building OpenCV on OS X 10.5 (intel):
```
ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture
ld: warning in .libs/... | Ok, I kind of worked it out
It needs to be compiled with python from macports or whatever. Then I need to run `/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5` (this is my previous python version) and there OpenCV just works. | It seems a little weird that it is warning about different architectures when looking for /Developer/SDKs/MacOSX10.4u.sdk while linking - can you give us some more detail about your build environment (version of XCode, GCC, Python, $PATH etc)
Alternatively, won't any of the OpenCV binaries available work for you? | OpenCV's Python - OS X | [
"",
"python",
"macos",
"opencv",
""
] |
I want to convert from char representing a hexadecimal value (in upper or lower case) to byte, like
```
'0'->0, '1' -> 1, 'A' -> 10, 'a' -> 10, 'f' -> 15 etc...
```
I will be calling this method extremely often, so performance is important. Is there a faster way than to use a pre-initialized `HashMap<Character,Byte>`... | A preinitialised array would be faster than a HashMap. Something like this:
```
int CharValues['f'-'0'+1] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, ... -1, 10, 11, 12, ...};
if (c < '0' || c > 'f') {
throw new IllegalArgumentException();
}
int n = CharValues[c-'0'];
if (n < 0) {
throw new IllegalArgumentExcept... | A hash table would be relatively slow. This is pretty quick:
```
if (c >= '0' && c <= '9')
{
return c - '0';
}
if (c >= 'a' && c <= 'f')
{
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F')
{
return c - 'A' + 10;
}
throw new IllegalArgumentException();
```
Another option would be to try a switch/case statem... | Performance question: Fastest way to convert hexadecimal char to its number value in Java? | [
"",
"java",
"performance",
"algorithm",
""
] |
I'm implementing an audit log on a database, so everything has a CreatedAt and a RemovedAt column. Now I want to be able to list all revisions of an object graph but the best way I can think of for this is to use unions. I need to get every unique CreatedAt and RemovedAt id.
If I'm getting a list of countries with pro... | You have most likely already implemented your solution, but to address a few issues; I would suggest considering Aleris's solution, or some derivative thereof.
- In your tables, you have a "removed at" field -- well, if that field were active (populated), technically the data shouldn't be there -- or perhaps your impl... | An alternative would be to create an audit log that might look like this:
```
AuditLog table
EntityName varchar(2000),
Action varchar(255),
EntityId int,
OccuranceDate datetime
```
where EntityName is the name of the table (eg: Contries, Provinces), the Action is the audit action (eg: Created, Removed... | Query to get all revisions of an object graph | [
"",
"sql",
"sql-server",
"orm",
"union",
""
] |
Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening . I can't find in the documentation how this is done - can someone point me in the right direction?
We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will ta... | Use [SetCursor](http://msdn.microsoft.com/en-us/library/ms940016.aspx)/[LoadCursor](http://msdn.microsoft.com/en-us/library/aa453410.aspx)/[ShowCursor](http://msdn.microsoft.com/en-us/library/aa453730.aspx) APIs, like this:
```
SetCursor(LoadCursor(NULL, IDC_WAIT));
// my code
ShowCursor(FALSE);
``` | Using compactframework.
Spining wheel:
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
Return to normal:
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; | How do I get a "busy wheel" on Windows Mobile 6? | [
"",
"c++",
"windows-mobile",
"progress-bar",
""
] |
Since I'm sure many people have different standard, I've made this post a community wiki.
My question is, what's a good naming scheme for table aliases? I've been using the first letter of every word from the table name, but it's been getting quite unreadable. Here's a quick example.
```
FROM incidents i
FROM cause_a... | The whole point of an alias is to shorten the name so you don't need verbosity.
It only needs to be unique within a given query, so there's no need for a scheme for naming them.
Edit: Also, the aliases you'd use depend highly on the table naming scheme. If all your tables have a 5-part name where the first 4 are comm... | The tables names themselves should already be readable. Therefore, if you want a readable name just don't alias.
This means the purpose of an alias is as much to save your poor fingers from re-typing long names as anything else. In that case, short terse names work well, especially as they must be declared right next ... | Readable SQL aliases | [
"",
"sql",
"oracle",
"alias",
""
] |
I was wondering how to unit test abstract classes, and classes that extend abstract classes.
Should I test the abstract class by extending it, stubbing out the abstract methods, and then test all the concrete methods? Then only test the methods I override, and test the abstract methods in the unit tests for objects th... | There are two ways in which abstract base classes are used.
1. You are specializing your abstract object, but all clients will use the derived class through its base interface.
2. You are using an abstract base class to factor out duplication within objects in your design, and clients use the concrete implementations ... | Write a Mock object and use them just for testing. They usually are very very very minimal (inherit from the abstract class) and not more.Then, in your Unit Test you can call the abstract method you want to test.
You should test abstract class that contain some logic like all other classes you have. | How to unit test abstract classes: extend with stubs? | [
"",
"java",
"unit-testing",
"testing",
"abstract-class",
""
] |
I need to extract some bitmaps from an .msstyles file (the Windows XP visual style files) and I'm not sure where to start. I can't seem to find any documentation on how to do it, and the file format seems to be binary and not easily parsed. I have been able to extract the bitmap by itself using:
```
IntPtr p = LoadLib... | [This](http://filext.com/file-extension/MSSTYLES "File Extensions") site claims the file format is documented though not by Microsoft.
Also found this in the [Wine Crossreference](http://source.winehq.org/source/dlls/uxtheme/msstyles.c "msstyles.c").
Hope that helps! | If you want to get files out of a dll directly (remember, msstyles are dlls with another extension), you could have a look at the [Anolis Project](http://www.codeplex.com/anolis "Anolis Project").
As for actually parsing that stuff you should look at the various tutorials on creating msstyles for information on how th... | How to parse an .msstyles file? | [
"",
"c#",
"uxtheme",
"msstyles",
""
] |
By means of a regular expression and Greasemonkey I have an array of results that looks like:
`choice1, choice2, choice3, choice3, choice1, etc..`
My question is how do I tally up the choices so I know how many times choice1 is in the array, choice2 is in the array, etc. if I do not know exactly how many choices the... | One technique would be to iterate over the choices and increment a counter associated to each unique choice in an object property.
Example:
```
var choiceCounts = {};
for (var iLoop=0; iLoop < aChoices.length; iLoop++) {
var keyChoice = aChoices[iLoop];
if (!choiceCounts[keyChoice]) {
choiceCounts[keyChoice] ... | Not 100% sure what your looking for, but I think this is it.
```
// Original data
var choices = [
"choice 1",
"choice 1",
"choice 2",
"choice 3",
"choice 3",
"choice 3",
"choice 3",
"choice 3",
"choice 3",
"choice 4",
"choice... | Counting Results in an Array | [
"",
"javascript",
"arrays",
"greasemonkey",
""
] |
Is there a tool which tells you (or gives you a hint) why a particular select statement dose not return any rows given the current data in your database.
eg if you had the following 4 table join
```
select *
from a, b, c, d
where a.b_id = b.id
and b.c_id = c.id
and c.d_id = d.id
```
If there were rows which satisfi... | This will get you started...
select count(1) from a, b where a.b\_id = b.id
select count(1) from b, c where b.c\_id = c.id
select count(1) from c, d where c.d\_id = d.id
Note that you are using AND so the overlap of the above queries may not be what you expect.
OR
Using MS-SQL Server Management Studio...
Display ... | I never have this problem, but I also use explicit joins so it's usually as simple as running parts of the query until I find out which one is restricting my results incorrectly.
In your case
```
SELECT *
FROM a -- First run just to here, are there records?
INNER JOIN b
ON a.b_id = b.id -- Then run just to here, ... | Tool to find out why an SQL select does not return any data | [
"",
"sql",
"postgresql",
""
] |
In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class:
<http://docs.python.org/library/httplib.html#httplib.HTTPConnection>
However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the **request**, not the connection. This doesn't seem to ... | You can set a global socket timeout (\*):
```
import socket
timeout = 10
socket.setdefaulttimeout(timeout)
```
---
(\*) **EDIT**: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of... | No, there isn't.
It's because the [HTTP spec](http://www.greenbytes.de/tech/webdav/rfc2616.html) does not provide anything for the client to specify time-to-live information with a HTTP request. You can do this only on TCP level, as you mentioned.
On the other hand, the server may inform the client about timeout situ... | HTTP Request Timeout | [
"",
"python",
"http",
""
] |
I have a string with a length that is a multiple of 8 that contains only 0's and 1's. I want to convert the string into a byte array suitable for writing to a file. For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the bina... | ```
py> data = "0010011010011101"
py> data = [data[8*i:8*(i+1)] for i in range(len(data)/8)]
py> data
['00100110', '10011101']
py> data = [int(i, 2) for i in data]
py> data
[38, 157]
py> data = ''.join(chr(i) for i in data)
py> data
'&\x9d'
``` | You could do something like this:
```
>>> s = "0010011010011101"
>>> [int(s[x:x+8], 2) for x in range(0, len(s), 8)]
[38, 157]
``` | Converting a string of 1's and 0's to a byte array | [
"",
"python",
""
] |
Suppose you create a generic Object variable and assign it to a specific instance. If you do GetType(), will it get type Object or the type of the original class? | Yes.
You can also do:
```
object c = new FooBar();
if(c is FooBar)
Console.WriteLine("FOOBAR!!!");
``` | **Short answer: GetType() will return the Type of the specific object.** I made a quick app to test this:
```
Foo f = new Foo();
Type t = f.GetType();
Object o = (object)f;
Type t2 = o.GetType();
bool areSame = t.Equals(t2);
```
And yep, they are the same. | Do C# objects know the type of the more specific class? | [
"",
"c#",
"object",
"types",
""
] |
I'm writing a global error handling "module" for one of my applications.
One of the features I want to have is to be able to easily wrap a function with a `try{} catch{}` block, so that all calls to that function will automatically have the error handling code that'll call my global logging method. (To avoid polluting... | Personally instead of polluting builtin objects I would go with a decorator technique:
```
var makeSafe = function(fn){
return function(){
try{
return fn.apply(this, arguments);
}catch(ex){
ErrorHandler.Exception(ex);
}
};
};
```
You can use it like that:
```
function fnOriginal(a){
con... | **2017 answer**: just use ES6. Given the following demo function:
```
function doThing(){
console.log(...arguments)
}
```
You can make your own wrapper function without needing external libraries:
```
function wrap(someFunction){
function wrappedFunction(){
var newArguments = [...arguments]
newArguments.... | How do I wrap a function in Javascript? | [
"",
"javascript",
"function",
"try-catch",
"apply",
"wrapper",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.