Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I have a .Net 2.0 app that is used internally and we want to use the WebBrowser control to access some Web resources. We want to add encryption to these sites using SSL using self signed certificates.
My question is if there is way to disable all the warnings about the SSL keys coming from an untrusted source? I would like to avoid to have to install the keys in each of the workstations running the app.
Any other suggestions on how to do this are welcome.
|
I do not believe there is a work around for this, you will always get the warning when accessing the above mentioned web resources via the WebBrowser control (or Internet Explorer for that matter) You could however distribute the **root** cert via Group Policy.
|
You can do this by hooking dialogs (as someone above send the link) but then implementing SSL will be pointless. Because when an attack does the MITM attack you'll ignore the warnings and continue anyway. Better potion your installer might install the certificate in the first place.
|
Access Intranet via SSL using WebBrowser Winforms Control
|
[
"",
"c#",
".net",
"user-interface",
"browser",
""
] |
I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s).
```
using std::string;
using std::vector;
class Foo { /*...*/ };
```
What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations into every cpp file that includes the header?
|
When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a `using` declaration has the exact same effect of placing the `using` declaration at the top of each file that includes that header file.
|
There's nothing special about header files that would keep the `using` declaration out. It's a simple text substitution before the compilation even starts.
You can limit a `using` declaration to a scope:
```
void myFunction()
{
using namespace std; // only applies to the function's scope
vector<int> myVector;
}
```
|
What's the scope of the "using" declaration in C++?
|
[
"",
"c++",
""
] |
Some of my data are 64-bit integers. I would like to send these to a JavaScript program running on a page.
However, as far as I can tell, integers in most JavaScript implementations are 32-bit signed quantities.
My two options seem to be:
1. Send the values as strings
2. Send the values as 64-bit floating point numbers
Option (1) isn't perfect, but option (2) seems far less perfect (loss of data).
How have you handled this situation?
|
This seems to be less a problem with JSON and more a problem with Javascript itself. What are you planning to do with these numbers? If it's just a magic token that you need to pass back to the website later on, by all means simply use a string containing the value. If you actually have to do arithmetic on the value, you could possibly write your own Javascript routines for 64-bit arithmetic.
One way that you could represent values in Javascript (and hence JSON) would be by splitting the numbers into two 32-bit values, eg.
```
[ 12345678, 12345678 ]
```
To split a 64-bit value into two 32-bit values, do something like this:
```
output_values[0] = (input_value >> 32) & 0xffffffff;
output_values[1] = input_value & 0xffffffff;
```
Then to recombine two 32-bit values to a 64-bit value:
```
input_value = ((int64_t) output_values[0]) << 32) | output_values[1];
```
|
There is in fact a limitation at JavaScript/ECMAScript level of precision to 53-bit for integers (they are stored in the mantissa of a "double-like" 8 bytes memory buffer). So transmitting big numbers as JSON won't be unserialized as expected by the JavaScript client, which would truncate them to its 53-bit resolution.
```
> parseInt("10765432100123456789")
10765432100123458000
```
See the [`Number.MAX_SAFE_INTEGER` constant](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) and `Number.isSafeInteger()` function:
> The `MAX_SAFE_INTEGER` constant has a value of `9007199254740991`. The
> reasoning behind that number is that JavaScript uses double-precision
> floating-point format numbers as specified in IEEE 754 and can only
> safely represent numbers between `-(2^53 - 1)` and `2^53 - 1`.
>
> Safe in this context refers to the ability to represent integers
> exactly and to correctly compare them. For example,
> `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will
> evaluate to `true`, which is mathematically incorrect. See
> `Number.isSafeInteger()` for more information.
Due to the resolution of floats in JavaScript, using "64-bit floating point numbers" as you proposed would suffer from the very same restriction.
IMHO the best option is to transmit such values as text. It would be still perfectly readable JSON content, and would be easy do work with at JavaScript level.
A "pure string" representation is what [OData specifies, for its `Edm.Int64` or `Edm.Decimal` types](https://stackoverflow.com/a/16549441/458259).
What the Twitter API does in this case, is to add a specific `".._str":` field in the JSON, as such:
```
{
"id": 10765432100123456789, // for JSON compliant clients
"id_str": "10765432100123456789", // for JavaScript
...
}
```
I like this option very much, since it would be still compatible with int64 capable clients. In practice, such duplicated content in the JSON won't hurt much, if it is deflated/gzipped at HTTP level.
Once transmitted as string, you may use libraries like [strint – a JavaScript library for string-encoded integers](https://github.com/rauschma/strint) to handle such values.
**Update:** Newer versions of JavaScript engines include a [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) object class, which is able to handle more than 53-bit. In fact, it can be used for arbitrarily large integers, so a good fit for 64-bit integer values. But when serializing as JSON, the BigInt value [will be serialized as a JSON string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json) - weirdly enough, but for compatibility purposes I guess.
|
What is the accepted way to send 64-bit values over JSON?
|
[
"",
"javascript",
"json",
"64-bit",
""
] |
At work one of our target platforms is a resource constrained mini-server running Linux (kernel 2.6.13, custom distribution based on an old Fedora Core). The application is written in Java (Sun JDK 1.6\_04). The Linux OOM killer is configured to kill processes when memory usage exceeds 160MB. Even during high load our application never go over 120MB and together with some other native processes that are active we stay well within the OOM limit.
However, it turns out that the Java Runtime.getRuntime().exec() method, the canonical way to execute external processes from Java, has a [particularly unfortunate implementation on Linux](http://developers.sun.com/solaris/articles/subprocess/subprocess.html) that causes spawned child processes to (temporarily) require the same amount of memory as the parent process since the address space is copied. The net result is that our application gets killed by the OOM killer as soon as we do Runtime.getRuntime().exec().
We currently work around this by having a separate native program do all external command execution and we communicate with that program over a socket. This is less than optimal.
After [posting about this problem online](http://aggregat4.net/2008/06/java-runtimeexec-dangerous-on-linux/) I got some feedback indicating that this should not occur on "newer" versions of Linux since they implement the posix fork() method using copy-on-write, presumably meaning it will only copy pages that it needs to modify when it is required instead of the entire address space immediately.
My questions are:
* Is this true?
* Is this something in the kernel, the libc implementation or somewhere else entirely?
* From what version of the kernel/libc/whatever is copy-on-write for fork() available?
|
This is pretty much the way \*nix (and linux) have worked since the dawn of time(or atleat the dawn of mmus).
To create a new process on \*nixes you call fork(). fork() creates a copy of the calling process with all its memory mappings, file descriptors, etc. The memory mappings are done copy-on-write so (in optimal cases) no memory is actually copied, only the mappings. A following exec() call replaces the current memory mapping with that of the new executable. So, fork()/exec() is the way you create a new process and that's what the JVM uses.
The caveat is with huge processes on a busy system, the parent might continue to run for a little while before the child exec()'s causing a huge amount of memory to be copied cause of the copy-on-write. In VMs , memory can be moved around a lot to facilitate a garbage collector which produces even more copying.
The "workaround" is to do what you've already done, create an external lightweight process that takes care of spawning new processes - or use a more lightweight approach than fork/exec to spawn processes (Which linux does not have - and would anyway require a change in the jvm itself). Posix specifies the posix\_spawn() function, which in theory can be implemented without copying the memory mapping of the calling process - but on linux it isn't.
|
Well, I personally doubt that this is true, since Linux's fork() is done via copy-on-write since God knows when (at least, 2.2.x kernels had it, and it was somewhere in the 199x).
Since OOM killer is believed to be a rather crude instrument which is known to misfire (f.e., it does not necessary kills the process that actually allocated most of the memory) and which should be used only as a last resport, it is not clear to me why you have it configured to fire on 160M.
If you want to impose a limit on memory allocation, then ulimit is your friend, not OOM.
My advice is to leave OOM alone (or disable it altogether), configure ulimits, and forget about this problem.
|
From what Linux kernel/libc version is Java Runtime.exec() safe with regards to memory?
|
[
"",
"java",
"linux",
"memory",
"out-of-memory",
""
] |
Python 3.0 is in beta with a final release coming shortly. Obviously it will take some significant time for general adoption and for it to eventually replace 2.x.
I am writing a tutorial about certain aspects of programming Python. I'm wondering if I should do it in Python 2.x or 3.0? (not that the difference is huge)
a 2.x tutorial is probably more useful now, but it would be nice to start producing 3.0 tutorials.
anyone have thoughts?
(of course I could do both, but I would prefer to do one or the other)
|
Start with 2.x. Most existing libraries will be on 2.x for a long time. Last year, [Guido himself said that it would be "two years"](http://www.artima.com/weblogs/viewpost.jsp?thread=211200) until you needed to learn 3.0; there's still another year left. Personally, I think it will be longer. People writing code on 2.x can learn how to use the `2to3` tool and have code that works on both versions. There is no 3to2, so code written for python 3 is significantly less valuable.
Thats not to mention how disappointing it will be for your students to learn that python 3 is not installed on their Linux computer ("`/usr/bin/python`" will be python 2.x for the next 5 years, at least), that there is no django for python 3, no wxwindows for python 3, no GTK for python 3, no Twisted for python 3, no PIL for python 3... the real strength of Python has always been in its extensive collection of libraries, and there are very few libraries for python 3 right now.
If your tutorial is well written, you should easily be able to update it to python 2.6, 2.7, and eventually python 3.
|
Van Rossum (creator of python) explains that "if you're starting a brand new thing, you should use 3.0." So most people looking to get started should even START with 3.0. It will be useful especially since there are probably very few out there now.
the [article](http://www.linux.com/feature/150399)
|
Tutorial for Python - Should I use 2.x or 3.0?
|
[
"",
"python",
"python-3.x",
"python-2.x",
""
] |
What's the best way for constructing headers, and footers? Should you call it all from the controller, or include it from the view file? I'm using CodeIgniter, and I'm wanting to know what's the best practice for this. Loading all the included view files from the controller, like this?
```
class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('header');
$this->load->view('menu');
$this->load->view('content', $data);
$this->load->view('footer');
}
}
```
or calling the single view file, and calling the header and footer views from there:
```
//controller file
class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('content', $data);
}
}
//view file
<?php $this->load->view('header'); ?>
<p>The data from the controller</p>
<?php $this->load->view('footer'); ?>
```
I've seen it done both ways, but want to choose now before I go too far down a path.
|
You could also try it this way -- define a default view template, which then pulls in the content based on a variable ('content' in my example) passed by the controller.
In your controller:
```
$data['content'] = 'your_controller/index';
// more code...
$this->load->vars($data);
$this->load->view('layouts/default');
```
Then define a default layout for all pages e.g. views/layouts/default.php
```
// doctype, header html etc.
<div id="content">
<?= $this->load->view($content) ?>
</div>
// footer html etc.
```
Then your views can just contain the pure content e.g. views/your\_controller/index.php might contain just the variables passed from the controller/data array
```
<?= $archives_table ?>
<?= $pagination ?>
// etc.
```
[More details on the CI wiki/FAQ](http://codeigniter.com/wiki/FAQ) -- (Q. How do I embed views within views? Nested templates?...)
|
Actually, after researching this quite a bit myself, I came to the conclusion that the best practice for including headers and footers in MVC is a third option - namely extending a base controller. That will give you a little more flexibility than the text's suggestion, particularly if you're building a very modular layout (not just header and footer, also sidebar panels, non-static menus, etc.).
First, define a `Base_controller` class, in which you create methods that append your page elements (header, footer, etc.) to an output string:
```
class Base_controller extends Controller
{
var $_output = '';
function _standard_header($data=null)
{
if (empty($data))
$data = ...; // set default data for standard header here
$this->_output .= $this->load->view('header', $data, true);
}
function _admin_header($data=null)
{
if (empty($data))
$data = ...; // set default data for expanded header here
$this->_output .= $this->load->view('admin_header', $data, true);
}
function _standard_page($data)
{
$this->_standard_header();
$this->_output .=
$this->load->view('standard_content', $data, true);
echo $this->_output; // note: place the echo statement in a
// separate function for added flexibility
}
function _page_with_admin_header($data)
{
$this->_admin_header($data);
$this->_output .=
$this->load->view('standard_content', $data, true);
echo $this->_output;
}
}
```
Then, in your page controllers, simply extend the base class and call your functions to build the page.
```
class Page_controller extends Base_controller
{
function index()
{
$data = ...; // Set content data here
$this->_standard_page($data);
}
function admin()
{
$data = ...; // Set content and header data here
$this->_page_with_admin_header($data);
}
}
```
Using a base controller, you can achieve very clean code in your individual page controllers AND have separate views for elements on the page (allowing code reuse in both views and controllers). All you need to do is define your common page 'sections' (what you might be tempted to call 'fragments') as functions in your base controller.
And if the base controller should start to grow uncontrollably (which can happen on large sites), you can rearrange some of its less-general functions by placing them in subclasses and letting the corresponding page controllers extend those instead of the original base controller.
Enjoy!
|
Best Practices: What's the Best Way for Constructing Headers and Footers?
|
[
"",
"php",
"codeigniter",
"templates",
""
] |
I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.
Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running.
For windows I use:
```
ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL);
```
For Linux I currently use:
```
pid_t pid;
char *args[2];
char *prog=0;
char firefox[]={"/usr/bin/firefox"};
if(strstri(filename,".html"))
prog=firefox;
if(prog)
{
args[0]=(char *)filename;
args[1]=0;
pid=fork();
if(!pid)
execvp(prog,args);
}
```
|
If you're writing this for modern distros, you can use `xdg-open`:
```
$ xdg-open http://google.com/
```
If you're on an older version you'll have to use a desktop-specific command like `gnome-open` or `exo-open`.
|
xdg-open is the new standard, and you should use it when possible. However, if the distro is more than a few years old, it may not exist, and alternative mechanisms include $BROWSER (older attempted standard), gnome-open (Gnome), kfmclient exec (KDE), exo-open (Xfce), or parsing mailcap yourself (the text/html handler will be likely be a browser).
That being said, most applications don't bother with that much work -- if they're built for a particular environment, they use that environment's launch mechanisms. For example, Gnome has gnome\_url\_show, KDE has KRun, most terminal programs (for example, mutt) parse mailcap, etc. Hardcoding a browser and allowing the distributor or user to override the default is common too.
I don't suggest hardcoding this, but if you really want to open a new tab in Firefox, you can use "firefox -new-tab $URL".
|
Launch web page from my application in Linux
|
[
"",
"c++",
"c",
"linux",
"browser",
""
] |
I'm working on a sparse matrix class that **needs** to use an array of `LinkedList` to store the values of a matrix. Each element of the array (i.e. each `LinkedList`) represents a row of the matrix. And, each element in the `LinkedList` array represents a column and the stored value.
In my class, I have a declaration of the array as:
```
private LinkedList<IntegerNode>[] myMatrix;
```
And, in my constructor for the `SparseMatrix`, I try to define:
```
myMatrix = new LinkedList<IntegerNode>[numRows];
```
The error I end up getting is
> Cannot create a generic array of `LinkedList<IntegerNode>`.
So, I have two issues with this:
1. What am I doing wrong, and
2. Why is the type acceptable in the declaration for the array if it can't be created?
`IntegerNode` is a class that I have created. And, all of my class files are packaged together.
|
You can't use generic array creation. It's a flaw/ feature of java generics.
The ways without warnings are:
1. Using List of Lists instead of Array of Lists:
```
List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>();
```
2. Declaring the special class for Array of Lists:
```
class IntegerNodeList {
private final List< IntegerNode > nodes;
}
```
|
For some reason you have to cast the type and make the declaration like this:
```
myMatrix = (LinkedList<IntegerNode>[]) new LinkedList<?>[numRows];
```
|
Cannot create an array of LinkedLists in Java...?
|
[
"",
"java",
"arrays",
"generics",
""
] |
Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward:
```
PostMethod method = new PostMethod();
method.addParameter("key", "value");
```
GetMethod doesn't have an "addParameter" method, though. I've discovered that this works:
```
GetMethod method = new GetMethod("http://www.example.com/page");
method.setQueryString(new NameValuePair[] {
new NameValuePair("key", "value")
});
```
However, most of the examples I've seen either hard-code the parameters directly into the URL, e.g.:
```
GetMethod method = new GetMethod("http://www.example.com/page?key=value");
```
or hard-code the query string, e.g.:
```
GetMethod method = new GetMethod("http://www.example.com/page");
method.setQueryString("?key=value");
```
Is one of these patterns to be preferred? And why the API discrepancy between PostMethod and GetMethod? And what are all those other HttpMethodParams methods intended to be used for?
|
Post methods have post parameters, but [get methods do not](http://www.cs.tut.fi/~jkorpela/forms/methods.html).
Query parameters are embedded in the URL. The current version of HttpClient accepts a string in the constructor. If you wanted to add the key, value pair above, you could use:
```
String url = "http://www.example.com/page?key=value";
GetMethod method = new GetMethod(url);
```
A good starting tutorial can be found on the [Apache Jakarta Commons page](http://hc.apache.org/httpclient-3.x/tutorial.html).
**Update**: As suggested in the comment, NameValuePair works.
```
GetMethod method = new GetMethod("example.com/page");
method.setQueryString(new NameValuePair[] {
new NameValuePair("key", "value")
});
```
|
It's not just a matter of personal preference. The pertinent issue here is URL-encoding your parameter values, so that the values won't get corrupted or misinterpreted as extra delimiters, etc.
As always, it is best to read the API documentation in detail:
[HttpClient API Documentation](http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpMethodBase.html#setQueryString(org.apache.commons.httpclient.NameValuePair[]))
Reading this, you can see that `setQueryString(String)` will NOT URL-encode or delimit your parameters & values, whereas `setQueryString(NameValuePair[])` will automatically URL-encode and delimit your parameter names and values. This is the best method whenever you are using dynamic data, because it might contain ampersands, equal signs, etc.
|
How do I add query parameters to a GetMethod (using Java commons-httpclient)?
|
[
"",
"java",
"httpclient",
"getmethod",
""
] |
I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this.
```
Dialog.Edit1.Text := MyObject.Username;
Dialog.Edit2.Text := MyObject.Password;
// ... many more of the same
if (Dialog.ShowModal = mrOk)
begin
MyObject.Username := Dialog.Edit1.Text;
MyObject.Password := Dialog.Edit2.Text;
// ... again, many more of the same
end;
```
I also often need similar code for marshalling objects to/from xml/ini-files/whatever.
Are there any common idioms or techniques for avoiding this kind of simple but repetitive code?
|
well, something that I feel completely invaluable is the [GExperts](http://www.gexperts.org) plugin wizard "Reverse Statement" which is invoked after installing GExperts by pressing Shift + ALT + R
What it does is automatically switch the assignments around for the highlighted block. For example:
```
edit1.text := dbfield.asString;
```
becomes
```
dbField.asString := edit1.text;
```
Not exactly what your looking for, but a huge time saver when you have a large number of assignments.
|
Here's my variation on this. What I did, having got fed up with the same repetitive code, was to name all the edit boxes according to the XML node names I wanted, then iterate around the components and output their values. The XML code should be obvious, and I only have an edit and checkbox, but you should be able to see the idea.
```
procedure TfrmFTPSetup.LoadFromXML(szFileName : string);
var
xComponent : TComponent;
nLoop : Integer;
xMainNode : TXmlNode;
xDocument : TNativeXml;
begin
inherited;
xDocument := TNativeXml.Create;
try
xDocument.LoadFromFile(szFileName);
xMainNode := xml_ChildNodeByName(xDocument.Root, 'options');
for nLoop := 0 to ComponentCount - 1 do
begin
xComponent := Components[nLoop];
if xComponent is TRzCustomEdit then
begin
(xComponent as TRzCustomEdit).Text := xMainNode.AttributeByName[xComponent.Name];
end;
if xComponent is TRzCheckBox then
begin
(xComponent as TRzCheckBox).Checked := xml_X2Boolean(xMainNode.AttributeByName[xComponent.Name], false);
end;
end;
finally
FreeAndNil(xDocument);
end;
end;
procedure TfrmFTPSetup.SaveToXML(szFileName : string);
var
xComponent : TComponent;
nLoop : Integer;
xMainNode : TXmlNode;
xDocument : TNativeXml;
begin
inherited;
xDocument := TNativeXml.CreateName('ftpcontrol');
try
xMainNode := xml_ChildNodeByNameCreate(xDocument.Root, 'options');
for nLoop := 0 to ComponentCount - 1 do
begin
xComponent := Components[nLoop];
if xComponent is TRzCustomEdit then
begin
xMainNode.AttributeByName[xComponent.Name] := (xComponent as TRzCustomEdit).Text;
end;
if xComponent is TRzCheckBox then
begin
xMainNode.AttributeByName[xComponent.Name] := xml_Boolean2X((xComponent as TRzCheckBox).Checked);
end;
end;
xDocument.XmlFormat := xfReadable;
xDocument.SaveToFile(szFileName);
finally
FreeAndNil(xDocument);
end;
end;
```
|
Avoiding Dialog Boilerplate in Delphi and /or C++
|
[
"",
"c++",
"delphi",
"modal-dialog",
"boilerplate",
""
] |
I have a class with both a static and a non-static interface in C#. Is it possible to have a static and a non-static method in a class with the same name and signature?
I get a compiler error when I try to do this, but for some reason I thought there was a way to do this. Am I wrong or is there no way to have both static and non-static methods in the same class?
If this is not possible, is there a good way to implement something like this that can be applied generically to any situation?
**EDIT**
From the responses I've received, it's clear that there is no way to do this. I'm going with a different naming system to work around this problem.
|
No you can't. The reason for the limitation is that static methods can also be called from non-static contexts without needing to prepend the class name (so MyStaticMethod() instead of MyClass.MyStaticMethod()). The compiler can't tell which you're looking for if you have both.
You can have static and non-static methods with the same name, but different parameters following the same rules as method overloading, they just can't have exactly the same signature.
|
Actually, there kind of is a way to accomplish this by explicitly implementing an interface. It is not a perfect solution but it can work in some cases.
```
interface IFoo
{
void Bar();
}
class Foo : IFoo
{
static void Bar()
{
}
void IFoo.Bar()
{
Bar();
}
}
```
I sometimes run into this situation when I make wrapper classes for P/Invoke calls.
|
Static and Instance methods with the same name?
|
[
"",
"c#",
".net",
"oop",
""
] |
In `.NET` (at least in the 2008 version, and maybe in 2005 as well), changing the `BackColor` property of a `DateTimePicker` has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar?
***Edit:*** I was talking about Windows forms, not ASP.
|
According to [MSDN](http://msdn.microsoft.com/en-us/library/0625h0ta.aspx) :
> Setting the `BackColor` has no effect on
> the appearance of the `DateTimePicker`.
You need to write a custom control that extends `DateTimePicker`. Override the `BackColor` property and the `WndProc` method.
Whenever you change the `BackColor`, don't forget to call the `myDTPicker.Invalidate()` method. This will force the control to redrawn using the new color specified.
```
const int WM_ERASEBKGND = 0x14;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if(m.Msg == WM_ERASEBKGND)
{
using(var g = Graphics.FromHdc(m.WParam))
{
using(var b = new SolidBrush(_backColor))
{
g.FillRectangle(b, ClientRectangle);
}
}
return;
}
base.WndProc(ref m);
}
```
|
There is a free implementation derived from `DateTimePicker` that allows you to change `BackColor` property on change.
See the CodeProject website: [`DateTimePicker` with working `BackColor`](http://www.codeproject.com/KB/selection/DateTimePicker_With_BackC.aspx)
|
Changing the background color of a DateTimePicker in .NET
|
[
"",
"c#",
".net",
"vb.net",
"winforms",
""
] |
I'm using the following code to loop through a directory to print out the names of the files. However, not all of the files are displayed. I have tried using **clearstatcache** with no effect.
```
$str = '';
$ignore = array('.', '..');
$dh = @opendir( $path );
if ($dh === FALSE)
{
// error
}
$file = readdir( $dh );
while( $file !== FALSE )
{
if (in_array($file, $ignore, TRUE)) { break; }
$str .= $file."\n";
$file = readdir( $dh );
}
```
Here's the contents of the directory right now:
```
root.auth test1.auth test2.auth test3.auth test5.auth
```
However, test5.auth does not appear. If I rename it to test4.auth it does not appear. If I rename it to test6.auth it **does** appear. This is reliable behaviour - I can rename it several times and it still won't show up unless I rename it to test6.auth.
What on earth could be happening?
I'm running Arch Linux (kernel 2.6.26-ARCH) with PHP Version 5.2.6 and Apache/2.2.9 with Suhosin-Patch. My filesystem is ext3 and I'm running fam 2.6.10.
|
Your `break` keywords messes up your code:
Your loop very likely first encounters the '.' directory and than breaks out of your while loop.
try replacing it with a `continue` and you should be fine.
|
Continue won't work either, because you will skip the line that reads the next file.
You could get rid of the first `$file = readdir( $dh );` and then do
```
while (false !== ($file = readdir($dh))) {
if (in_array($file, $ignore, TRUE)) { continue; }
$str .= $file."\n";
}
```
|
PHP readdir is not reading some files
|
[
"",
"php",
""
] |
Is there any advantage of using
[**java.util.concurrent.CountdownLatch**](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html)
instead of
[**java.util.concurrent.Semaphore**](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html)?
As far as I can tell the following fragments are almost equivalent:
**1. Semaphore**
```
final Semaphore sem = new Semaphore(0);
for (int i = 0; i < num_threads; ++ i)
{
Thread t = new Thread() {
public void run()
{
try
{
doStuff();
}
finally
{
sem.release();
}
}
};
t.start();
}
sem.acquire(num_threads);
```
**2: CountDownLatch**
```
final CountDownLatch latch = new CountDownLatch(num_threads);
for (int i = 0; i < num_threads; ++ i)
{
Thread t = new Thread() {
public void run()
{
try
{
doStuff();
}
finally
{
latch.countDown();
}
}
};
t.start();
}
latch.await();
```
Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)
So in what situation might the latch be preferable?
|
`CountDownLatch` is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on `await()` that would all start simultaneously when the countown reached zero.
```
final CountDownLatch countdown = new CountDownLatch(1);
for (int i = 0; i < 10; ++ i) {
Thread racecar = new Thread() {
public void run() {
countdown.await(); //all threads waiting
System.out.println("Vroom!");
}
};
racecar.start();
}
System.out.println("Go");
countdown.countDown(); //all threads start now!
```
You could also use this as an MPI-style "barrier" that causes all threads to wait for other threads to catch up to a certain point before proceeding.
```
final CountDownLatch countdown = new CountDownLatch(num_thread);
for (int i = 0; i < num_thread; ++ i) {
Thread t= new Thread() {
public void run() {
doSomething();
countdown.countDown();
System.out.printf("Waiting on %d other threads.",countdown.getCount());
countdown.await(); //waits until everyone reaches this point
finish();
}
};
t.start();
}
```
That all said, the `CountDownLatch` can safely be used in the manner you've shown in your example.
|
[CountDownLatch](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html) is used to start a series of threads and then wait until all of them are complete (or until they call `countDown()` a given number of times.
Semaphore is used to control the number of concurrent threads that are using a resource. That resource can be something like a file, or could be the cpu by limiting the number of threads executing. The count on a Semaphore can go up and down as different threads call `acquire()` and `release()`.
In your example, you're essentially using Semaphore as a sort of Count*UP*Latch. Given that your intent is to wait on all threads finishing, using the `CountdownLatch` makes your intention clearer.
|
CountDownLatch vs. Semaphore
|
[
"",
"java",
"multithreading",
"concurrency",
"semaphore",
"countdownlatch",
""
] |
***Imagine*** a base class with many constructors and a virtual method
```
public class Foo
{
...
public Foo() {...}
public Foo(int i) {...}
...
public virtual void SomethingElse() {...}
...
}
```
and now i want to create a descendant class that overrides the virtual method:
```
public class Bar : Foo
{
public override void SomethingElse() {...}
}
```
And another descendant that does some more stuff:
```
public class Bah : Bar
{
public void DoMoreStuff() {...}
}
```
Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?
Is there no way to inherit constructors? Is there no way to encourage code reuse?
|
Yes, you will have to implement the constructors that make sense for each derivation and then use the `base` keyword to direct that constructor to the appropriate base class or the `this` keyword to direct a constructor to another constructor in the same class.
If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like `null` and only expose the necessary ones through their constructors.
# Update
In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.
|
387 constructors?? That's your main problem. How about this instead?
```
public Foo(params int[] list) {...}
```
|
How to inherit constructors?
|
[
"",
"c#",
"inheritance",
"constructor",
""
] |
Is there a `Python` module for converting `wiki markup` to other languages (e.g. `HTML`)?
A similar question was asked here, [What's the easiest way to convert wiki markup to html](https://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html), but no `Python` modules are mentioned.
Just curious. :) Cheers.
|
Django uses the following libraries for markup:
* [Markdown](http://www.freewisdom.org/projects/python-markdown/)
* [Textile](http://pypi.python.org/pypi/textile)
* [reStructuredText](http://docutils.sourceforge.net/rst.html)
You can see [how they're used in Django](http://code.djangoproject.com/browser/django/trunk/django/contrib/markup/templatetags/markup.py).
|
[mwlib](https://github.com/pediapress/mwlib) provides ways of converting MediaWiki formatted text into HTML, PDF, DocBook and OpenOffice formats.
|
Python module for wiki markup
|
[
"",
"python",
"wiki",
"markup",
""
] |
Note, I realize that this has been addressed [here](https://stackoverflow.com/questions/944/unhandled-exception-handler-in-net-11). That post discusses exception handling in .NET 1.1 while implying that there is a better solution for >.NET 2.0 so this question is specifically about the more recent .NET versions.
I have a windows forms application which is expected to frequently and unexpectedly lose connectivity to the database, in which case it is to reset itself to its initial state.
I am already doing error logging, retry connection, etc. through a set of decorators on my custom DBWrapper object. After that is taken care of however, I would like to let the error fall through the stack. Once it reaches the top and is unhandled I would like it to be swallowed and my ApplicationResetter.Reset() method to be executed.
Can anyone tell me how to do this?
If this is impossible, then is there at least a way to handle this without introducing a dependency on ApplicationResetter to every class which might receive such an error and without actually shutting down and restarting my application (which would just look ugly)?
|
For Windows Forms threads (which call Application.Run()), assign a ThreadException handler at the beginning of Main(). Also, I found it was necessary to call SetUnhandledExceptionMode:
```
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);
Application.ThreadException += ShowUnhandledException;
Application.Run(...);
```
Here is an example handler. I know it's not what you're looking for, but it shows the format of the handler. Notice that if you want the exception to be fatal, you have to explicitly call Application.Exit().
```
static void ShowUnhandledException(object sender, ThreadExceptionEventArgs t)
{
Exception ex = t.Exception;
try {
// Build a message to show to the user
bool first = true;
string msg = string.Empty;
for (int i = 0; i < 3 && ex != null; i++) {
msg += string.Format("{0} {1}:\n\n{2}\n\n{3}",
first ? "Unhandled " : "Inner exception ",
ex.GetType().Name,
ex.Message,
i < 2 ? ex.StackTrace : "");
ex = ex.InnerException;
first = false;
}
msg += "\n\nAttempt to continue? (click No to exit now)";
// Show the message
if (MessageBox.Show(msg, "Unhandled exception", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No)
Application.Exit();
} catch (Exception e2) {
try {
MessageBox.Show(e2.Message, "Fatal error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
} finally {
Application.Exit();
}
}
}
```
|
caveat: not familiar with 3.5 yet, there may be a better answer ...
...but my understanding is that by the time the event gets to the unhandled exception handler, the app is probably going to die - and if it doesn't die, it may be so corrupted that it should die anyway
if you are already handling a db-not-there case and are letting other exceptions pass through, then the app should die as it may be unstable
|
Is there a way to define an action for unhandled exceptions in a WinForms .NET 3.5 app?
|
[
"",
"c#",
".net",
"exception",
""
] |
Suppose I have a base class B, and a derived class D. I wish to have a method foo() within my base class that returns a new object of whatever type the instance is. So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.
Is this possible?
|
Don't. Make the "foo" method abstract.
```
abstract class B {
public abstract B foo();
}
```
Or receive an abstract factory through the base class constructor:
```
abstract class B {
private final BFactory factory;
protected B(BFactory factory) {
this.factory = factory;
}
public B foo() {
return factory.create();
}
}
interface BFactory {
B create();
}
```
Add covariant return types and generics to taste.
|
As long as each class has a default constructor:
```
public B instance() throws Exception {
return getClass().newInstance();
}
```
|
Java: Newbie-ish inheritance question
|
[
"",
"java",
"inheritance",
"types",
"derived-class",
"base-class",
""
] |
I have an application running in tomcat that has a bunch of configuration files that are different for each environment it runs in (dev, testing, and production). But not every line in a config file will be different between environments so there's invariably duplicated information that doesn't get updated if something changes.
Is there a good framework/library that collapses the separate files into one with environment specific blocks? Or some other way of dealing with this?
|
1. Assign reasonable default values for all properties in the properties files distributed within your .war file.
2. Assign environment-specific values for the appropriate properties in webapp context (e.g. conf/server.xml or conf/Catalina/localhost/yourapp.xml)
3. Have your application check the context first (for the environment-specific values), and fall back on the default values in the app's properties values if no override is found.
|
A Properties file is what I've always used. It's editable by hand as well as in in your software and the Properties object can read itself in and write itself out to the filesystem. Here's the javadoc page:
<http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html>
|
What is the best way to deal with environment specific configuration in java?
|
[
"",
"java",
"configuration",
"tomcat",
""
] |
I'd like to sprinkle some print statements in my code to show where I am and print important values to a console window.
How do I do that, but then be able to turn it off for the release version?
|
All calls to [`System.Diagnostics.Debug.Print()`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.print.aspx) will be removed when you switch to a release version.
|
Use [Log4net](http://logging.apache.org/log4net/index.html) with logging at debug level in release and warn or error level in production.
Benefit to this is that you can turn logging back on in the release environment if you have problems there that you can't recreate in development.
[EDIT] FWIW, I find that I do a **LOT** less debug logging now that I use Test-Driven Development. Most of my logging is of the warn/error variety.
|
Disable Debugging Output
|
[
"",
"c#",
".net",
"debugging",
"console",
""
] |
A prospective client wants to have a calendar feature on their website. They want the option to go edit this calendar to update the events. Does Word Press offer something like this?
|
I've seen people use Google Calendar for this. Then you can easily embed google cal in your web pages. Also, if others use Google Cal they can add evens to their calendars.
<http://www.google.com/support/calendar/bin/answer.py?hl=en&answer=41207>
Update: Looks like this plugin will help with getting google cal into Wordpress if that's what you're looking for :
[WoogleCal](http://www.blueace.nl/wooglecal/)
|
Sounds like you might be searching for [this](http://wordpress.org/extend/plugins/event-calendar/).
|
Creating a client editable events calendar in html or php
|
[
"",
"php",
"html",
"wordpress",
"calendar",
""
] |
Say you have a web form with some fields that you want to validate to be only some subset of alphanumeric, a minimum or maximum length etc.
You can validate in the client with javascript, you can post the data back to the server and report back to the user, either via ajax or not. You could have the validation rules in the database and push back error messages to the user that way.
Or any combination of all of the above.
If you want a single place to keep validation rules for web application user data that persist to a database, what are some best practices, patterns or general good advice for doing so?
[edit]
I have edited the question title to better reflect my actual question! Some great answers so far btw.
|
all of the above:
1. client-side validation is more convenient for the user
2. but you can't trust the client so the code-behind should also validate
3. similarly the database can't trust that you validated so validate there too
EDIT: i see that you've edited the question to ask for a single point of specification for validation rules. This is called a "Data Dictionary" (DD), and is a Good Thing to have and use to generate validation rules in the different layers. Most systems don't, however, so don't feel bad if you never get around to building such a thing ;-)
One possible/simple design for a DD for a modern 3-tier system might just include - along with the usual max-size/min-size/datatype info - a Javascript expression/function field, C# assembly/class/method field(s), and a sql expression field. The javascript could be slotted into the client-side validation, the C# info could be used for a reflection load/call for server-side validation, and the sql expression could be used for database validation.
But while this is all good in theory, I don't know of any real-world systems that actually do this in practice [though it "sounds" like a Good Idea].
If you do, let us know how it goes!
|
To answer the actual question:
First of all it isn't allways the case that the databse restriction matches client side restrictions. So it would probably be a bad idea to limit yourself to only validate based on database constraints.
But then again, you do want the databse constraints to be reflected in your datamodel. So a first approximation would probably be to defins some small set of perdicates that is mappeble to both check constraints, system language and javascript.
Either that or you just take care to kepp the three representations in the same place so you remember to keep them in sync when changeing something.
But suppose you do want another set of restrictions used in a particular context where the domain model isn't restrictive enough, or maybe it's data that isn't in the model at all. It would probably be a good idea if you could use the same framwork used to defin model restriction to define other kinds of restrictions.
Maybe the way to go is to define a small managable DSL for perdicates describing the restriction. Then you produce "compilers" that parses this DSL and provides the representation you need.
The "DSL" doesn't have to be that fancy, simple string and int validation isn't that much of a problem. RegEx validation could be a problem if your database doesn't support it though. You can probably design this DSL as just a set of classes or what your system language provides that can be combined into expressions with simple boolean algebra.
|
Where do you record validation rules for form data in a web application?
|
[
"",
"javascript",
"design-patterns",
"validation",
""
] |
Is it possible to see the return value of a method after the line has been run and before the instruction pointer returns to the calling function?
I am debugging code I can't modify *(read: don't want to re-compile a third party library)*, and sometimes it jumps to code I don't have source to or the return expression has side effects that stop me being able to just run the expression in the *Display* tab.
Often the return value is used in a compound statement, and so the *Variables* view will never show me the value (hence wanting to see the result before control returns to the calling function).
**UPDATE:** I can't use the expression viewer as there are side-effects in the statement.
|
This feature was added to Eclipse version 4.7 M2 under [Eclipse bug 40912](https://bugs.eclipse.org/bugs/show_bug.cgi?id=40912).
To use it:
* step over the `return` statement (using "Step Over" or "Step Return")
* now the first line in the variable view will show the result of the return statement, as "[statement xxx] returned: "
See [Eclipse Project Oxygen (4.7) M2 - New and Noteworthy](https://www.eclipse.org/eclipse/news/4.7/M2/#step-show-methodresult) for details.
|
Found a really good shortcut for this.
Select the expression which returns the value and press
```
Ctrl + Shift + D
```
This will display the value of the return statement. This is really helpful in cases where you can't or don't want to change just for debugging purpose.
Hope this helps.
Note: Have not tested this with third party libraries, but it is working fine for my code.
Tested this on *Eclipse Java EE IDE for Web Developers. Version: Juno Service Release 1*
|
Can I find out the return value before returning while debugging in Eclipse?
|
[
"",
"java",
"eclipse",
"debugging",
"return-value",
""
] |
Having difficulty articulating this correlated subquery. I have two tables fictitious tables, foo and bar. foo has two fields of foo\_id and total\_count. bar has two fields, seconds and id.
I need to aggregate the seconds in bar for each individual id and update the total\_count in foo. id is a foreign key in bar for foo\_id.
I've tried something similar without much luck:
```
UPDATE foo f1 set total_count = (SELECT SUM(seconds) from bar b1 INNER JOIN foo f2 WHERE b1.foo_id = f2.id) WHERE f1.foo_id = bar.id;
```
|
```
UPDATE foo f1
SET total_count = (SELECT SUM(seconds)
FROM bar b1 WHERE b1.id = f1.foo_id)
```
You should have access to the appropriate foo id within the sub-query, so there is no need to join in the table.
|
In larger data sets, correlated subqueries can be very resource-intensive. Joining to a derived table containing the appropriate aggregates can be much more efficient:
```
create table foo ( foo_id int identity, total_count int default 0 )
create table bar ( foo_id int, seconds int )
insert into foo default values
insert into foo default values
insert into foo default values
insert into bar values ( 1, 10 )
insert into bar values ( 1, 11 )
insert into bar values ( 1, 12 )
/* total for foo_id 1 = 33 */
insert into bar values ( 2, 10 )
insert into bar values ( 2, 11 )
/* total for foo_id 2 = 21 */
insert into bar values ( 3, 10 )
insert into bar values ( 3, 19 )
/* total for foo_id 3 = 29 */
select *
from foo
foo_id total_count
----------- -----------
1 0
2 0
3 0
update f
set total_count = sumsec
from foo f
inner join (
select foo_id
, sum(seconds) sumsec
from bar
group by foo_id
) a
on f.foo_id = a.foo_id
select *
from foo
foo_id total_count
----------- -----------
1 33
2 21
3 29
```
|
MySQL correlated subquery
|
[
"",
"mysql",
"sql",
"inner-join",
""
] |
What is the best way for converting phone numbers into international format (E.164) using Java?
Given a 'phone number' and a country id (let's say an ISO country code), I would like to convert it into a standard E.164 international format phone number.
I am sure I can do it by hand quite easily - but I would not be sure it would work correctly in all situations.
Which Java framework/library/utility would you recommend to accomplish this?
P.S. The 'phone number' could be anything identifiable by the general public - such as
```
* (510) 786-0404
* 1-800-GOT-MILK
* +44-(0)800-7310658
```
that last one is my favourite - it is how some people write their number in the UK and means that you should either use the +44 or you should use the 0.
The E.164 format number should be all numeric, and use the full international country code (e.g.+44)
|
Google provides a library for working with phone numbers. The same one they use for Android
<http://code.google.com/p/libphonenumber/>
```
String swissNumberStr = "044 668 18 00"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
// Produces "+41 44 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));
// Produces "044 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));
// Produces "+41446681800"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));
```
|
Speaking from experience at writing this kind of thing, it's really difficult to do with 100% reliability. I've written some Java code to do this that is reasonably good at processing the data we have but won't be applicable in every country. Questions you need to ask are:
Are the character to number mappings consistent between countries? The US uses a lot of this (eg 1800-GOT-MILK) but in Australia, as one example, its pretty rare. What you'd need to do is ensure that you were doing the correct mapping for the country in question if it varies (it might not). I don't know what countries that use different alphabets (eg Cyrilic in Russia and the former Eastern block countries) do;
You have to accept that your solution will not be 100% and you should not expect it to be. You need to take a "best guess" approach. For example, theres no real way of knowing that 132345 is a valid phone number in Australia, as is 1300 123 456 but that these are the only two patterns that are for 13xx numbers and they're not callable from overseas;
You also have to ask if you want to validate regions (area codes). I believe the US uses a system where the second digit of the area code is a 1 or a 0. This may have once been the case but I'm not sure if it still applies. Whatever the case, many other countries will have other rules. In Australia, the valid area codes for landlines and mobile (cell) phones are two digits (the first is 0). 08, 03 and 04 are all valid. 01 isn't. How do you cater for that? Do you want to?
Countries use different conventions no matter how many digits they're writing. You have to decide if you want to accept something other than the "norm". These are all common in Australia:
* (02) 1234 5678
* 02 1234 5678
* 0411 123 123 (but I've never seen 04 1112 3456)
* 131 123
* 13 1123
* 131 123
* 1 300 123 123
* 1300 123 123
* 02-1234-5678
* 1300-234-234
* +44 78 1234 1234
* +44 (0)78 1234 1234
* +44-78-1234-1234
* +44-(0)78-1234-1234
* 0011 44 78 1234 1234 (0011 is the standard international dialling code)
* (44) 078 1234 1234 (not common)
And thats just off the top of my head. For one country. In France, for example, its common the write the phone number in number pairs (12 34 56 78) and they pronounce it that way too: instead of:
un (one), deux (two), trois (three), ...
its
douze (twelve), trente-quatre (thirty four), ...
Do you want to cater for that level of cultural difference? I would assume not but the question is worth considering just in case you make your rules too strict.
Also some people may append extension numbers on phone numbers, possibly with "ext" or similar abbreviation. Do you want to cater for that?
Sorry, no code here. Just a list of questions to ask yourself and issues to consider. As others have said, a series of regular expressions can do much of the above but ultimately phone number fields are (mostly) free form text at the end of the day.
|
What is the best way for converting phone numbers into international format (E.164) using Java?
|
[
"",
"java",
"validation",
"formatting",
"phone-number",
""
] |
Can anyone recommend any good resources for learning C++ Templates?
Many thanks.
|
I've found [cplusplus.com](http://www.cplusplus.com/) to be helpful on numerous occasions. Looks like they've got a pretty good intro to [templates.](http://www.cplusplus.com/doc/tutorial/templates.html)
If its an actual book you're looking for, [Effective C++](https://rads.stackoverflow.com/amzn/click/com/0321334876) is a classic with a great section on templates.
|
I recomned that you get [C++ Templates - The Complete Guide](http://www.josuttis.com/tmplbook/) it's an excellent resource and reference.
|
Learning C++ Templates
|
[
"",
"c++",
"templates",
""
] |
I want to call `ShowDialog()` when a keyboard hook event is triggered, but I'm having some difficulties:
* ShowDialog() blocks, so I can't call it from the hook triggered event, because it will block the OS.
* I can start a new thread and call `ShowDialog()` from there, but I get some nasty exception. I guess I can't call `ShowDialog()` in any other thread.
* I can start a timer: in the next 50 milliseconds call `ShowDialog()` (which is a nasty hack BTW, and I rather not do this). But then the timer fires in a new thread, and then I run into the same problem explained in the previous bullet.
Is there a way?
|
The problem may be that you are trying to put UI in a non-UI thread. Make your event fire from another thread and invoke the method that runs `ShowDialog()` from your UI thread.
Essentially, you want to keep your UI on the UI thread and move anything else to a back ground thread.
Check out [Gekki Software](http://www.gekko-software.nl/DotNet/Art05.htm) for some details (there are zillions of others - this just happens to be the first one I found in research archives).
|
I'm not sure about ShowDialog, but whenever you get an exception when trying to do something with the UI in a background thread, it means you should use the UI dispatcher.
Try calling the BeginInvoke method (if you are on Windows Forms) of any UI object you control with a delegate that calls the showdialog.
Also, make sure to try (before this) passing a reference to a valid owner in the show dialog method.
|
ShowDialog() from keyboard hook event in C#
|
[
"",
"c#",
"keyboard-hook",
""
] |
I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.
I'd like to do this purely from (Py)GTK+, but I am amenable to calling platform-specific functions. Ideally I'd like to call functions which have already been wrapped from Python, but if that's not possible, I'm not above a little bit of C or `ctypes` code, as long as I know what I'm actually looking for.
On Windows I think the function I want is [`GetLastInputInfo`](http://msdn.microsoft.com/en-us/library/ms646302.aspx), but that doesn't seem to be wrapped by pywin32; I hope I'm missing something.
|
[Gajim](http://www.gajim.org/) does it this way on Windows, OS X and GNU/Linux (and other \*nixes):
1. [Python wrapper module](https://dev.gajim.org/gajim/gajim/blob/89c7eb6e6ab3f61a188c6cee063a000526df522c/gajim/common/sleepy.py) (also includes Windows idle time detection code, using `GetTickCount` with `ctypes`);
2. [Ctypes-based module to get X11 idle time](https://dev.gajim.org/gajim/gajim/blob/89c7eb6e6ab3f61a188c6cee063a000526df522c/gajim/common/idle.py) (using `XScreenSaverQueryInfo`, was a C module in old Gajim versions);
3. [C module to get OS X idle time](https://dev.gajim.org/gajim/gajim/blob/8ee54c65325d6670fffc6df8d773f811c5bf0243/src/common/idle_c/idle.c) (using `HIDIdleTime` system property).
Those links are to quite dated 0.12 version, so you may want to check current source for possible further improvements and changes.
|
If you use PyGTK and X11 on Linux, you can do something like this, which is based on what Pidgin does:
```
import ctypes
import ctypes.util
import platform
class XScreenSaverInfo(ctypes.Structure):
_fields_ = [('window', ctypes.c_long),
('state', ctypes.c_int),
('kind', ctypes.c_int),
('til_or_since', ctypes.c_ulong),
('idle', ctypes.c_ulong),
('eventMask', ctypes.c_ulong)]
class IdleXScreenSaver(object):
def __init__(self):
self.xss = self._get_library('Xss')
self.gdk = self._get_library('gdk-x11-2.0')
self.gdk.gdk_display_get_default.restype = ctypes.c_void_p
# GDK_DISPLAY_XDISPLAY expands to gdk_x11_display_get_xdisplay
self.gdk.gdk_x11_display_get_xdisplay.restype = ctypes.c_void_p
self.gdk.gdk_x11_display_get_xdisplay.argtypes = [ctypes.c_void_p]
# GDK_ROOT_WINDOW expands to gdk_x11_get_default_root_xwindow
self.gdk.gdk_x11_get_default_root_xwindow.restype = ctypes.c_void_p
self.xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)
self.xss.XScreenSaverQueryExtension.restype = ctypes.c_int
self.xss.XScreenSaverQueryExtension.argtypes = [ctypes.c_void_p,
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
self.xss.XScreenSaverQueryInfo.restype = ctypes.c_int
self.xss.XScreenSaverQueryInfo.argtypes = [ctypes.c_void_p,
ctypes.c_void_p,
ctypes.POINTER(XScreenSaverInfo)]
# gtk_init() must have been called for this to work
import gtk
gtk # pyflakes
# has_extension = XScreenSaverQueryExtension(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
# &event_base, &error_base);
event_base = ctypes.c_int()
error_base = ctypes.c_int()
gtk_display = self.gdk.gdk_display_get_default()
self.dpy = self.gdk.gdk_x11_display_get_xdisplay(gtk_display)
available = self.xss.XScreenSaverQueryExtension(self.dpy,
ctypes.byref(event_base),
ctypes.byref(error_base))
if available == 1:
self.xss_info = self.xss.XScreenSaverAllocInfo()
else:
self.xss_info = None
def _get_library(self, libname):
path = ctypes.util.find_library(libname)
if not path:
raise ImportError('Could not find library "%s"' % (libname, ))
lib = ctypes.cdll.LoadLibrary(path)
assert lib
return lib
def get_idle(self):
if not self.xss_info:
return 0
# XScreenSaverQueryInfo(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
# GDK_ROOT_WINDOW(), mit_info);
drawable = self.gdk.gdk_x11_get_default_root_xwindow()
self.xss.XScreenSaverQueryInfo(self.dpy, drawable, self.xss_info)
# return (mit_info->idle) / 1000;
return self.xss_info.contents.idle / 1000
```
The example above uses gdk via ctypes to be able to access the X11 specific. Xscreensaver APIs also need to be accessed via ctypes.
It should be pretty easy to port it to use PyGI and introspection.
|
How can I determine the display idle time from Python in Windows, Linux, and MacOS?
|
[
"",
"python",
"winapi",
"gtk",
"pygtk",
"pywin32",
""
] |
I found this:
<http://www.evolt.org/failover-database-connection-with-php-mysql>
and similar examples. But is there a better way?
I am thinking along the lines of the [Automatic Failover Client](http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/implappfailover.mspx#EMD) in the MS SQL Native Client.
|
It's traditional to handle failover strategies at the system level; that way all applications can enjoy a robust environment.
I'd like to refer to [MySQL failover strategy](http://dev.mysql.com/tech-resources/articles/failover-strategy-part1.html) and [MySQL proxy](http://forge.mysql.com/wiki/MySQL_Proxy). The latter describes a MySQL utility that can do load balancing and failover, and seems quite easy to set up.
Not the answer to the question, but it is the more common solution to handle failover.
|
There's nothing built in to handle that in PHP. You have to write the code yourself.
The best approach would be to abstract your database access and create a class that can encapsulate the failover logic.
Here's some code, off the cuff:
```
interface MySQL_Interface {
public function query($sql);
}
class MySQL_Concrete implements MySQL_Interface {
public function __construct($host, $user, $pass, $dbname) {
$this->_mysql = mysql_connect($host, $user, $pass) or throw Exception("Could not connect to server");
mysql_select_db($db, $this->_mysql) or throw Exception("Could not connect to database");
}
public function query($sql) {
return mysql_query($sql) or throw new Exception("Query failed");
}
}
class MySQL_Failover implements MySQL_Interface {
public function __construct(MySQL_Interface $one, MySQL_Interface $two) {
$this->_one = $one;
$this->_two = $two;
}
public function query($sql) {
try {
return $this->_one->query($sql);
} catch (Exception $e) {
return $this->_two->query($sql);
}
}
}
$db = new MySQL_Failover(
new MySQL_Concrete('host1', 'user', 'pass', 'db'),
new MySQL_Concrete('host2', 'user', 'pass', 'db')
);
$db->query('SELECT * FROM Users');
```
*PS: I've left quite a bit out of here, it's not to be used verbatim.*
*PPS: I'd probably be better to use an existing database abstraction library (Zend\_Db, MDB2, ect) and implement their interface instead of creating your own ad-hoc solution*
|
Does PHP have a built in mechanism to failover from one database server to another?
|
[
"",
"php",
"mysql",
"database",
"failover",
""
] |
How do I pull out the filename from a full path using regular expressions in C#?
Say I have the full path `C:\CoolDirectory\CoolSubdirectory\CoolFile.txt`.
How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out.
Also, in the course of trying to solve this problem, I realized that I can just use `System.IO.Path.GetFileName`, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.
|
```
// using System.Text.RegularExpressions;
/// <summary>
/// Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM
/// Using Expresso Version: 3.0.2766, http://www.ultrapico.com
///
/// A description of the regular expression:
///
/// Any character that is NOT in this class: [\\], any number of repetitions
/// End of line or string
///
///
/// </summary>
public static Regex regex = new Regex(
@"[^\\]*$",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
```
**UPDATE:** removed beginning slash
|
Why must you use regular expressions? .NET has the built-in `Path.GetFileName()` method specifically for this which works across platforms and filesystems.
|
Parse filename from full path using regular expressions in C#
|
[
"",
"c#",
".net",
"regex",
""
] |
Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious?
For example, imagine I have this class in C++:
```
public class SomeClass {
private:
bool mIsVisible;
public:
void draw();
void erase();
}
```
I could add functions to get/set "mIsVisible" like this:
```
bool getVisible() { return mIsVisible; };
```
void setVisible(bool visible) {
if (!mIsVisible && visible) {
draw();
} else if (mIsVisible && !visible) {
erase();
}
```
mIsVisible = visible;
```
}
However, it would be equally possible to use the following methods instead:
```
bool isVisible() { return mIsVisible; };
void show() {
if (!mIsVisible) {
mIsVisible = true;
draw();
}
}
void hide() {
if (mIsVisible) {
mIsVisible = false;
erase();
}
}
```
In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing?
|
Have a read of the article "[Tell, Don't Ask](http://www.pragprog.com/articles/tell-dont-ask)" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go.
Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely:
1. get current visibility value,
2. make decision based on value,
3. update object.
|
In the example you gave, `show()` and `hide()` make a lot of sense, at least to me.
On the other hand, if you had a property `skinPigment` and you decided to make functions called `tanMe()` and `makeAlbino()` that would be a really poor, non-obvious choice.
It is subjective, you have to try to think the way your users (the people utilizing this class) think. Whichever way you decide, it should be obvious to them, and **well-documented.**
|
Which is more appropriate: getters and setters or functions?
|
[
"",
"c++",
"coding-style",
"setter",
"getter",
""
] |
I'm trying to determine the best way of having a PHP script determine which server the script/site is currently running on.
At the moment I have a `switch()` that uses `$_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']` to determine which server it's on. It then sets a few paths, db connection parameters, SMTP paramters and debug settings based on which server it's on. (There maybe additional parameters depending on the site needs.)
This means that I can simply drop the site onto any of the configured servers without having to change any code (specifically the configuration). If it's a new server, then I simply add a new `case` and it's ready from then on.
We have done loading config files based on the same `SERVER_NAME:SERVER_PORT` combination, but found that it's another file you have to maintain, plus we weren't sure on the speed of parsing ini files, (although having extra cases for each server may be just as slow).
Another problem we have is when a site is often moved between 2 servers, but we use the same `SERVER_NAME` and `SERVER_PORT` on each. This means we need to temporarily comment one case and ensure it doesn't get into the repo.
Another other ideas? It needs to be available on all servers (sometimes `SERVER_NAME` and `SERVER_PORT` are not). It would also be nice if it worked with the CLI PHP.
|
How about using **$\_SERVER['SERVER\_ADDR']** and base your identity off the IP address of the server.
UPDATE: In a virtual host situation, you might also like to concatenate the IP with the document root path like so:
```
$id = $_SERVER['SERVER_ADDR'] . $_SERVER['DOCUMENT_ROOT'];
```
|
We use the $\_SERVER['HTTP\_HOST'] variable to create the filename of a PHP include file which contains all the vhost-specific information (we deploy the same software to a lot of vhosts)
I like this technique, as you can get clever with it to build hierarchies of configurations, e.g. for www.foo.com,
* try to load *com.config.php*
* try to load *foo.com.config.php*
* try to load *www.foo.com.config.php*
Doing it this way lets you set options for all your live sites globally, and tweak individual sites on as as-needed basis. We have our own internal root domain name for developer sandboxes too, so we can enable all the developer level options in internal.config.php
You can also do this in reverse, i.e. try to load www.foo.com.config.php, and only if not found would you try to load foo.com.config.php, and so on. More efficient, but a little less flexible.
|
What is the best way to determine which server the script is on and therefore the configuration in PHP?
|
[
"",
"php",
"configuration",
""
] |
I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (`Alt` + `Down`) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so...
How do I raise the event from an external function via reflection?
|
Here's a demo using generics (error checks omitted):
```
using System;
using System.Reflection;
static class Program {
private class Sub {
public event EventHandler<EventArgs> SomethingHappening;
}
internal static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs
{
var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);
if (eventDelegate != null)
{
foreach (var handler in eventDelegate.GetInvocationList())
{
handler.Method.Invoke(handler.Target, new object[] { source, eventArgs });
}
}
}
public static void Main()
{
var p = new Sub();
p.Raise("SomethingHappening", EventArgs.Empty);
p.SomethingHappening += (o, e) => Console.WriteLine("Foo!");
p.Raise("SomethingHappening", EventArgs.Empty);
p.SomethingHappening += (o, e) => Console.WriteLine("Bar!");
p.Raise("SomethingHappening", EventArgs.Empty);
Console.ReadLine();
}
}
```
|
In general, you can't. Think of events as basically pairs of `AddHandler`/`RemoveHandler` methods (as that's basically what what they are). How they're implemented is up to the class. Most WinForms controls use [`EventHandlerList`](http://msdn.microsoft.com/en-us/library/system.componentmodel.eventhandlerlist.aspx) as their implementation, but your code will be very brittle if it starts fetching private fields and keys.
Does the `ButtonEdit` control expose an `OnClick` method which you could call?
Footnote: Actually, events *can* have "raise" members, hence `EventInfo.GetRaiseMethod`. However, this is never populated by C# and I don't believe it's in the framework in general, either.
|
How do I raise an event via reflection in .NET/C#?
|
[
"",
"c#",
".net",
"event-handling",
"devexpress",
""
] |
I want to read all items of a feed in C#. The solutions I've found are only for the latest items like just the last 10 days.
Anybody has a good solution for this?
|
If you can tie into something like Google Reader, which archives old feed items (although I'm not sure it's a permanent archive or not), then perhaps you can accomplish this.
|
Libraries for reading feeds typically read all the data in the feed, but feeds typically only contain recent data - you need a source of data that includes older items, not a better library for reading the data you have.
Most entities publish feeds to allow people to track when new content is published, not to make all their data available in a more convenient machine readable format. For this purpose, publishing recent data only makes sense as it saves on bandwidth.
|
How do I read all feed items?
|
[
"",
"c#",
""
] |
The following code executes a simple insert command. If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown. Is there something else I should be doing to free up resources?
```
using (OleDbConnection conn = new OleDbConnection(connectionString))
using (OleDbCommand cmd = new OleDbCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
```
|
The system resources exceeded error is not coming from the managed code, its coming from you killing your database (JET?)
You are opening way too many connections, way too fast...
Some tips:
* Avoid round trips by not opening a new connection for every single command, and perform the inserts using a single connection.
* Ensure that database connection pooling is working. (Not sure if that works with OLEDB connections.)
* Consider using a more optimized way to insert the data.
Have you tried this?
```
using (OleDbConnection conn = new OleDbConnection(connstr))
{
while (IHaveData)
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.ExecuteScalar();
}
}
}
```
|
I tested this code out with an Access 2007 database with no exceptions (I went as high as 13000 inserts).
However, what I noticed is that it is terribly slow as you are creating a connection every time. If you put the "using(connection)" outside the loop, it goes much faster.
|
OleDbException System Resources Exceeded
|
[
"",
"c#",
"oledbexception",
""
] |
Does anyone know of crossbrowser equivalent of explicitOriginalTarget event parameter? This parameter is Mozilla specific and it gives me the element that caused the blur. Let's say i have a text input and a link on my page. Text input has the focus. If I click on the link, text input's blur event gives me the link element in Firefox via explicitOriginalTarget parameter.
I am extending Autocompleter.Base's onBlur method to not hide the search results when search field loses focus to given elements. By default, onBlur method hides if search-field loses focus to any element.
```
Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap(
function(origfunc, ev) {
var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode: ev.explicitOriginalTarget); // FIX: This works only in firefox because of event's explicitOriginalTarget property
var callOriginalFunction = true;
for (i = 0; i < obj.options.validEventElements.length; i++) {
if ($(obj.options.validEventElements[i])) {
if (newTargetElement.descendantOf($(obj.options.validEventElements[i])) == true || newTargetElement == $(obj.options.validEventElements[i])) {
callOriginalFunction = false;
break;
}
}
}
if (callOriginalFunction) {
return origFunc(ev);
}
}
);
new Ajax.Autocompleter("search-field", "search-results", 'getresults.php', { validEventElements: ['search-field','result-count'] });
```
Thanks.
|
There is no equivalent to explicitOriginalTarget in any of the other than Gecko-based browsers. In Gecko this is an internal property and it is not supposed to be used by an application developer (maybe by XBL binding writers).
|
The rough equivalent for Mozilla's .explicitOriginalTarget in IE is document.activeElement. I say rough equivalent because it will sometimes return a slightly different level in the DOM node tree depending on your circumstance, but it's still a useful tool. Unfortunately I'm still looking for a Google Chrome equivalent.
|
Crossbrowser equivalent of explicitOriginalTarget event parameter
|
[
"",
"javascript",
"events",
"cross-browser",
"scriptaculous",
""
] |
I have multiple layers in an application and i find myself having to bubble up events to the GUI layer for doing status bar changes, etc . . I find myself having to write repeated coded where each layer simply subscribes to events from the lower layer and then in the call back simply raise an event up the chain. Is there a more efficient way of doing this?
|
If all you're doing is firing an event handler from another event handler, you can cut out the middle man and hook the event handlers directly in the add/remove blocks for the event.
For example, if you have a UserControl with a "SaveButtonClick" event, and all you want to do when is call the event handler when the "SaveButton" on your UserControl is clicked, you can do this:
```
public event EventHandler SaveButtonClick
{
add { this.SaveButton.Click += value; }
remove { this.SaveButton.Click -= value; }
}
```
Now you don't need any code to fire the SaveButtonClick event - it will automatically be fired when the SaveButton.Click event is raised (ie when someone clicks that button).
|
Have a read of Jeremy Miller's blog "The Shade Tree Developer", especially his [*Write Your Own CAB* series](http://codebetter.com/jeremymiller/2007/07/26/the-build-your-own-cab-series-table-of-contents/) - the command pattern stuff he talks about there is probably what you need.
|
Bubbling up events .
|
[
"",
"c#",
"winforms",
"events",
""
] |
Basically, I'm trying to selectively copy a table from one database to another. I have two different [Oracle] databases (e.g., running on different hosts) with the same schema. I'm interested in a efficient way to load Table A in DB1 with the result of running a select on Table A in DB2. I'm using JDBC, if that's relevant.
|
Use a database link, and use create table as select.
```
create database link other_db connect to remote_user identified by remote_passwd using remote_tnsname;
create table a as select * from a@other_db;
```
|
If the databases are from the same vendor they usually provide a native way to make a view
of a table in another database. in which case, a "select into" query will do it no problem
Oracle, for example, has the database link which works pretty well.
Outside of that you are going to have to make a connection to each database and read in
from one connection and write out to the other.
There are tools like Oracle's ODI that can do the legwork, but they all use the same
read in, write out model
|
Bulk Row Transfer between Oracle Databases with a Select Filter
|
[
"",
"java",
"database",
"oracle",
"html-select",
""
] |
Here are the requirements:
Must be alphanumeric, 8-10 characters so that it is user friendly. These will be stored as unique keys in database. I am using Guids as primary keys so an option to use GUids to generate these unique Ids would be preferable.
I am thinking on the lines of a base-n converter that takes a Guid and converts to an 8 character unique string.
Short, light-weight algorithm preferred as it would be called quite often.
|
You might consider [base 36.](http://en.wikipedia.org/wiki/Base_36) in that it can do letters and numbers.
Consider removing I (eye) and O (Oh) from your set so they don't get mixed up with 1 (one) and 0 (zero). Some people might complain about 2 and Z as well.
|
```
8 characters - perfectly random - 36^8 = 2,821,109,907,456 combinations
10 characters - perfectly random - 36^10 = 3,656,158,440,062,976 combinations
GUID's - statistically unique* - 2^128 = 340,000,000,000,000,000,000,000,000,000,000,000,000 combinations
```
\* [Is a GUID unique 100% of the time? [stackoverflow]](https://stackoverflow.com/questions/39771/is-a-guid-unique-100-of-the-time)
The problem with your GUID -> character conversion; while your GUID is statistically unique, by taking any subset you decrease randomness and increase the chance of collisions. You certainly don't want to create non-unqiue SKU's.
---
Solution 1:
Create SKU using data relevant to the object and business rules.
i.e. There likely to be a small combination of attributes that makes an object unique [(a natural key)](http://en.wikipedia.org/wiki/Natural_key). Combine the elements of the natural key, encode and compress them to create a SKU. Often all you need is a date-time field (ie CreationDate) and a few other properties to achieve this. You're likely to have a lot of holes in sku creation, but sku's are more relevant to your users.
hypothetically:
```
Wholesaler, product name, product version, sku
Amazon, IPod Nano, 2.2, AMIPDNN22
BestBuy, Vaio, 3.2, BEVAIO32
```
---
Solution 2:
A method that reserves a range of numbers, and then proceeds to release them sequentially, and never returns the same number twice. You can still end up with holes in the range. Likely though you don't need to generate enough sku's to matter, but ensure your requirements allow for this.
An implementation is to have a `key` table in a database that has a counter. The counter is incremented in a transaction. An important point is that rather than incrementing by 1, the method in software grabs a block. pseudo-c#-code is as follows.
```
-- what the key table may look like
CREATE TABLE Keys(Name VARCHAR(10) primary key, NextID INT)
INSERT INTO Keys Values('sku',1)
// some elements of the class
public static SkuKeyGenerator
{
private static syncObject = new object();
private static int nextID = 0;
private static int maxID = 0;
private const int amountToReserve = 100;
public static int NextKey()
{
lock( syncObject )
{
if( nextID == maxID )
{
ReserveIds();
}
return nextID++;
}
}
private static void ReserveIds()
{
// pseudocode - in reality I'd do this with a stored procedure inside a transaction,
// We reserve some predefined number of keys from Keys where Name = 'sku'
// need to run the select and update in the same transaction because this isn't the only
// method that can use this table.
using( Transaction trans = new Transaction() ) // pseudocode.
{
int currentTableValue = db.Execute(trans, "SELECT NextID FROM Keys WHERE Name = 'sku'");
int newMaxID = currentTableValue + amountToReserve;
db.Execute(trans, "UPDATE Keys SET NextID = @1 WHERE Name = 'sku'", newMaxID);
trans.Commit();
nextID = currentTableValue;
maxID = newMaxID;
}
}
```
The idea here is that you reserve enough keys so that your code doesn't go the the database often, as getting the key range is an expensive operation. You need to have a good idea of the number of keys you need to reserve to balance key loss (application restart) versus exhausting keys too quickly and going back to the database. This simple implementation has no way to reuse lost keys.
Because this implementation relies a database and transactions you can have applications running concurrently and all generate unique keys without needing to go to the database often.
Note the above is loosely based on `key table`, page 222 from [Patterns of Enterprise Application Architecture (Fowler)](http://martinfowler.com/books.html#eaa). The method is usually used to generate primary keys without the need of a database identity column, but you can see how it can be adapted for your purpose.
|
What are the options for generating user friendly alpha numeric IDs (like business id, SKU)
|
[
"",
"c#",
".net",
"algorithm",
"guid",
""
] |
I want to sort members by name in the source code. Is there any easy way to do it?
I'm using NetBeans, but if there is another editor that can do that, just tell me the name of it.
|
In Netbeans 8.0.1:
```
Tools -> Options -> Editor -> Formatting -> Category: Ordering
```

Then:
```
Source -> Organize Members
```

|
Eclipse can do it.
|
How can I sort class members by name in NetBeans, or another Java IDE?
|
[
"",
"java",
"sorting",
"netbeans",
"methods",
""
] |
Let's say that you have overridden an object's equals() and hashCode() methods, so that they use the object's fields.
How you do you check if two references are to the same object, ala the stock equals() method?
|
Use `==` on objects to perform identity comparison.
That is what the default implementation of `equals()` does, but one normally overrides `equals()` to serve as an "equivalent content" check.
|
That's what the == operator does.
|
Comparing references in Java
|
[
"",
"java",
""
] |
Often, programmers write code that generates other code.
(The technical term is [metaprogramming](http://en.wikipedia.org/wiki/Metaprogramming "Wikipedia article on metaprogramming"), but it is more common than merely cross-compilers; think about every PHP web-page that generates HTML or every XSLT file.)
One area I find challenging is coming up with techniques to ensure that *both* the hand-written source file, and the computer-generated object file are clearly indented to aid debugging. The two goals often seem to be competing.
I find this particularly challenging in the PHP/HTML combination. I think that is because:
* there is sometimes more of the HTML code in the source file than the generating PHP
* HTML files tend to be longer than, say, SQL statements, and need better indenting
* HTML has space-sensitive features (e.g. between tags)
* the result is more publicly visible HTML than SQL statements, so there is more pressure to do a reasonable job.
What techniques do you use to address this?
---
Edit: I accept that there are at least three arguments to not bothering to generate pretty HTML code:
* Complexity of generating code is increased.
* Makes no difference to rendering by browser; developers can use Firebug or similar to view it nicely.
* Minor performance hit - increased download time for whitespace characters.
I have certainly sometimes generated code without thought to the indenting (especially SQL).
However, there are a few arguments pushing the other way:
* I find, in practice, that I *do* frequently read generated code - having extra steps to access it is inconvenient.
* HTML has some space-sensitivity issues that bite occasionally.
For example, consider the code:
```
<div class="foo">
<?php
$fooHeader();
$fooBody();
$fooFooter();
?>
</div>
```
It is clearer than the following code:
```
<div class="foo"><?php
$fooHeader();
$fooBody();
$fooFooter();
?></div>
```
However, it is also has different rendering because of the whitespace included in the HTML.
|
In the more general case, I have written XSLT code that generates C++ database interface code. Although at first I tried to output correctly indented code from the XSLT, this quickly became untenable. My solution was to completely ignore formatting in the XSLT output, and then run the resulting very long line of code through [GNU indent](http://www.gnu.org/software/indent/). This produced a reasonably formatted C++ source file suitable for debugging.
I can imagine the problem gets a lot more prickly when dealing with combined source such as HTML and PHP.
|
A technique that I use when the generating code dominates over the generated code is to pass an indent parameter around.
e.g., in Python, generating more Python.
```
def generateWhileLoop(condition, block, indentPrefix = ""):
print indentPrefix + "while " + condition + ":"
generateBlock(block, indentPrefix + " ")
```
Alternatively, depending on my mood:
```
def generateWhileLoop(condition, block, indentLevel = 0):
print " " * (indentLevel * spacesPerIndent) + "while " + condition + ":"
generateBlock(block, indentLevel + 1)
```
Note the assumption that `condition` is a short piece of text that fits on the same line, while `block` is on a separate indented line. If this code can't be sure of whether the sub-items need to be indented, this method starts to fall down.
Also, this technique isn't nearly as useful for sprinkling relatively small amounts of PHP into HTML.
[Edit to clarify: I wrote the question and also this answer. I wanted to seed the answers with one technique that I do use and is sometimes useful, but this technique fails me for typical PHP coding, so I am looking for other ideas like it.]
|
Indenting for code-generation
|
[
"",
"php",
"code-generation",
"metaprogramming",
""
] |
If the C++ runtime msvcr80.dll is missing from a compiled library, is there any way to determine which version was used to create the library or to get it to run on a later version of msvcr80.dll?
|
The VC80 SP1 CRT redistributable package will install both the RTM and SP1 versions of the C runtime into `%SystemRoot%\WinSxS` (assuming you're using Windows XP or Vista; Windows 2000 doesn't support side-by-side assemblies). If you have VC8 installed, the CRT redistributable package is in `%ProgramFiles%\Microsoft Visual Studio 8\VC\redist`. If you don't have VC8 installed, I think you can download the CRT redistributable package from Microsoft.com.
Also, to find out exactly what CRT version (e.g. RTM vs. SP1) is needed by a binary that was built with VC8 or VC9, you can extract the manifest:
```
mt.exe -inputresource:mydll.dll;#1 -out:mydll.dll.manifest
```
Look for something like this:
```
<assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b">
</assemblyIdentity>
```
My executable requires CRT version 9.0.21022.8. This version number is also embedded in the `WinSxS` subdirectory names (unfortunately it's surrounded by hashes):
```
D:>dir c:\windows\WinSxS\*VC90.CRT*
12/14/2007 02:16 AM <DIR> amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_750b37ff97f4f68b
12/14/2007 02:00 AM <DIR> x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91
```
|
[Dependency Walker](http://www.dependencywalker.com/) will help you answer this question.
|
Missing msvcr80.dll
|
[
"",
"c++",
"windows",
"dll",
"dependencies",
""
] |
Is there any libraries that would allow me to use the same known notation as we use in BeanUtils for extracting POJO parameters, but for easily replacing placeholders in a string?
I know it would be possible to roll my own, using BeanUtils itself or other libraries with similar features, but I didn't want to reinvent the wheel.
I would like to take a String as follows:
```
String s = "User ${user.name} just placed an order. Deliver is to be
made to ${user.address.street}, ${user.address.number} - ${user.address.city} /
${user.address.state}";
```
And passing one instance of the User class below:
```
public class User {
private String name;
private Address address;
// (...)
public String getName() { return name; }
public Address getAddress() { return address; }
}
public class Address {
private String street;
private int number;
private String city;
private String state;
public String getStreet() { return street; }
public int getNumber() { return number; }
// other getters...
}
```
To something like:
```
System.out.println(BeanUtilsReplacer.replaceString(s, user));
```
Would get each placeholder replaced with actual values.
Any ideas?
|
Rolling your own using BeanUtils wouldn't take too much wheel reinvention (assuming you want it to be as basic as asked for). This implementation takes a Map for replacement context, where the map key should correspond to the first portion of the variable lookup paths given for replacement.
```
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsReplacer
{
private static Pattern lookupPattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
public static String replaceString(String input, Map<String, Object> context)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
int position = 0;
StringBuffer result = new StringBuffer();
Matcher m = lookupPattern.matcher(input);
while (m.find())
{
result.append(input.substring(position, m.start()));
result.append(BeanUtils.getNestedProperty(context, m.group(1)));
position = m.end();
}
if (position == 0)
{
return input;
}
else
{
result.append(input.substring(position));
return result.toString();
}
}
}
```
Given the variables provided in your question:
```
Map<String, Object> context = new HashMap<String, Object>();
context.put("user", user);
System.out.println(BeanUtilsReplacer.replaceString(s, context));
```
|
Spring Framework should have a feature that does this (see Spring JDBC example below). If you can use groovy (just add the groovy.jar file) you can use Groovy's GString feature to do this quite nicely.
Groovy example
```
foxtype = 'quick'
foxcolor = ['b', 'r', 'o', 'w', 'n']
println "The $foxtype ${foxcolor.join()} fox"
```
Spring JDBC has a feature that I use to support named and nested named bind variables from beans like this:
```
public int countOfActors(Actor exampleActor) {
// notice how the named parameters match the properties of the above 'Actor' class
String sql = "select count(0) from T_ACTOR where first_name = :firstName and last_name = :lastName";
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);
return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
}
```
|
Simplest way to use "BeanUtils alike" replace
|
[
"",
"java",
"string",
"replace",
"placeholder",
""
] |
I am looking get to grips with functional programming concepts.
I've used Javascript for many years for client side scripting in web applications and apart from using prototypes it was all simple DOM manipulation, input validation etc.
Of late, I have [often read](http://eloquentjavascript.net/chapter6.html) that Javascript is one of the languages that supports functional programming.
With my familiarity and experience with Javascript, my preference is to use it to learn functional programming. I expect I would be able to concentrate more on the main functional concepts and not get bogged down or distracted by a completely new syntax.
So in summary, is Javascript a good choice to learn functional programming concepts? What capabilities in Javascript are relevant/support functional programming?
|
JavaScript supports first class functions. See *[Use functional programming techniques to write elegant JavaScript](http://www.ibm.com/developerworks/library/wa-javascript.html)*.
|
[Higher Order Javascript](http://interglacial.com/hoj/hoj.html) is a *great* way to get familiar with the functional aspects of javascript. It's also a relatively short read in case you want to get your feet wet without diving into a larger book.
|
Javascript as a functional language
|
[
"",
"javascript",
"functional-programming",
"language-features",
""
] |
What is the PHP preg\_replace in C#?
I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").
```
$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';
$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);
```
|
```
public static class StringManipulation
{
public static string PregReplace(string input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (int i = 0; i < pattern.Length; i++)
{
input = Regex.Replace(input, pattern[i], replacements[i]);
}
return input;
}
}
```
Here is what I will use. Some code of Jonathan Holland but not in C#3.5 but in C#2.0 :)
Thx all.
|
Real men use regular expressions, but here is an extension method that adds it to String if you wanted it:
```
public static class ExtensionMethods
{
public static String PregReplace(this String input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (var i = 0; i < pattern.Length; i++)
{
input = Regex.Replace(input, pattern[i], replacements[i]);
}
return input;
}
}
```
You use it like this:
```
class Program
{
static void Main(string[] args)
{
String[] pattern = new String[4];
String[] replacement = new String[4];
pattern[0] = "Quick";
pattern[1] = "Fox";
pattern[2] = "Jumped";
pattern[3] = "Lazy";
replacement[0] = "Slow";
replacement[1] = "Turtle";
replacement[2] = "Crawled";
replacement[3] = "Dead";
String DemoText = "The Quick Brown Fox Jumped Over the Lazy Dog";
Console.WriteLine(DemoText.PregReplace(pattern, replacement));
}
}
```
|
C# preg_replace?
|
[
"",
"c#",
".net",
".net-2.0",
"preg-replace",
""
] |
Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:
```
class A {
public:
A(const B& b): mB(b) { };
private:
B mB;
};
```
Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?
|
Have a read of <http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/>)
Edit: After more digging, these are called "Function try blocks".
I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :)
To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be:
```
C::C()
try : init1(), ..., initn()
{
// Constructor
}
catch(...)
{
// Handle exception
}
```
|
It's not particularly pretty:
```
A::A(const B& b) try : mB(b)
{
// constructor stuff
}
catch (/* exception type */)
{
// handle the exception
}
```
|
Catching exceptions from a constructor's initializer list
|
[
"",
"c++",
"exception",
""
] |
If I have two variables:
```
Object obj;
String methodName = "getName";
```
Without knowing the class of `obj`, how can I call the method identified by `methodName` on it?
The method being called has no parameters, and a `String` return value. It's *a getter for a Java bean*.
|
Coding from the hip, it would be something like:
```
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
catch (NoSuchMethodException e) { ... }
```
The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give `methodName`).
Then you invoke that method by calling
```
try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { ... }
catch (IllegalAccessException e) { ... }
catch (InvocationTargetException e) { ... }
```
Again, leave out the arguments in `.invoke`, if you don't have any. But yeah. Read about [Java Reflection](http://java.sun.com/docs/books/tutorial/reflect/index.html)
|
Use [method invocation](http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html) from reflection:
```
Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", parameterTypes);
method.invoke(objectToInvokeOn, params);
```
Where:
* `"class name"` is the name of the class
* `objectToInvokeOn` is of type Object and is the object you want to invoke the method on
* `"method name"` is the name of the method you want to call
* `parameterTypes` is of type `Class[]` and declares the parameters the method takes
* `params` is of type `Object[]` and declares the parameters to be passed to the method
|
How do I invoke a Java method when given the method name as a string?
|
[
"",
"java",
"reflection",
"invoke",
""
] |
I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java `String` flavor and pasted it into Java code, it does not work. The following class prints `false`:
```
public class RegexFoo {
public static void main(String[] args) {
String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";
String text = "http://google.com";
System.out.println(IsMatch(text,regex));
}
private static boolean IsMatch(String s, String pattern) {
try {
Pattern patt = Pattern.compile(pattern);
Matcher matcher = patt.matcher(s);
return matcher.matches();
} catch (RuntimeException e) {
return false;
}
}
}
```
Does anyone know what I am doing wrong?
|
Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.
```
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
```
This works too:
```
String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
```
Note:
```
String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>
String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
```
|
The best way to do it now is:
```
android.util.Patterns.WEB_URL.matcher(linkUrl).matches();
```
EDIT: Code of `Patterns` from <https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Patterns.java> :
```
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Commonly used regular expression patterns.
*/
public class Patterns {
/**
* Regular expression to match all IANA top-level domains.
* List accurate as of 2011/07/18. List taken from:
* http://data.iana.org/TLD/tlds-alpha-by-domain.txt
* This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
*
* @deprecated Due to the recent profileration of gTLDs, this API is
* expected to become out-of-date very quickly. Therefore it is now
* deprecated.
*/
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR =
"((aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
+ "|(biz|b[abdefghijmnorstvwyz])"
+ "|(cat|com|coop|c[acdfghiklmnoruvxyz])"
+ "|d[ejkmoz]"
+ "|(edu|e[cegrstu])"
+ "|f[ijkmor]"
+ "|(gov|g[abdefghilmnpqrstuwy])"
+ "|h[kmnrtu]"
+ "|(info|int|i[delmnoqrst])"
+ "|(jobs|j[emop])"
+ "|k[eghimnprwyz]"
+ "|l[abcikrstuvy]"
+ "|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
+ "|(name|net|n[acefgilopruz])"
+ "|(org|om)"
+ "|(pro|p[aefghklmnrstwy])"
+ "|qa"
+ "|r[eosuw]"
+ "|s[abcdeghijklmnortuvyz]"
+ "|(tel|travel|t[cdfghjklmnoprtvwz])"
+ "|u[agksyz]"
+ "|v[aceginu]"
+ "|w[fs]"
+ "|(\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
+ "|y[et]"
+ "|z[amw])";
/**
* Regular expression pattern to match all IANA top-level domains.
* @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.
*/
@Deprecated
public static final Pattern TOP_LEVEL_DOMAIN =
Pattern.compile(TOP_LEVEL_DOMAIN_STR);
/**
* Regular expression to match all IANA top-level domains for WEB_URL.
* List accurate as of 2011/07/18. List taken from:
* http://data.iana.org/TLD/tlds-alpha-by-domain.txt
* This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
*
* @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.
*/
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL =
"(?:"
+ "(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
+ "|(?:biz|b[abdefghijmnorstvwyz])"
+ "|(?:cat|com|coop|c[acdfghiklmnoruvxyz])"
+ "|d[ejkmoz]"
+ "|(?:edu|e[cegrstu])"
+ "|f[ijkmor]"
+ "|(?:gov|g[abdefghilmnpqrstuwy])"
+ "|h[kmnrtu]"
+ "|(?:info|int|i[delmnoqrst])"
+ "|(?:jobs|j[emop])"
+ "|k[eghimnprwyz]"
+ "|l[abcikrstuvy]"
+ "|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
+ "|(?:name|net|n[acefgilopruz])"
+ "|(?:org|om)"
+ "|(?:pro|p[aefghklmnrstwy])"
+ "|qa"
+ "|r[eosuw]"
+ "|s[abcdeghijklmnortuvyz]"
+ "|(?:tel|travel|t[cdfghjklmnoprtvwz])"
+ "|u[agksyz]"
+ "|v[aceginu]"
+ "|w[fs]"
+ "|(?:\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
+ "|y[et]"
+ "|z[amw]))";
/**
* Good characters for Internationalized Resource Identifiers (IRI).
* This comprises most common used Unicode characters allowed in IRI
* as detailed in RFC 3987.
* Specifically, those two byte Unicode characters are not included.
*/
public static final String GOOD_IRI_CHAR =
"a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
public static final Pattern IP_ADDRESS
= Pattern.compile(
"((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
+ "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
+ "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
+ "|[1-9][0-9]|[0-9]))");
/**
* RFC 1035 Section 2.3.4 limits the labels to a maximum 63 octets.
*/
private static final String IRI
= "[" + GOOD_IRI_CHAR + "]([" + GOOD_IRI_CHAR + "\\-]{0,61}[" + GOOD_IRI_CHAR + "]){0,1}";
private static final String GOOD_GTLD_CHAR =
"a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
private static final String GTLD = "[" + GOOD_GTLD_CHAR + "]{2,63}";
private static final String HOST_NAME = "(" + IRI + "\\.)+" + GTLD;
public static final Pattern DOMAIN_NAME
= Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")");
/**
* Regular expression pattern to match most part of RFC 3987
* Internationalized URLs, aka IRIs. Commonly used Unicode characters are
* added.
*/
public static final Pattern WEB_URL = Pattern.compile(
"((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
+ "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
+ "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
+ "(?:" + DOMAIN_NAME + ")"
+ "(?:\\:\\d{1,5})?)" // plus option port number
+ "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~" // plus option query params
+ "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
+ "(?:\\b|$)"); // and finally, a word boundary or end of
// input. This is to stop foo.sure from
// matching as foo.su
public static final Pattern EMAIL_ADDRESS
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
/**
* This pattern is intended for searching for things that look like they
* might be phone numbers in arbitrary text, not for validating whether
* something is in fact a phone number. It will miss many things that
* are legitimate phone numbers.
*
* <p> The pattern matches the following:
* <ul>
* <li>Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes
* may follow.
* <li>Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.
* <li>A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.
* </ul>
*/
public static final Pattern PHONE
= Pattern.compile( // sdd = space, dot, or dash
"(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
+ "(\\([0-9]+\\)[\\- \\.]*)?" // (<digits>)<sdd>*
+ "([0-9][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
/**
* Convenience method to take all of the non-null matching groups in a
* regex Matcher and return them as a concatenated string.
*
* @param matcher The Matcher object from which grouped text will
* be extracted
*
* @return A String comprising all of the non-null matched
* groups concatenated together
*/
public static final String concatGroups(Matcher matcher) {
StringBuilder b = new StringBuilder();
final int numGroups = matcher.groupCount();
for (int i = 1; i <= numGroups; i++) {
String s = matcher.group(i);
if (s != null) {
b.append(s);
}
}
return b.toString();
}
/**
* Convenience method to return only the digits and plus signs
* in the matching string.
*
* @param matcher The Matcher object from which digits and plus will
* be extracted
*
* @return A String comprising all of the digits and plus in
* the match
*/
public static final String digitsAndPlusOnly(Matcher matcher) {
StringBuilder buffer = new StringBuilder();
String matchingRegion = matcher.group();
for (int i = 0, size = matchingRegion.length(); i < size; i++) {
char character = matchingRegion.charAt(i);
if (character == '+' || Character.isDigit(character)) {
buffer.append(character);
}
}
return buffer.toString();
}
/**
* Do not create this static utility class.
*/
private Patterns() {}
}
```
|
Regular expression to match URLs in Java
|
[
"",
"java",
"regex",
"regexbuddy",
""
] |
I am using pseudo-code here, but this is in JavaScript. With the most efficient algorithm possible I am trying to find the high and low given an array of positive whole numbers. This is what I came up with, but I don't think it is probably best, and was just wondering if anyone has any other suggestions.
```
var low = 1;
var high = 1;
for ( loop numbers ) {
if ( number > high ) {
high = number;
}
if ( low == 1 ) {
low = high;
}
if ( number < low ) {
low = number;
}
}
```
|
initialise the high and low to be the first element. makes a lot more sense than picking an arbitrarily "high" or "low" number.
```
var myArray = [...],
low = myArray[0],
high = myArray[0]
;
// start looping at index 1
for (var i = 1, l = myArray.length; i < l; ++i) {
if (myArray[i] > high) {
high = myArray[i];
} else if (myArray[i] < low) {
low = myArray[i];
}
}
```
or, avoiding the need to lookup the array multiple times:
```
for (var i = 1, val; (val = myArray[i]) !== undefined; ++i) {
if (val > high) {
high = val;
} else if (val < low) {
low = val;
}
}
```
|
You have to do it in `O(n)` time because you need to loop through all (`n`) of the elements to check them because any one of the elements may be the min or max. (Unless they are already sorted.)
In other words you need to loop through all elements and do the max and min check like you have.
Sorting is usually at best `O(n*log(n))`. Thus it is slower than a single sweep through (`O(n)`).
|
Best algorithm for determining the high and low in an array of numbers?
|
[
"",
"javascript",
"algorithm",
""
] |
Basically I have the following class:
```
class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};
```
The methods stateA() and stateB() should be able return pointers to stateA() and stateB().
How to typedef the StateMethod?
|
[GotW #57](http://www.gotw.ca/gotw/057.htm) says to use a proxy class with an implicit conversion for this very purpose.
```
struct StateMethod;
typedef StateMethod (StateMachine:: *FuncPtr)();
struct StateMethod
{
StateMethod( FuncPtr pp ) : p( pp ) { }
operator FuncPtr() { return p; }
FuncPtr p;
};
class StateMachine {
StateMethod stateA();
StateMethod stateB();
};
int main()
{
StateMachine *fsm = new StateMachine();
FuncPtr a = fsm->stateA(); // natural usage syntax
return 0;
}
StateMethod StateMachine::stateA
{
return stateA; // natural return syntax
}
StateMethod StateMachine::stateB
{
return stateB;
}
```
> This solution has three main
> strengths:
>
> 1. It solves the problem as required. Better still, it's type-safe and
> portable.
> 2. Its machinery is transparent: You get natural syntax for the
> caller/user, and natural syntax for
> the function's own "return stateA;"
> statement.
> 3. It probably has zero overhead: On modern compilers, the proxy class,
> with its storage and functions, should
> inline and optimize away to nothing.
|
Using just typedef:
```
class StateMachine {
public:
class StateMethod;
typedef StateMethod (StateMachine::*statemethod)();
class StateMethod {
statemethod method;
StateMachine& obj;
public:
StateMethod(statemethod method_, StateMachine *obj_)
: method(method_), obj(*obj_) {}
StateMethod operator()() { return (obj.*(method))(); }
};
StateMethod stateA() { return StateMethod(&StateMachine::stateA, this); }
StateMethod stateB() { return StateMethod(&StateMachine::stateB, this); }
};
```
|
How to typedef a pointer to method which returns a pointer the method?
|
[
"",
"c++",
"pointer-to-member",
""
] |
Let's say that for some reason you need to write a macro: `MACRO(X,Y)`. **(Let's assume there's a good reason you can't use an inline function.)** You want this macro to emulate a call to a function with no return value.
---
### Example 1: This should work as expected.
```
if (x > y)
MACRO(x, y);
do_something();
```
### Example 2: This should not result in a compiler error.
```
if (x > y)
MACRO(x, y);
else
MACRO(y - x, x - y);
```
### Example 3: This should *not* compile.
```
do_something();
MACRO(x, y)
do_something();
```
---
The naïve way to write the macro is like this:
```
#define MACRO(X,Y) \
cout << "1st arg is:" << (X) << endl; \
cout << "2nd arg is:" << (Y) << endl; \
cout << "Sum is:" << ((X)+(Y)) << endl;
```
This is a very bad solution which fails all three examples, and I shouldn't need to explain why.
**Ignore what the macro actually does, that's not the point.**
---
Now, the way I most often see macros written is to enclose them in curly braces, like this:
```
#define MACRO(X,Y) \
{ \
cout << "1st arg is:" << (X) << endl; \
cout << "2nd arg is:" << (Y) << endl; \
cout << "Sum is:" << ((X)+(Y)) << endl; \
}
```
This solves example 1, because the macro is in one statement block. But example 2 is broken because we put a semicolon after the call to the macro. This makes the compiler think the semicolon is a statement by itself, which means the else statement doesn't correspond to any if statement! And lastly, example 3 compiles OK, even though there is no semicolon, because a code block doesn't need a semicolon.
---
Is there a way to write a macro so that it pass all three examples?
---
*Note: I am submitting my own answer as part of the [accepted way of sharing a tip](https://stackoverflow.com/questions/162246/is-stack-overflow-appropriate-for-sharing-knowledge-tips-tricks-and-interesting), but if anyone has a better solution feel free to post it here, it may get more votes than my method. :)*
|
Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once.
If it must be a macro, a while loop (already suggested) will work, or you can try the comma operator:
```
#define MACRO(X,Y) \
( \
(cout << "1st arg is:" << (X) << endl), \
(cout << "2nd arg is:" << (Y) << endl), \
(cout << "3rd arg is:" << ((X) + (Y)) << endl), \
(void)0 \
)
```
The `(void)0` causes the statement to evaluate to one of `void` type, and the use of commas rather than semicolons allows it to be used inside a statement, rather than only as a standalone. I would still recommend an inline function for a host of reasons, the least of which being scope and the fact that `MACRO(a++, b++)` will increment `a` and `b` twice.
|
There is a rather clever solution:
```
#define MACRO(X,Y) \
do { \
cout << "1st arg is:" << (X) << endl; \
cout << "2nd arg is:" << (Y) << endl; \
cout << "Sum is:" << ((X)+(Y)) << endl; \
} while (0)
```
Now you have a single block-level statement, which must be followed by a semicolon. This behaves as expected and desired in all three examples.
|
How do I make a C++ macro behave like a function?
|
[
"",
"c++",
"c-preprocessor",
""
] |
I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.
So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.
This public [weather.com RSS feed](http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&cm_cat=rss&par=LWO_rss) is a good example of what we'd be parsing (*our actual weather.com feed contains additional information because of a partnership w/them*).
In a nutshell, how should we convert XML to JSON using Python?
|
There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to *do* with the results.
That being said, Python's standard library has [several modules for parsing XML](http://docs.python.org/2/library/xml.html) (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the [`json` module](http://docs.python.org/2/library/json.html).
So the infrastructure is there.
|
[xmltodict](https://github.com/martinblech/xmltodict) (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this ["standard"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html). It is [Expat](http://docs.python.org/library/pyexpat.html)-based, so it's very fast and doesn't need to load the whole XML tree in memory.
Once you have that data structure, you can serialize it to JSON:
```
import xmltodict, json
o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'
```
|
Converting XML to JSON using Python?
|
[
"",
"python",
"json",
"xml",
"converters",
""
] |
At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like:
```
class Header
{
int type;
int payloadLength;
};
```
All of the data was contiguous (header, immediately followed by data). We wanted to get to the payload given that we had a pointer to a header. Traditionally, you might say something like:
```
char* Header::GetPayload()
{
return ((char*) &payloadLength) + sizeof(payloadLength);
}
```
or even:
```
char* Header::GetPayload()
{
return ((char*) this) + sizeof(Header);
}
```
That seemed kind of verbose, so I came up with:
```
char* Header::GetPayload()
{
return (char*) &this[1];
}
```
It seems rather disturbing at first, possibly too odd to use -- but very compact.
There was a lot of debate on whether it was brilliant or an abomination.
So which is it - Crime against coding, or nice solution? Have you ever had a similar trade-off?
-Update:
We did try the zero sized array, but at the time, compilers gave warnings.
We eventually went to the inhertited technique: Message derives from Header.
It works great in practice, but in priciple you are saying a message IsA Header - which seems a little awkward.
|
I'd go for crime against coding.
Both methods will generate the exact same object code. The first makes it's intention clear. The second is very confusing, with the only advantage that it saves a couple keystrokes. (Just learn to freakin' type).
Also, note that NEITHER method is guaranteed to work. The sizeof() an object includes padding for word alignment, so that if the header was:
```
class Header
{
int type;
int payloadLength;
char status;
};
```
Both methods you describe would have the payload starting at Header+12, when most likely it actually starts at Header+9.
|
Personally I think that if there's a crime, it's asking the header for the payload.
But as long as you're going to do it that way, 'this+1' is as good a way as any.
Justification: '&this[1]' is a general-purpose piece of code that doesn't require you to go digging through class-definitions to fully comprehend, and doesn't require fixing when someone changes the name or contents of the class.
BTW, the first example is the true crime against humanity. Add a member to the end of the class and it'll fail. Move the members around the class and it'll fail. If the compiler pads the class, it'll fail.
Also, if you're going to assume that the compiler's layout of classes/structs matches your packet layout, then you should understand how the compiler in question works. Eg. on MSVC you'll probably want to know about `#pragma pack`.
PS: It's a little scary how many people consider "this+1" or "&this[1]" hard to read or understand.
|
C++ example of Coding Horror or Brilliant Idea?
|
[
"",
"c++",
"optimization",
"syntax",
""
] |
Something that has always bugged me is how unpredictable the `setTimeout()` method in Javascript is.
In my experience, the timer is horribly inaccurate in a lot of situations. By inaccurate, I mean the actual delay time seems to vary by 250-500ms more or less. Although this isn't a huge amount of time, when using it to hide/show UI elements the time can be visibly noticeable.
Are there any tricks that can be done to ensure that `setTimeout()` performs accurately (without resorting to an external API) or is this a lost cause?
|
> Are there any tricks that can be done
> to ensure that `setTimeout()` performs
> accurately (without resorting to an
> external API) or is this a lost cause?
No and no. You're not going to get anything close to a perfectly accurate timer with `setTimeout()` - browsers aren't set up for that. **However**, you don't need to rely on it for timing things either. Most animation libraries figured this out years ago: you set up a callback with `setTimeout()`, but determine what needs to be done based on the value of `(new Date()).milliseconds` (or equivalent). This allows you to take advantage of more reliable timer support in newer browsers, while still behaving appropriately on older browsers.
It also allows you to *avoid using too many timers*! This is important: each timer is a callback. Each callback executes JS code. While JS code is executing, browser events - including other callbacks - are delayed or dropped. When the callback finishes, additional callbacks must compete with other browser events for a chance to execute. Therefore, one timer that handles all pending tasks for that interval will perform better than two timers with coinciding intervals, and (for short timeouts) better than two timers with overlapping timeouts!
Summary: stop using `setTimeout()` to implement "one timer / one task" designs, and use the real-time clock to smooth out UI actions.
|
.
REF; <http://www.sitepoint.com/creating-accurate-timers-in-javascript/>
This site bailed me out on a major scale.
You can use the system clock to compensate for timer inaccuracy. If you run a timing function as a series of setTimeout calls — each instance calling the next — then all you have to do to keep it accurate is work out exactly how inaccurate it is, and subtract that difference from the next iteration:
```
var start = new Date().getTime(),
time = 0,
elapsed = '0.0';
function instance()
{
time += 100;
elapsed = Math.floor(time / 100) / 10;
if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }
document.title = elapsed;
var diff = (new Date().getTime() - start) - time;
window.setTimeout(instance, (100 - diff));
}
window.setTimeout(instance, 100);
```
This method will minimize drift and reduce the inaccuracies by more than 90%.
It fixed my issues, hope it helps
|
Is there a more accurate way to create a Javascript timer than setTimeout?
|
[
"",
"javascript",
"timer",
""
] |
I have a PHP script that initialises an image gallery. It loops through all images, checks if they are thumbnailed and watermarks them.
My shared hosting account only lets me have 30 seconds of execution per script, as set in the php.ini settings. I can't change that.
What can I do to get round this? Currently I refresh the page after every 5 images, this prevents the script timing out, but the browser recognises that the script won't complete and gives an error. That's ok, but it's not really user friendly.
Any suggestions?
|
three ideas:
1. you could offload this to a script that runs on the server (PHP CLI perhaps?) and have your current script check the progress (still running! check back later!).
2. if javascript is ok in your environment, perhaps you could make ajax calls to handle this as well. the first solution allows the user to keep wandering around the site though, not sure if that's an important consideration in your case.
3. you could get the PHP script to just do a certain batch (say 10 images at a time), then refresh the page with a progress report and go for 10 more, instead of an arbitrary time based refresh.
|
get a list of images and then loop through them
for example you get a total of 500 imgs you can take 5 at a time and after you're finished with them output a meta refresh tag that will reload the script in 2 seconds for example with the image number you're currently at as a parameter .
```
<meta http-equiv="refresh" content="2;url=script.php?start=5">
```
and in your script also check what $\_GET['start'] is and continue from there with next 5 images then output start=10 and so one... until you loop through all of them.
|
How can I split a PHP script that takes a long time to run into smaller chunks?
|
[
"",
"php",
""
] |
I work in an Oracle shop. There's a toolset that consists of roughly 1000 Oracle Forms (using the Forms builder from 6i, early 90's software) with Oracle 10g on the back end. It's serving roughly 500 unique people a month, with 200 concurrent connections at any given time during the work day.
Obviously this is something that needs to be addressed to get rid of the Forms runtime and move to a web based solution. The tools need to be accessed from Windows, Linux, various UNIX's, VMS and Solaris.
What options out there exist that would be feasible to migrate to? Not only does it need to be feasible for migration but the development will need to be done by 8 or so engineers who support the tool set (and many of which who would prefer to stay put and not modernize this tool set).
Oracle offers a few solutions that convert Oracle Forms into a crappy Java Applet (it's a very terrible temporary solution).
My solution of choice has been migrating to Ruby on Rails (which I'm a big proponent of Rails) but this will involve a learning curve (which we'll hit with any solution) for other developers. Also, the other difficulty in this is converting some very complex forms to HTML forms.
Has anyone tackled such a solution? Are there any packages offered by anyone outside of Oracle?
Any specific Java Web frameworks?
Would GWT, jQuery UI, ExtJS or any other JavaScript UI frameworks offer the rich user experience needed?
.NET is a consideration but a last resort (mostly because of license costs, there's no room in the budget in addition to what we're paying for Oracle licenses).
|
That's exactly what I am currently doing using...
[Oracle Application Express](http://apex.oracle.com/i/index.html)
The learning curve is much smaller than most web-based alternatives for Forms developers, as all the code is in PL/SQL (unless you start getting fancy with Javascript, which you can). Also, in the latest release of Application Express (3.2), there is a [tool to convert Forms applications to Apex](http://www.oracle.com/technology/obe/apex32/apex32frmmigr.htm).
It comes free with Oracle versions since 9.2.
|
I'll +1 for Oracle Application Express -- I think that there are some significant advantages in your situation.
1. Free licensing
2. It may bean attractive option to the current staff, if they are Oracle bigots like me.
3. It's 100% web, and in 11g doesn't even require a web tier.
|
Best solution for migration from Oracle Forms 6i to the web?
|
[
"",
"java",
"oracle",
"migration",
"oracleforms",
""
] |
I've been trying to figure out how to retrieve the text selected by the user in my webbrowser control and have had no luck after digging through msdn and other resources, So I was wondering if there is a way to actually do this. Maybe I simply missed something.
I appreciate any help or resources regarding this.
Thanks
|
You need to use the Document.DomDocument property of the WebBrowser control and cast this to the IHtmlDocument2 interface provided in the Microsoft.mshtml interop assembly. This gives you access to the full DOM as is available to Javascript actually running in IE.
To do this you first need to add a reference to your project to the Microsoft.mshtml assembly normally at "C:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll". There may be more than one, make sure you choose the reference with this path.
Then to get the current text selection, for example:
```
using mshtml;
...
IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject currentSelection= htmlDocument.selection;
if (currentSelection!=null)
{
IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;
if (range != null)
{
MessageBox.Show(range.text);
}
}
```
For more information on accessing the full DOM from a .NET application, see:
* [Walkthrough: Accessing the DHTML DOM from C#](http://msdn.microsoft.com/en-us/library/aa290341(VS.71).aspx)
* [IHTMLDocument2 Interface reference](http://msdn.microsoft.com/en-us/library/aa752574(VS.85).aspx)
|
Just in case anybody is interested in solution that doesn't require adding a reference to mshtml.dll:
```
private string GetSelectedText()
{
dynamic document = webBrowser.Document.DomDocument;
dynamic selection = document.selection;
dynamic text = selection.createRange().text;
return (string)text;
}
```
|
Retrieving Selected Text from Webbrowser control in .net(C#)
|
[
"",
"c#",
"winforms",
"webbrowser-control",
""
] |
What kind of collection I should use to convert NameValue collection to be bindable to GridView?
When doing directly it didn't work.
**Code in aspx.cs**
```
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = list;
resultGV.DataBind();
}
```
**Code in aspx**
```
<asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Key" />
<asp:BoundField DataField="Value" HeaderText="Value" />
</Columns>
</asp:GridView>
```
Any tip most welcome. Thanks. X.
|
Can you use Dictionary<string,string> instead of NameValueCollection. Since Dictionary<T,T> implements IEnumerable you could use LINQ as so:
```
resultGV.DataSource = from item in nvpDictionary
select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();
```
[EDIT] Actually you may be able to use Dictionary directly as:
```
resultGV.DataSource = nvpDictionary;
resultGV.DataBind();
```
If it doesn't map key/value the way you want you can always go back to LINQ. LINQ would also allow you to rename the fields to whatever you want.
[EDIT] If you can't change to use Dictionary<T,T>, make a copy of the NameValueCollection as a Dictionary in the method and bind to it.
```
private void BindList(NameValueCollection nvpList)
{
Dictionary<string,string> temp = new Dictionary<string,string>();
foreach (string key in nvpList)
{
temp.Add(key,nvpList[key]);
}
resultGV.DataSource = temp;
resultGV.DataBind();
}
```
If you do this a lot, you could write an extension method to convert to a Dictionary, and use it so.
```
public static class NameValueCollectionExtensions
{
public static Dictionary<string,string> ToDictionary( this NameValueCollection collection )
{
Dictionary<string,string> temp = new Dictionary<string,string>();
foreach (string key in collection)
{
temp.Add(key,collection[key]);
}
return temp;
}
}
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = nvpList.ToDictionary();
resultGV.DataBind();
}
```
|
It's a little tricky, because the [enumerator](http://msdn.microsoft.com/en-us/library/system.collections.specialized.nameobjectcollectionbase.getenumerator.aspx) returns only the Keys. But, you can get the Key value with Container.DataItem, and then look up into the NameValueCollection to get the value:
```
<asp:GridView id="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Key">
<ItemTemplate><%# Container.DataItem %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<%# ((NameValueCollection)gv.DataSource)[(string)Container.DataItem] %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
|
Bind NameValueCollection to GridView?
|
[
"",
"c#",
"asp.net",
"data-binding",
"namevaluecollection",
""
] |
I fill a collection one single time when my J2EE webapp starts.
Then, several thread may access it at same time but only to read it.
I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ?
|
Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance.
---
**Aside note:** Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable.
```
class Test {
public Test(final int a, final int b) {
this.a = a;
this.b = b;
}
public int a;
public int b;
}
public class Main {
public static void main(String[] args) throws Exception {
List<Test> values = new ArrayList<Test>(2);
values.add(new Test(1, 2));
values.add(new Test(3, 4));
List<Test> readOnly = Collections.unmodifiableList(values);
for (Test t : readOnly) {
t.a = 5;
}
for (Test t : values) {
System.out.println(t.a);
}
}
}
```
This outputs:
```
5
5
```
---
Important considerations from @WMR answser.
> It depends on if the threads that are
> reading your collection are started
> before or after you're filling it. If
> they're started before you fill it,
> you have no guarantees (without
> synchronizing), that these threads
> will ever see the updated values.
>
> The reason for this is the Java Memory
> Model, if you wanna know more read the
> section "Visibility" at this link:
> <http://gee.cs.oswego.edu/dl/cpj/jmm.html>
>
> And even if the threads are started
> after you fill your collection, you
> might have to synchronize because your
> collection implementation could change
> its internal state even on read
> operations (thanks [Michael
> Bar-Sinai](https://stackoverflow.com/questions/152342/in-java-do-i-need-to-declare-my-collection-synchronized-if-its-read-only#152425),
> I didn't know such collections
> existed).
>
> Another very interesting read on the
> topic of concurrency which covers
> topics like publishing of objects,
> visibility, etc. in much more detail
> is Brian Goetz's book [Java
> Concurrency in
> Practice](http://www.briangoetz.com/pubs.html).
|
It depends on if the threads that are reading your collection are started before or after you're filling it. If they're started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values.
The reason for this is the Java Memory Model, if you wanna know more read the section "Visibility" at this link: <http://gee.cs.oswego.edu/dl/cpj/jmm.html>
And even if the threads are started after you fill your collection, you might have to synchronize because your collection implementation could change its internal state even on read operations (thanks [Michael Bar-Sinai](https://stackoverflow.com/questions/152342/in-java-do-i-need-to-declare-my-collection-synchronized-if-its-read-only#152425), I didn't know such collections existed in the standard JDK).
Another very interesting read on the topic of concurrency which covers topics like publishing of objects, visibility, etc. in much more detail is Brian Goetz's book [Java Concurrency in Practice](http://www.briangoetz.com/pubs.html).
|
In Java, do I need to declare my collection synchronized if it's read-only?
|
[
"",
"java",
"multithreading",
"synchronization",
"web-applications",
""
] |
It seems that the
* [`System.Diagnostics.Debug`](https://msdn.microsoft.com/en-us/library/system.diagnostics.debug(v=vs.110).aspx), and
* [`System.Diagnostics.Trace`](https://msdn.microsoft.com/en-us/library/system.diagnostics.trace(v=vs.110).aspx)
are largely the same, with the notable exception that **Debug** usage is compiled out in a release configuration.
When would you use one and not the other? The only answer to this I've dug up so far is just that you use the **Debug** class to generate output that you only see in debug configuration, and **Trace** will remain in a release configuration, but that doesn't really answer the question in my head.
If you're going to instrument your code, why would you ever use **Debug**, since **Trace** can be turned off without a recompile?
|
The main difference is the one you indicate: Debug is not included in release, while Trace is.
The intended difference, as I understand it, is that development teams might use Debug to emit rich, descriptive messages that might prove too detailed (or revealing) for the consumer(s) of a product, while Trace is intended to emit the kinds of messages that are more specifically geared toward instrumenting an application.
To answer your last question, I can't think of a reason to use Debug to instrument a piece of code I intended to release.
Hope this helps.
|
The only difference between trace and debug is that trace statements are included by default in the program when it is compiled into a release build, whereas debug statement are not.
Thus, the debug class is principally used for debugging in the development phase, while trace can be used for **testing and optimization** after the application is compiled and released.
|
Trace vs Debug in .NET BCL
|
[
"",
"c#",
".net",
"debugging",
"instrumentation",
""
] |
In Visual Studio, two files are created when you create a new Windows Form in your solution (e.g. if you create MyForm.cs, MyForm.Designer.cs and MyForm.resx are also created). These second two files are displayed as a subtree in the Solution Explorer.
**Is there any way to add files to the sub-tree or group for a Windows Form class?**
|
Open .csproj in edit mode, look for the file you want to be under another one, and add the DependentUpon element, like this:
```
<Compile Include="AlertDialog.xaml.cs">
<DependentUpon>AlertDialog.xaml</DependentUpon>
</Compile>
```
|
You need to edit the csproj directly. There is a DependentUpon tag that you have to add as a child tag of the file you want to place under MyForm.cs.
Example:
```
<Compile Include="MyForm.MyCoolSubFile.cs">
<DependentUpon>MyForm.cs</DependentUpon>
</Compile>
```
|
Can I create a file that sits next to a .Designer.cs file in Visual Studio?
|
[
"",
"c#",
".net",
"visual-studio-2008",
""
] |
I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please?
```
public class Test {
public static void main(String args[]) {
Test t = new Test();
t.testT(null);
}
public <T extends Test> void testT(Class<T> type) {
Class<T> testType = type == null ? Test.class : type; //Error here
System.out.println(testType);
}
}
```
`Type mismatch: cannot convert from Class<capture#1-of ? extends Test> to Class<T>`
By casting `Test.class` to `Class<T>` this compiles with an `Unchecked cast` warning and runs perfectly.
|
The reason is that Test.class is of the type Class<Test>. You cannot assign a reference of type Class<Test> to a variable of type Class<T> as they are not the same thing. This, however, works:
```
Class<? extends Test> testType = type == null ? Test.class : type;
```
The wildcard allows both Class<T> and Class<Test> references to be assigned to testType.
There is a ton of information about Java generics behavior at [Angelika Langer Java Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html "Java Generics FAQ"). I'll provide an example based on some of the information there that uses the `Number` class heirarchy Java's core API.
Consider the following method:
```
public <T extends Number> void testNumber(final Class<T> type)
```
This is to allow for the following statements to be successfully compile:
```
testNumber(Integer.class);
testNumber(Number.class);
```
But the following won't compile:
```
testNumber(String.class);
```
Now consider these statements:
```
Class<Number> numberClass = Number.class;
Class<Integer> integerClass = numberClass;
```
The second line fails to compile and produces this error `Type mismatch: cannot convert from Class<Number> to Class<Integer>`. But `Integer` extends `Number`, so why does it fail? Look at these next two statements to see why:
```
Number anumber = new Long(0);
Integer another = anumber;
```
It is pretty easy to see why the 2nd line doesn't compile here. You can't assign an instance of `Number` to a variable of type `Integer` because there is no way to guarantee that the `Number` instance is of a compatible type. In this example the `Number` is actually a `Long`, which certainly can't be assigned to an `Integer`. In fact, the error is also a type mismatch: `Type mismatch: cannot convert from Number to Integer`.
The rule is that an instance cannot be assigned to a variable that is a subclass of the type of the instance as there is no guarantee that is is compatible.
Generics behave in a similar manner. In the generic method signature, `T` is just a placeholder to indicate what the method allows to the compiler. When the compiler encounters `testNumber(Integer.class)` it essentially replaces `T` with `Integer`.
Wildcards add additional flexibility, as the following will compile:
```
Class<? extends Number> wildcard = numberClass;
```
Since `Class<? extends Number>` indicates any type that is a `Number` or a subclass of `Number` this is perfectly legal and potentially useful in many circumstances.
|
Suppose I extend Test:
```
public class SubTest extends Test {
public static void main(String args[]) {
Test t = new Test();
t.testT(new SubTest());
}
}
```
Now, when I invoked `testT`, the type parameter `<T>` is `SubTest`, which means the variable `testType` is a `Class<SubTest>`. `Test.class` is of type `Class<Test>`, which is not assignable to a variable of type `Class<SubTest>`.
Declaring the variable `testType` as a `Class<? extends Test>` is the right solution; casting to `Class<T>` is hiding a real problem.
|
Type mismatch for Class Generics
|
[
"",
"java",
"generics",
""
] |
I'm working on a C# program, and right now I have one `Form` and a couple of classes. I would like to be able to access some of the `Form` controls (such as a `TextBox`) from my class. When I try to change the text in the `TextBox` from my class I get the following error:
> An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog'
How can I access methods and controls that are in `Form1.cs` from one of my classes?
|
You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.
If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.
Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg
```
public void DoSomethingWithText(string formText)
{
// do something text in here
}
```
or exposing properties on your form class and setting the form text in there - eg
```
string SomeProperty
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
```
|
Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
test.ModifyText(textBox1);
}
}
public class TestClass
{
public void ModifyText(TextBox textBox)
{
textBox.Text = "New text";
}
}
```
|
How to access form methods and controls from a class in C#?
|
[
"",
"c#",
"winforms",
""
] |
I have a bit of code that basically reads an XML document using the XMLDocument.Load(uri) method which works fine, but doesn't work so well if the call is made through a proxy.
I was wondering if anyone knew of a way to make this call (or achieve the same effect) through a proxy?
|
Do you have to provide credentials to the proxy?
If so, this should help:
"Supplying Authentication Credentials to XmlResolver when Reading from a File"
<http://msdn.microsoft.com/en-us/library/aa720674.aspx>
Basically, you...
1. Create an XmlTextReader using the URL
2. Set the Credentials property of the reader's XmlResolver
3. Create an XmlDocument instance and pass the reader to the Load method.
|
This is the code that I ended up using:
```
WebProxy wp = new WebProxy(Settings.Default.ProxyAddress);
wp.Credentials = new NetworkCredential(Settings.Default.ProxyUsername, Settings.Default.ProxyPassword);
WebClient wc = new WebClient();
wc.Proxy = wp;
MemoryStream ms = new MemoryStream(wc.DownloadData(url));
XmlTextReader rdr = new XmlTextReader(ms);
return XDocument.Load(rdr);
```
|
XMLDocument.Load(url) through a proxy
|
[
"",
"c#",
"xml",
"proxy",
""
] |
In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information.
My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (see bellow) is that when creating the string stream the buffers gets copied, and memory usage doubles.
```
#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream is;
is.open (sFilename.c_str(), ios::binary );
// get length of file:
is.seekg (0, std::ios::end);
long length = is.tellg();
is.seekg (0, std::ios::beg);
// allocate memory:
char *buffer = new char [length];
// read data as a block:
is.read (buffer,length);
// create string stream of memory contents
// NOTE: this ends up copying the buffer!!!
istringstream iss( string( buffer ) );
// delete temporary buffer
delete [] buffer;
// close filestream
is.close();
/* ==================================
* Use iss to access data
*/
}
```
|
`std::ifstream` has a method `rdbuf()`, that returns a pointer to a `filebuf`. You can then "push" this `filebuf` into your `stringstream`:
```
#include <fstream>
#include <sstream>
int main()
{
std::ifstream file( "myFile" );
if ( file )
{
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
// operations on the buffer...
}
}
```
EDIT: As Martin York remarks in the comments, this might not be the fastest solution since the `stringstream`'s `operator<<` will read the filebuf character by character. You might want to check his answer, where he uses the `ifstream`'s `read` method as you used to do, and then set the `stringstream` buffer to point to the previously allocated memory.
|
OK. I am not saying this will be quicker than reading from the file
But this is a method where you create the buffer once and after the data is read into the buffer use it directly as the source for stringstream.
**N.B.**It is worth mentioning that the std::ifstream is buffered. It reads data from the file in (relatively large) chunks. Stream operations are performed against the buffer only returning to the file for another read when more data is needed. So before sucking all data into memory please verify that this is a bottle neck.
```
#include <fstream>
#include <sstream>
#include <vector>
int main()
{
std::ifstream file("Plop");
if (file)
{
/*
* Get the size of the file
*/
file.seekg(0,std::ios::end);
std::streampos length = file.tellg();
file.seekg(0,std::ios::beg);
/*
* Use a vector as the buffer.
* It is exception safe and will be tidied up correctly.
* This constructor creates a buffer of the correct length.
*
* Then read the whole file into the buffer.
*/
std::vector<char> buffer(length);
file.read(&buffer[0],length);
/*
* Create your string stream.
* Get the stringbuffer from the stream and set the vector as it source.
*/
std::stringstream localStream;
localStream.rdbuf()->pubsetbuf(&buffer[0],length);
/*
* Note the buffer is NOT copied, if it goes out of scope
* the stream will be reading from released memory.
*/
}
}
```
|
How to read file content into istringstream?
|
[
"",
"c++",
"optimization",
"memory",
"stream",
"stringstream",
""
] |
Does MS Access 2007 support internal foreign keys within the same table?
|
Yes. Create the table with the hierarchy.
id - autonumber - primary key
parent\_id - number
value
Go to the relationships screen. Add the hierarchy table twice. Connect the id and the parent\_id fields. Enforce referential integrity.
|
Yes it does and unlike many more capable SQLs (e.g. SQL Server) you can also use CASCADE referential actions on FKs within the same table, which is nice.
|
Microsoft Access - SQL - Internal Foreign Key
|
[
"",
"sql",
"ms-access",
""
] |
I'm working on an upgrade for an existing database that was designed without any of the code to implement the design being considered. Now I've hit a brick wall in terms of implementing the database design in code. I'm certain whether its a problem with the design of the database or if I'm simply not seeing the correct solution on how to what needs to be done.
The basic logic stipulates the following:
1. Users access the online trainings by way of Seats. Users can have multiple Seats.
2. Seats are purchased by companies and have a many-to-many relationship with Products.
3. A Product has a many-to-many relationship with Modules.
4. A Module has a many-to-many relationship with Lessons.
5. Lessons are the end users access for their training.
6. To muddy the waters, for one reason or another some Users have multiple Seats that contain the same Products.
7. Certification takes place on a per Product basis, not on a per Seat basis.
8. Users have a many-to-many relationship with lessons that stores their current status or score for the lesson.
9. Users certify for a Product when they complete all of the Lessons in all of the Modules for the Product.
10. It is also significant to know when all Lessons for a particular Module are completed by a User.
11. Some Seats will be for ReCertification meaning that Users that previously certified for a Product can sign up and take a recertification exam.
12. Due to Rule 11, Users can and will have multiple Certification records.
13. Edit: When a User completes a Lesson (scores better than 80%) then the User has (according to the current business logic) completed the Lesson for all Products and all Seats that contain the Lesson.
The trouble that I keep running into with the current design and the business logic as I've more or less described it is that I can't find a way to effectively tie whether a user has certified for a particular product and seat vs when they have not. I keep hitting snags trying to establish which Products under which Seats have been certified for the User and which haven't. Part of the problem is because if they are currently registered for multiple of the same Product under different Seats, then I have to count the Product only once.
Below is a copy of the portion of the schema that's involved. Any suggestions on how to improve the design or draw the association in code would be appreciated. In case it matters, this site is built on the LAMPP stack.
You can view the relevant portion of the database schema here: [<http://lpsoftware.com/problem_db_structure.png>](http://lpsoftware.com/problem_db_structure.png)
|
What you're looking for is [relational division](http://www.dbazine.com/ofinterest/oi-articles/celko1)
Not implemented directly in SQL, but it can be done. Search google for other examples.
|
UPDATE:
I have considering this issue further and have considered whether it would allow things to work better to simply remove the user\_seat\_rtab table and then use the equivalent certification\_rtab table (probably renamed) to hold all of the information regarding the status of a user's seat. This way there is a direct relationship established between a User, their Seat, each Product within the Seat, and whether the User has certified for the particular Product and Seat.
So I would apply the following changes to the schema posted with the question:
```
DROP TABLE user_seat_rtab;
RENAME TABLE certification_rtab TO something_different;
```
An alternative to further normalize this new structure would be to do something like this:
```
ALTER TABLE user_seat_rtab
DROP PRIMARY KEY;
ADD COLUMN product_id int(10) unsigned NOT NULL;
ADD CONSTRAINT pk_user_seat_product PRIMARY KEY (user_id, seat_id, product_id);
ADD CONSTRAINT fk_product_user_seat FOREIGN KEY (product_id) REFERENCES product_rtab(id) ON DELETE RESTRICT;
```
I'm not really certain whether this would solve the problem or if it will just change the nature of the problem slightly while introducing new ones. So, does anyone have any other criticisms or suggestions?
|
Database Design Issues with relationships
|
[
"",
"php",
"mysql",
"database-design",
"foreign-keys",
"relational-database",
""
] |
C++ was the first programming language I really got into, but the majority of my work on it was academic or for game programming. Most of the programming jobs where I live require Java or .NET programmers and I have a fairly good idea of what technologies they require aside from the basic language. For example, a Java programmer might be required to know EJB, Servlets, Hibernate, Spring, and other technologies, libraries, and frameworks.
I'm not sure about C++, however. In real life situations, for general business programming, what are C++ programmers required to know beyond the language features? Stuff like Win32 API, certain libraries, frameworks, technologies, tools, etc.
---
Edit: I was thinking of the standard library as well when I said basic language, sorry if it was wrong or not clear. I was wondering if there are any more specific domain requirements similar to all the technologies Java or .NET programmers might be required to learn as apposed to what C++ programmers need to know in general. I do agree that the standard library and Boost are essential, but is there anything beyond that or is it different for every company/project/domain?
|
As for every language, I believe there are three interconnected levels of knowledge :
1. Master your language. Every programmer should (do what it takes to) master the syntax. Good references to achieve this are :
* [The C++ Programming Language](http://www.research.att.com/~bs/3rd.html) by Bjarne Stroustrup.
* [Effective C++ series](http://www.aristeia.com/books.html) by Scott Meyers.
2. Know your libraries extensively.
* [STL](http://en.wikipedia.org/wiki/Standard_Template_Library) is definitely a must as it has been included in the [C++ Standard Library](http://en.wikipedia.org/wiki/C%2B%2B_standard_library), so knowing it is very close to point 1 : you have to master it.
* Knowing [boost](http://www.boost.org/) can be very interesting, as a multi-platform and generic library.
* Know the libraries you are supposed to work with, whether it is [Win32 API](http://en.wikipedia.org/wiki/Win32), [OCCI](http://www.oracle.com/technology/tech/oci/occi/index.html), [XPCOM](http://www.mozilla.org/projects/xpcom/) or [UNO](http://udk.openoffice.org/) (just a few examples here). No need to know a database library if you develop purely graphic components...
3. Develop your knowledge of patterns. Cannot avoid [Design Patterns: Elements of Reusable Object-Oriented Software](http://en.wikipedia.org/wiki/Design_Patterns) here...
---
So, my answer to your updated question would be : know your language, know your platform, know your domain. I think there is enough work by itself here, especially in C++. It's an evergoing work that should never be overlooked.
|
C++ developer have to grok [std](http://en.wikipedia.org/wiki/C%2B%2B_standard_library) and [boost](http://www.boost.org) libraries.
List of other technologies largely depends on project type. For sure you will have some interaction with SO, so you will need to know API of your environment.
As for data-access and other stuffs there are tons for different solutions. C++ is much richer than some managed langs in that sense. 99% of old popular systems have C/C++ interface.
After you clarified your question a bit in the comment to my answer I can recommend:
* Good code browser (SourceInsight or Understand For C++ for example)
* Static analysis tools (Link, KlockWork Inforce, etc.)
* MySQL\SQLite (I encountered these DB in a huge number of C++ projects)
* UI technologies (OpenGL\GLUT, DirectX, GDI, Qt, etc)
|
What technologies do C++ programmers need to know?
|
[
"",
"c++",
""
] |
How to get the path of the current csproject?
Let's say I have a csproject name `MyProj.csproj`, inside there is a class that wants to know what is the file path of this csproj, any idea on how to do this? thanks.
|
If you really must do this, I would consider meta-programming. Create another project in your solution that builds a command line exe which takes one argument. The command line exe project should output a cs file that contains a class with a static property returning the value passed at the command line.
Then, as a pre-build step of your other project, call this command line exe (you'll need your build order such that the command line exe is built first) with the ProjectDir variable so that the command line argument is your project dir.
You'll also need your csproj to include the file that will be output by the command line so that it gets incorporated into your compiled assembly. Your main assembly code can call the static property of the generated class and so access the path.
Of course, just because you can do this, doesn't mean you should; I'm just assuming you've already determined that you must do this for your project.
|
Unless you are talking about creating a plugin for Visual Studio, the CsProj file no longer exists (as far as your code is concerned) once your program compiles and is running.
The CsProj is actually used to instruct the compiler how to compile your C# code into an assembly. After that point the CsProj is left on the developer's workstation as it is not needed by the "end user" of your application.
|
Get CSproj path in code
|
[
"",
"c#",
""
] |
I would like to specify a constraint which is another type with a generic argument.
```
class KeyFrame<T>
{
public float Time;
public T Value;
}
// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}
```
But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?:
```
class Timeline<TKeyframe, TKeyframeValue>
where TKeyframe : Keyframe<TKeyframeValue>,
{
}
```
|
Read about this from [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2008/05/19/a-generic-constraint-question.aspx)
Basically, you have to find a way to refer to the type you want without specifying the secondary type parameter.
In his post, he shows this example as a possible solution:
```
public abstract class FooBase
{
private FooBase() {} // Not inheritable by anyone else
public class Foo<U> : FooBase {...generic stuff ...}
... nongeneric stuff ...
}
public class Bar<T> where T: FooBase { ... }
...
new Bar<FooBase.Foo<string>>()
```
Hope that helps,
Troy
|
As TimeLine is most likely an aggregation of KeyFrames, wouldn't something like:
```
class TimeLine<T>
{
private IList<KeyFrame<T>> keyFrameList;
...
}
```
fulfill your requirements nicely?
|
How can I use a type with generic arguments as a constraint?
|
[
"",
"c#",
"generics",
"constraints",
""
] |
I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.
What is the best way to convert the entire file format using Python?
|
You can convert the file easily enough just using the `unicode` function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.
[This blog](http://www.peterbe.com/plog/unicode-to-ascii) recommends the `unicodedata` module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g.
```
>>> title = u"Klüft skräms inför på fédéral électoral große"
```
is typically converted to
```
Klft skrms infr p fdral lectoral groe
```
which is pretty wrong. However, using the `unicodedata` module, the result can be much closer to the original text:
```
>>> import unicodedata
>>> unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'
```
|
*I think this is a deeper issue than you realize*. Simply changing the file from Unicode into ASCII is easy, however, getting all of the Unicode characters to translate into reasonable ASCII counterparts (many letters are not available in both encodings) is another.
This Python Unicode tutorial may give you a better idea of what happens to Unicode strings that are translated to ASCII: <http://www.reportlab.com/i18n/python_unicode_tutorial.html>
**Here's a useful quote from the site:**
> Python 1.6 also gets a "unicode"
> built-in function, to which you can
> specify the encoding:
```
> >>> unicode('hello') u'hello'
> >>> unicode('hello', 'ascii') u'hello'
> >>> unicode('hello', 'iso-8859-1') u'hello'
> >>>
```
> All three of these return the same
> thing, since the characters in 'Hello'
> are common to all three encodings.
>
> Now let's encode something with a
> European accent, which is outside of
> ASCII. What you see at a console may
> depend on your operating system
> locale; Windows lets me type in
> ISO-Latin-1.
```
> >>> a = unicode('André','latin-1')
> >>> a u'Andr\202'
```
> If you can't type an acute letter e,
> you can enter the string 'Andr\202',
> which is unambiguous.
>
> Unicode supports all the common
> operations such as iteration and
> splitting. We won't run over them
> here.
|
How do I convert a file's format from Unicode to ASCII using Python?
|
[
"",
"python",
"unicode",
"encoding",
"file",
"ascii",
""
] |
I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than [ROT13](http://en.wikipedia.org/wiki/ROT13) or [Base64](http://en.wikipedia.org/wiki/Base64).
I'd prefer something that is already included in the [.NET](http://en.wikipedia.org/wiki/.NET_Framework) framework 2.0, so I don't have to worry about any external dependencies.
I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.
|
Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays.
NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be <= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use <https://www.random.org/bytes/> to generate a new set easily:
* [generate `Key`](https://www.random.org/cgi-bin/randbyte?nbytes=32&format=d)
* [generate `Vector`](https://www.random.org/cgi-bin/randbyte?nbytes=16&format=d)
Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place.
---
```
using System;
using System.Data;
using System.Security.Cryptography;
using System.IO;
public class SimpleAES
{
// Change these keys
private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });
// a hardcoded IV should not be used for production AES-CBC code
// IVs should be unpredictable per ciphertext
private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 });
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleAES()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
static public byte[] GenerateEncryptionKey()
{
//Generate a Key.
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateKey();
return rm.Key;
}
/// Generates a unique encryption vector
static public byte[] GenerateEncryptionVector()
{
//Generate a Vector
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateIV();
return rm.IV;
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue));
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString));
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return UTFEncoder.GetString(decryptedBytes);
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
```
|
I cleaned up SimpleAES (above) for my use. Fixed convoluted encrypt/decrypt methods; separated methods for encoding byte buffers, strings, and URL-friendly strings; made use of existing libraries for URL encoding.
The code is small, simpler, faster and the output is more concise. For instance, `johnsmith@gmail.com` produces:
```
SimpleAES: "096114178117140150104121138042115022037019164188092040214235183167012211175176167001017163166152"
SimplerAES: "YHKydYyWaHmKKnMWJROkvFwo1uu3pwzTr7CnARGjppg%3d"
```
Code:
```
public class SimplerAES
{
private static byte[] key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });
// a hardcoded IV should not be used for production AES-CBC code
// IVs should be unpredictable per ciphertext
private static byte[] vector = __Replace_Me_({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 });
private ICryptoTransform encryptor, decryptor;
private UTF8Encoding encoder;
public SimplerAES()
{
RijndaelManaged rm = new RijndaelManaged();
encryptor = rm.CreateEncryptor(key, vector);
decryptor = rm.CreateDecryptor(key, vector);
encoder = new UTF8Encoding();
}
public string Encrypt(string unencrypted)
{
return Convert.ToBase64String(Encrypt(encoder.GetBytes(unencrypted)));
}
public string Decrypt(string encrypted)
{
return encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
}
public byte[] Encrypt(byte[] buffer)
{
return Transform(buffer, encryptor);
}
public byte[] Decrypt(byte[] buffer)
{
return Transform(buffer, decryptor);
}
protected byte[] Transform(byte[] buffer, ICryptoTransform transform)
{
MemoryStream stream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return stream.ToArray();
}
}
```
|
Simple insecure two-way data "obfuscation"?
|
[
"",
"c#",
"obfuscation",
""
] |
I want to do some benchmarking of a C# process, but I don't want to use time as my vector - I want to count the number of IL instructions that get executed in a particular method call. Is this possible?
**Edit** I don't mean static analysis of a method body - I'm referring to the actual number of instructions that are executed - so if, for example, the method body includes a loop, the count would be increased by however many instructions make up the loop \* the number of times the loop is iterated.
|
I don't think it's possible to do what you want. This is because the IL is only used during JIT (Just-In-Time) compilation. By the time the method is running the IL has been translated into native machine code. So, while it might be possible to count the number of IL instructions in a given method/type/assembly statically, there's no concept of this at runtime.
You haven't stated your intention in knowing the number of IL instructions that would be interpreted. Given that there's only a loose correlation between the IL count of a method body and the actual number of machine code instructions, I fail to see what knowing this number would achieve (other than satisfying your curiosity).
|
Well, it won't be easy. I *think* you could instrument your assembly post-compile with performance counter code that executed after blocks of IL. For example, if you had a section of a method that loaded an int onto the stack then executed a static method using that int under optimized code, you could record a count of 2 for the int load and call.
Even using existing IL/managed assembly reading/writing projects, this would be a pretty daunting task to pull off.
Of course, some instructions that your counter recorded might get optimized away during just-in-time compiling to x86/ia64/x64, but that is a risk you'd have to take to try to profile based on an abstract lanaguage like IL.
|
Is there a way to count the number of IL instructions executed?
|
[
"",
"c#",
".net",
"benchmarking",
"cil",
""
] |
I want to run a psychological study for which participants have to look at large images.
The experiment is done on the web and therefore in a browser window. Is it possible to tell the browser to go into fullscreen, for example on button press?
I know there is the possibility to open a fixed-size popup window. Do you think this would be a feasable alternative? And if, what would be the best way to do it? Are there elegant ways of detecting a popup-blocker, to fallback and run the study in the original browser window.
The main concern is that the participants of this study are not familiar with technical details and should not be bothered by them.
|
I have found some code after searching.
```
function fullscreen() {
var element = document.getElementById("content");
if (element.requestFullScreen) {
if (!document.fullScreen) {
element.requestFullscreen();
$(".fullscreen").attr('src',"img/icons/panel_resize_actual.png");
} else {
document.exitFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize.png");
}
} else if (element.mozRequestFullScreen) {
if (!document.mozFullScreen) {
element.mozRequestFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize_actual.png");
google.maps.event.trigger(map, 'resize');
} else {
document.mozCancelFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize.png");
}
} else if (element.webkitRequestFullScreen) {
if (!document.webkitIsFullScreen) {
element.webkitRequestFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize_actual.png");
google.maps.event.trigger(map, 'resize');
} else {
document.webkitCancelFullScreen();
$(".fullscreen").attr('src',"img/icons/panel_resize.png");
}
}
}
```
It will use html5 api. I switch with jquery the a special picture for it. Hope that will help out. At the moment, i don't know if you can force it, 'cause it was forbitten due security.
|
You could just tell the user to press F11. Next to it, put a 'why?' link and explain why you feel like they need to be in fullscreen mode.
I don't think you can force a browser to go full screen and, in fact, if you were able to do that I'd be furious at my browser. It's too invasive. Even Flash has security so that forcing the plugin to go to fullscreen requires the event to originate with a user interaction. So, if it's that important to you, this might be a good reason to use the Flash plugin because you could attach the go-fullscreen call to a misleading button that says 'start quiz' (or whatever).
But, please don't do that. Just be straight forward with the user and tell them to hit F11.
EDIT: I just tried the sample code provided in another comment and I'm happy to say that Firefox opens up a maximized window with an address bar, not a fullscreen window.
|
Could a website force the browser to go into fullscreen mode?
|
[
"",
"javascript",
"html",
"browser",
"window",
""
] |
Im trying to find out a good JavaScript library that can create a nice "inner-window" popup within a page on my site.
I would like to not have to worry about screen positioning (i.e. dont have to calcuate if the size of the window will be off screen, etc...), but just make a new pop-up that has content in it.
I'll be using .NET 3.5 ASP.NET (maybe MVC, havent started yet), I know JQuery has great support, but from what I have seen, it doesnt have this type of widget feature.
Please note, I do not want to use "frames" in any way, shape, or form! But rather the floating div style approach (or similar).
Thanks heaps!
Mark
|
**Floating containers, panels and dialogs:**
For dialog boxes and windows, perhaps a [**YUI module**](http://developer.yahoo.com/yui/container/module/) would be a **good solution**.
**Modal Boxes**
If you **aren't a javascript programmer**, and you're interested in a more-elaborate modal box, there are jQuery **plugins** [**offering**](http://leandrovieira.com/projects/jquery/lightbox/) the [**modal lightbox effect**](http://jquery.com/demo/thickbox/).
**Sidenote:** There are many libraries offering this kind of functionality, but if the box itself is the only piece you need, keep in consideration that **some libraries will include many things you aren't using**. If you're careful to use only the packages you need, you can keep your page nice and lean.
**Sidenote:** If you're fairly well-versed with javascript, or wish to become so, remember that you can always *write your own*. It's common for people in the javascript world to turn straight to libraries. Libraries are an important part of the modern javascript landscape, but sometimes they become a crutch for developers. Writing a few front-end pieces yourself is a great way to dive into front-end development.
|
I have used one called [iBox](http://www.ibegin.com/labs/ibox/) and it has worked well.
If you are already using jQuery then you might want to check out these [two](http://leandrovieira.com/projects/jquery/lightbox/) [options](http://jquery.com/demo/thickbox/).
|
JavaScript library to create div-style window within page
|
[
"",
".net",
"javascript",
"dhtml",
""
] |
Is there a way to change the color of the background for a MDIParent windows in MFC (2005)?
I have tried intercepting ON\_WM\_CTLCOLOR AND ON\_WM\_ERASEBKGND but neither work. OnEraseBkgnd does work, but then it gets overwritten by the standard WM\_CTL color.
Cheers
|
The CMDIFrameWnd is actually covered up by another window called the MDIClient window. Here is a Microsoft article on how to subclass this MDIClient window and change the background colour. I just tried it myself and it works great.
<http://support.microsoft.com/kb/129471>
|
Create a class deriving CWnd (CClientWnd for example)
In your CWnd-derived class handle
```
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint(void);
afx_msg void OnSize(UINT nType, int cx, int cy);
```
You need the following message map entries:
```
ON_WM_ERASEBKGND()
ON_WM_PAINT()
ON_WM_SIZE()
```
In OnEraseBkgnd just return TRUE, you'll do all of the work in OnPaint
In OnPaint, do whatever you like. To fill with a color, you could do
```
CBrush brush;
brush.CreateSolidBrush(COLORREF(RGB( 80, 160, 240 )));
CRect clientRect;
GetClientRect(clientRect);
CPaintDC dc(this);
dc.FillRect(clientRect, &brush);
```
In OnSize, call the base class, then invalidate to force a repaint:
```
CWnd::OnSize(nType, cx, cy);
Invalidate(FALSE);
```
---
In your mainframe, declare a member CClientWnd (m\_clientWnd for example)
In your mainframe's OnCreate, first call the superclass, then
```
m_clientWnd.SubclassWindow(m_hWndMDIClient);
```
|
Setting Background Color CMDIFrameWnd
|
[
"",
"c++",
"user-interface",
"mfc",
"colors",
""
] |
I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
|
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of `std::string`'), check out this [Guru of the Week "Monolith" class article](http://www.gotw.ca/gotw/084.htm).
|
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
|
Extending an existing class like a namespace (C++)?
|
[
"",
"c++",
"code-organization",
""
] |
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
|
Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:
<http://www.perforce.com/perforce/loadsupp.html#api>
You will find their documentation of the scripting API to be helpful:
<http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf>
Use of the Python API is quite similar to the command-line client:
```
PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> import P4
>>> p4 = P4.P4()
>>> p4.connect() # connect to the default server, with the default clientspec
>>> desc = {"Description": "My new changelist description",
... "Change": "new"
... }
>>> p4.input = desc
>>> p4.run("changelist", "-i")
['Change 2579505 created.']
>>>
```
I'll verify it from the command line:
```
P:\>p4 changelist -o 2579505
# A Perforce Change Specification.
#
# Change: The change number. 'new' on a new changelist.
# Date: The date this specification was last modified.
# Client: The client on which the changelist was created. Read-only.
# User: The user who created the changelist.
# Status: Either 'pending' or 'submitted'. Read-only.
# Description: Comments about the changelist. Required.
# Jobs: What opened jobs are to be closed by this changelist.
# You may delete jobs from this list. (New changelists only.)
# Files: What opened files from the default changelist are to be added
# to this changelist. You may delete files from this list.
# (New changelists only.)
Change: 2579505
Date: 2008/10/08 13:57:02
Client: MYCOMPUTER-DT
User: myusername
Status: pending
Description:
My new changelist description
```
|
Here's what I came up with:
```
import os
def CreateNewChangeList(description):
"Create a new changelist and returns the changelist number as a string"
p4in, p4out = os.popen2("p4 changelist -i")
p4in.write("change: new\n")
p4in.write("description: " + description)
p4in.close()
changelist = p4out.readline().split()[1]
return changelist
def OpenFileForEdit(file, changelist = ""):
"Open a file for edit, if a changelist is passed in then open it in that list"
cmd = "p4 edit "
if changelist:
cmd += " -c " + changelist + " "
ret = os.popen(cmd + file).readline().strip()
if not ret.endswith("opened for edit"):
print "Couldn't open", file, "for edit:"
print ret
raise ValueError
```
|
How do I check out a file from perforce in python?
|
[
"",
"python",
"scripting",
"perforce",
""
] |
I have the following query:
```
SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid)
WHERE j.jobid = 123;
```
I have the following questions:
1. Is the USING syntax synonymous with ON syntax?
2. Are these joins evaluated left to right? In other words, does this query say: x = companies JOIN users; y = x JOIN jobs; z = y JOIN useraccounts;
3. If the answer to question 2 is yes, is it safe to assume that the companies table has companyid, userid and jobid columns?
4. I don't understand how the WHERE clause can be used to pick rows on the companies table when it is referring to the alias "j"
Any help would be appreciated!
|
1. USING (fieldname) is a shorthand way of saying ON table1.fieldname = table2.fieldname.
2. SQL doesn't define the 'order' in which JOINS are done because it is not the nature of the language. Obviously an order has to be specified in the statement, but an INNER JOIN can be considered commutative: you can list them in any order and you will get the same results.
That said, when constructing a SELECT ... JOIN, particularly one that includes LEFT JOINs, I've found it makes sense to regard the third JOIN as joining the new table to the results of the first JOIN, the fourth JOIN as joining the results of the second JOIN, and so on.
More rarely, the specified order can influence the behaviour of the query optimizer, due to the way it influences the heuristics.
3. No. The way the query is assembled, it requires that companies and users both have a companyid, jobs has a userid and a jobid and useraccounts has a userid. However, only one of companies *or* user needs a userid for the JOIN to work.
4. The WHERE clause is filtering the whole result -- i.e. all JOINed columns -- using a column provided by the jobs table.
|
I can't answer the bit about the USING syntax. That's weird. I've never seen it before, having always used an ON clause instead.
But what I *can* tell you is that the order of JOIN operations is determined dynamically by the query optimizer when it constructs its query plan, based on a system of optimization heuristics, some of which are:
1. Is the JOIN performed on a primary key field? If so, this gets high priority in the query plan.
2. Is the JOIN performed on a foreign key field? This also gets high priority.
3. Does an index exist on the joined field? If so, bump the priority.
4. Is a JOIN operation performed on a field in WHERE clause? Can the WHERE clause expression be evaluated by examining the index (rather than by performing a table scan)? This is a *major* optimization opportunity, so it gets a major priority bump.
5. What is the cardinality of the joined column? Columns with high cardinality give the optimizer more opportunities to discriminate against false matches (those that don't satisfy the WHERE clause or the ON clause), so high-cardinality joins are usually processed before low-cardinality joins.
6. How many actual rows are in the joined table? Joining against a table with only 100 values is going to create less of a data explosion than joining against a table with ten million rows.
Anyhow... the point is... there are a LOT of variables that go into the query execution plan. If you want to see how MySQL optimizes its queries, use the EXPLAIN syntax.
And here's a good article to read:
<http://www.informit.com/articles/article.aspx?p=377652>
---
ON EDIT:
To answer your 4th question: You aren't querying the "companies" table. You're querying the joined cross-product of **ALL** four tables in your FROM and USING clauses.
The "j.jobid" alias is just the fully-qualified name of one of the columns in that joined collection of tables.
|
In what order are MySQL JOINs evaluated?
|
[
"",
"mysql",
"sql",
"join",
""
] |
Is there any advantage to using `__construct()` instead of the class's name for a constructor in PHP?
Example (`__construct`):
```
class Foo {
function __construct(){
//do stuff
}
}
```
Example (named):
```
class Foo {
function Foo(){
//do stuff
}
}
```
Having the `__construct` method (first example) is possible since PHP 5.
---
**Moderator note**: The question relates to functionality that was available in PHP 5. Since PHP 7.0, named constructors have been deprecated and removed in PHP 8.0.
|
The advantage is that you don't have to rename it if you rename your class. DRY.
Similarly, if you have a child class, you can call the parent constructor:
```
parent::__construct()
```
If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent.
It seems like a small thing, but missing changing the constructor call name to your parents' classes could create subtle (and not so subtle) bugs.
For example, if you inserted a class into your hierarchy, but forgot to change the constructor calls, you could start calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.
|
`__construct` was introduced in PHP5. It is the way you are supposed to do it now. I am not aware of any *advantages* per se, though.
From the PHP manual:
> For backwards compatibility, if PHP 5 cannot find a \_\_construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named \_\_construct() which was used for different semantics
If you're on PHP5 I would recommend using `__construct` to avoid making PHP look elsewhere.
|
__construct() vs SameAsClassName() for constructor in PHP
|
[
"",
"php",
"constructor",
""
] |
I tried this XAML:
```
<Slider Width="250" Height="25" Minimum="0" Maximum="1" MouseLeftButtonDown="slider_MouseLeftButtonDown" MouseLeftButtonUp="slider_MouseLeftButtonUp" />
```
And this C#:
```
private void slider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
sliderMouseDown = true;
}
private void slider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
sliderMouseDown = false;
}
```
The sliderMouseDown variable never changes because the MouseLeftButtonDown and MouseLeftButtonUp events are never raised. How can I get this code to work when a user has the left mouse button down on a slider to have a bool value set to true, and when the mouse is up, the bool is set to false?
|
Sliders swallow the MouseDown Events (similar to the button).
You can register for the PreviewMouseDown and PreviewMouseUp events which get fired before the slider has a chance to handle them.
|
Another way to do it (and possibly better depending on your scenario) is to register an event handler in procedural code like the following:
```
this.AddHandler
(
Slider.MouseLeftButtonDownEvent,
new MouseButtonEventHandler(slider_MouseLeftButtonDown),
true
);
```
Please note the true argument. **It basically says that you want to receive that event even if it has been marked as handled.** Unfortunately, hooking up an event handler like this can only be done from procedural code and not from xaml.
In other words, with this method, you can register an event handler for the normal event (which bubbles) instead of the preview event which tunnels (and therefore occur at different times).
See the Digging Deeper sidebar on page 70 of *WPF Unleashed* for more info.
|
WPF: Slider doesnt raise MouseLeftButtonDown or MouseLeftButtonUp
|
[
"",
"c#",
"wpf",
"slider",
"mouseevent",
""
] |
I've got build server running CruiseControl.NET and recently it started throwing this error on one of my projects (.NET 2.0, C#):
> MSB3176: Specified minimum required version is greater than the current publish version. Please specify a version less than or equal to the current publish version. in Microsoft.Common.targets(2238, 9)
I've search the net, but could not find a solution.
Any suggestions?
|
Check the properties of your project. The version numbers are on the 'publish' tab. You should compare the publish version with the minimum version ('Updates' button).
|
The project properties have a publish version (on the Publish tab), and an (optional) minimum version (on the Updates button on the Publish tab). Neither is related to any assembly version, and is just used for ClickOnce. If a minimum version is specified, it must be logical (i.e. not higher than the main version).
In the csproj, this is the ApplicationVersion/ApplicationRevision and MinimumRequiredVersion elements.
|
Error "MSB3176: Specified minimum required version is greater than the current publish version"
|
[
"",
"c#",
"msbuild",
".net-2.0",
"cruisecontrol.net",
""
] |
Is there a way to print all methods of an object in JavaScript?
|
Sure:
```
function getMethods(obj) {
var result = [];
for (var id in obj) {
try {
if (typeof(obj[id]) == "function") {
result.push(id + ": " + obj[id].toString());
}
} catch (err) {
result.push(id + ": inaccessible");
}
}
return result;
}
```
Using it:
```
alert(getMethods(document).join("\n"));
```
|
If you just want to look what is inside an object, you can print all object's keys. Some of them can be variables, some - methods.
The method is not very accurate, however it's really quick:
```
console.log(Object.keys(obj));
```
|
Is there a way to print all methods of an object?
|
[
"",
"javascript",
""
] |
I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?
|
You can use:
```
System.getProperty("os.name")
```
P.S. You may find this code useful:
```
class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}
```
All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)
|
As indicated in other answers, System.getProperty provides the raw data. However, the [Apache Commons Lang component](http://commons.apache.org/lang/) provides a [wrapper for java.lang.System](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html) with handy properties like [`SystemUtils.IS_OS_WINDOWS`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html#IS_OS_WINDOWS), much like the aforementioned Swingx OS util.
|
How do I programmatically determine operating system in Java?
|
[
"",
"java",
"operating-system",
""
] |
Personally, I find the range of functionality provided by java.util.Iterator to be fairly pathetic. At a minimum, I'd like to have methods such as:
* peek() returns next element without moving the iterator forward
* previous() returns the previous element
Though there are lots of other possibilities such as first() and last().
Does anyone know if such a 3rd party iterator exists? It would probably need to be implemented as a decorator of java.util.Iterator so that it can work with the existing java collections. Ideally, it should be "generics aware".
Thanks in advance,
Don
|
[Apache Commons Collections](https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/iterators/package-summary.html)
[Google Collections](https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/package-summary.html)
|
You can get `previous()` easily by just using a `java.util.ListIterator`.
Peek at that point is easily implemented by doing a
```
public <T> T peek(ListIterator<T> iter) throws NoSuchElementException {
T obj = iter.next();
iter.previous();
return obj;
}
```
Unfortunately it will be easier to have it as a utility method since each collection class implements their own iterators. To do a wrapper to get a peek method on each collection on some interface such as `MyListIterator` would be quite a lot of work.
|
improved collection Iterator
|
[
"",
"java",
"collections",
"iterator",
"decorator",
""
] |
I'm working on a simple 2D game engine in Java, and having no trouble with FSEM, buffer strategies, and so on; my issue is with the mouse cursor. In windowed mode, I can hide the mouse cursor, no problem, by using setCursor() from my JFrame to set a wholly-transparent cursor. However, after a call to device.setFullScreenWindow(this) to go into FSEM, the mouse cursor comes back, and subsequent calls to setCursor() to set it back to my blank cursor have no effect. Calling device.setFullScreenWindow(null) allows me to get rid of the cursor again - it's only while I'm in FSEM that I can't get rid of it.
I'm working under JDK 6, target platform is JDK 5+.
**UPDATE:** I've done some more testing, and it looks like this issue occurs under MacOS X 10.5 w/Java 6u7, but not under Windows XP SP3 with Java 6u7. So, it could possibly be a bug in the Mac version of the JVM.
|
I think I've finally found the solution:
```
System.setProperty("apple.awt.fullscreenhidecursor","true");
```
This is an Apple-proprietary system property that hides the mouse cursor when an application is in full-screen mode. It's the only way I've found to fix it.
|
Try Creating a custom invisible cursor:
```
Toolkit toolkit = Toolkit.getDefaultToolkit();
Point hotSpot = new Point(0,0);
BufferedImage cursorImage = new BufferedImage(1, 1, BufferedImage.TRANSLUCENT);
Cursor invisibleCursor = toolkit.createCustomCursor(cursorImage, hotSpot, "InvisibleCursor");
setCursor(invisibleCursor);
```
|
How do I get rid of the mouse cursor in full-screen exclusive mode?
|
[
"",
"java",
"mouse",
"fullscreen",
"mouse-cursor",
""
] |
I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this?
|
**Overview:**
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++ does change the definition of some terms in C such as structs, although still in a superset way.
**Examples of why it is not a strict superset:**
[This Wikipedia article](http://en.wikipedia.org/wiki/C%2B%2B) has a couple good examples of such a differences:
> One commonly encountered difference is
> that C allows implicit conversion from
> void\* to other pointer types, but C++
> does not. So, the following is valid C
> code:
>
> ```
> int *i = malloc(sizeof(int) * 5);
> ```
>
> ... but to make it work in both C and
> C++ one would need to use an explicit
> cast:
>
> ```
> int *i = (int *) malloc(sizeof(int) * 5)
> ```
>
> Another common portability issue is
> that C++ defines many new keywords,
> such as new and class, that may be
> used as identifiers (e.g. variable
> names) in a C program.
[This wikipedia article](http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B) has further differences as well:
> C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:
```
void fn(void)
{
goto flack;
int i = 1;
flack:
;
}
```
**What should you learn first?**
You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first. You will eventually learn just about everything about C anyway because it is more or less contained in C++.
|
While it's true that C++ was designed to maintain a large degree of compatibility with C and a subset of what you learn in C++ will apply to C the mindset is completely different. Programming C++ with Boost or STL is a very different experience than programming in C.
There was a term of art called using C++ as a better C. This meant using some C++ language features and tools to make C programming easier (e.g., declaring the index variable of a for loop within the for statement). But now, modern C++ development seems very different from C other than a great deal of the syntax and in those cases the C legacy often seems to be a burden rather than a benefit.
|
Is it true that there is no need to learn C because C++ contains everything?
|
[
"",
"c++",
"c",
""
] |
I'm working with jQuery for the first time and need some help. I have html that looks like the following:
```
<div id='comment-8' class='comment'>
<p>Blah blah</p>
<div class='tools'></div>
</div>
<div id='comment-9' class='comment'>
<p>Blah blah something else</p>
<div class='tools'></div>
</div>
```
I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment.
What I have thus far is:
```
<script type='text/javascript'>
$(function() {
var actionSpan = $('<span>[Do Something]</span>');
actionSpan.bind('click', doSomething);
$('.tools').append(actionSpan);
});
function doSomething(commentId) { alert(commentId); }
</script>
```
I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that.
Thanks,
Brian
|
Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a `target` property that references the element it was called for, and the `this` variable is a reference to the element the event handler was attached to. So you could do the following:
```
function doSomething(event)
{
var id = $(event.target).parents(".tools").attr("id");
id = substring(id.indexOf("-")+1);
alert(id);
}
```
...or:
```
function doSomething(event)
{
var id = $(this).parents(".tools").attr("id");
id = substring(id.indexOf("-")+1);
alert(id);
}
```
|
To get from the span up to the surrounding divs, you can use `<tt>parent()</tt>` (if you know the exact relationship), like this: `<tt>$(this).parent().attr('id')</tt>;` or if the structure might be more deeply nested, you can use parents() to search up the DOM tree, like this: `<tt>$(this).parents('div:eq(0)').attr('id')</tt>`.
To keep my answer simple, I left off matching the class `<tt>"comment"</tt>` but of course you could do that if it helps narrow down the div you are searching for.
|
Passing in parameter from html element with jQuery
|
[
"",
"javascript",
"jquery",
""
] |
Is there a way to use Enum values inside a JSP without using scriptlets.
e.g.
```
package com.example;
public enum Direction {
ASC,
DESC
}
```
so in the JSP I want to do something like this
```
<c:if test="${foo.direction ==<% com.example.Direction.ASC %>}">...
```
|
You could implement the web-friendly text for a direction within the enum as a field:
```
<%@ page import="com.example.Direction" %>
...
<p>Direction is <%=foo.direction.getFriendlyName()%></p>
<% if (foo.direction == Direction.ASC) { %>
<p>That means you're going to heaven!</p>
<% } %>
```
but that mixes the view and the model, although for simple uses it can be view-independent ("Ascending", "Descending", etc).
Unless you don't like putting straight Java into your JSP pages, even when used for basic things like comparisons.
|
It can be done like this I guess
```
<c:set var="ASC" value="<%=Direction.ASC%>"/>
<c:if test="${foo.direction == ASC}"></c:if>
```
the advantage is when we refactor it will reflect here too
|
Enum inside a JSP
|
[
"",
"java",
"jsp",
"jstl",
""
] |
I'm trying to do a domain lookup in vba with something like this:
```
DLookup("island", "villages", "village = '" & txtVillage & "'")
```
This works fine until txtVillage is something like Dillon's Bay, when the apostrophe is taken to be a single quote, and I get a run-time error.
I've written a trivial function that escapes single quotes - it replaces "'" with "''". This seems to be something that comes up fairly often, but I can't find any reference to a built-in function that does the same. Have I missed something?
|
The "Replace" function should do the trick. Based on your code above:
```
DLookup("island", "villages", "village = '" & Replace(txtVillage, "'", "''") & "'")
```
|
It's worse than you think. Think about what would happen if someone entered a value like this, and you haven't escaped anything:
```
'); DROP TABLE [YourTable]
```
Not pretty.
The reason there's no built in function to simply escape an apostrophe is because the correct way to handle this is to use query parameters. For an Ole/Access style query you'd set this as your query string:
```
DLookup("island", "village", "village = ? ")
```
And then set the parameter separately. I don't know how you go about setting the parameter value from vba, though.
|
Escaping ' in Access SQL
|
[
"",
"sql",
"vba",
"ms-access",
"escaping",
""
] |
I need to add the ability for users of my software to select records by character ranges.
How can I write a query that returns all widgets from a table whose name falls in the range Ba-Bi for example?
Currently I'm using greater than and less than operators, so the above example would become:
```
select * from widget
where name >= 'ba' and name < 'bj'
```
Notice how I have "incremented" the last character of the upper bound from i to j so that "bike" would not be left out.
Is there a generic way to find the next character after a given character based on the field's collation or would it be safer to create a second condition?
```
select * from widget
where name >= 'ba'
and (name < 'bi' or name like 'bi%')
```
My application needs to support localization. How sensitive is this kind of query to different character sets?
I also need to support both MSSQL and Oracle. What are my options for ensuring that character casing is ignored no matter what language appears in the data?
|
Let's skip directly to localization. Would you say "aa" >= "ba" ? Probably not, but that is where it sorts in Sweden. Also, you simply can't assume that you can ignore casing in any language. Casing is explicitly language-dependent, with the most common example being Turkish: uppercase i is İ. Lowercase I is ı.
Now, your SQL DB defines the result of <, == etc by a "collation order". This is definitely language specific. So, you should explicitly control this, for every query. A Turkish collation order will put those i's where they belong (in Turkish). You can't rely on the default collation.
As for the "increment part", don't bother. Stick to >= and <=.
|
For MSSQL see this thread: <http://bytes.com/forum/thread483570.html> .
For Oracle, it depends on your Oracle version, as Oracle 10 now supports regex(p) like queries: <http://www.psoug.org/reference/regexp.html> (search for regexp\_like ) and see this article: <http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html>
HTH
|
What is the best way to select string fields based on character ranges?
|
[
"",
"sql",
"sql-server",
"oracle",
"localization",
"collation",
""
] |
I have a stored procedure that looks like:
```
CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND CASE WHEN @AdditionalFilter = 1 THEN
T.Column2 IS NOT NULL
```
Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help.
|
```
CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND (@AdditionalFilter = 0 OR
T.Column2 IS NOT NULL)
```
If @AdditionalFilter is 0, the column won't be evaluated since it can't affect the outcome of the part between brackets. If it's anything other than 0, the column condition will be evaluated.
|
This practice tends to confuse the query optimizer. I've seen SQL Server 2000 build the execution plan exactly the opposite way round and use an index on Column1 when the flag was set and vice-versa. SQL Server 2005 seemed to at least get the execution plan right on first compilation, but you then have a new problem. The system caches compiled execution plans and tries to reuse them. If you first use the query one way, it will still execute the query that way even if the extra parameter changes, and different indexes would be more appropriate.
You can force a stored procedure to be recompiled on this execution by using `WITH RECOMPILE` in the `EXEC` statement, or every time by specifying `WITH RECOMPILE` on the `CREATE PROCEDURE` statement. There will be a penalty as SQL Server re-parses and optimizes the query each time.
In general, if the form of your query is going to change, use dynamic SQL generation **with parameters**. SQL Server will also cache execution plans for parameterized queries and auto-parameterized queries (where it tries to deduce which arguments are parameters), and even regular queries, but it gives most weight to stored procedure execution plans, then parameterized, auto-parameterized and regular queries in that order. The higher the weight, the longer it can stay in RAM before the plan is discarded, if the server needs the memory for something else.
|
Stored procedure bit parameter activating additional where clause to check for null
|
[
"",
"sql",
"stored-procedures",
""
] |
I know there is built-in Internet explorer, but what I'm looking for is to open Firefox/Mozilla window (run the application) with specified URL. Anyone can tell me how to do that in C# (.nET) ?
|
This will launch the system defined default browser:
```
string url = "http://stackoverflow.com/";
System.Diagnostics.Process.Start(url);
```
Remember that Process.Start(url) might throw exceptions if the browser is not configured correctly.
|
You can do this:
```
System.Diagnostics.Process.Start("firefox.exe", "http://www.google.com");
```
|
How do I open alternative webbrowser (Mozilla or Firefox) and show the specific url?
|
[
"",
"c#",
".net",
"browser",
""
] |
Is there any real practical difference between "java -server" and "java -client"?
All I can find on Sun's site is a vague
> "-server starts slower but should run faster".
What are the real differences? (Using JDK 1.6.0\_07 currently.)
|
This is really linked to *HotSpot* and the default *option values* ([Java HotSpot VM Options](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html)) which differ between client and server configuration.
From [Chapter 2](http://www.oracle.com/technetwork/java/whitepaper-135217.html#2) of the whitepaper ([The Java HotSpot Performance Engine Architecture](http://www.oracle.com/technetwork/java/whitepaper-135217.html)):
> The JDK includes two flavors of the VM -- a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults.
>
> Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint.
>
> The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs.
So the real difference is also on the compiler level:
> The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint.
>
> The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques.
Note: The release of *jdk6 update 10* (see [Update Release Notes:Changes in 1.6.0\_10](http://www.oracle.com/technetwork/java/javase/6u10-142936.html)) tried to improve startup time, but for a different reason than the hotspot options, being packaged differently with a much smaller kernel.
---
[G. Demecki](https://stackoverflow.com/users/1037316/g-demecki) points out [in the comments](https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client/198651?noredirect=1#comment59707599_198651) that in 64-bit versions of JDK, the `-client` option is ignored for many years.
See [Windows `java` command](https://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html):
```
-client
```
> Selects the Java HotSpot Client VM.
> **A 64-bit capable JDK currently ignores this option and instead uses the Java Hotspot Server VM**.
---
2022: [Holger](https://stackoverflow.com/users/2711488/holger) references in [the comments](https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client/198651?noredirect=1#comment124789844_198651) the [JavaSE6 / Server-Class Machine Detection](https://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html), adding:
> Only on 32 bit Windows systems, `-client` was ever chosen unconditionally.
> Other systems checked whether the machine was “server class” which was fulfilled when having at least 2 cores and at least 2GiB of memory.
>
> Which explains why almost everything uses `-server` for quite some time now. Even the cheapest computers you can find, are “server class” machines. The Sun/Oracle 64 builds did not even ship with a client JVM.
|
The most visible immediate difference in older versions of Java would be the memory allocated to a `-client` as opposed to a `-server` application. For instance, on my Linux system, I get:
```
$ java -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'
uintx AdaptivePermSizeWeight = 20 {product}
uintx ErgoHeapSizeLimit = 0 {product}
uintx InitialHeapSize := 66328448 {product}
uintx LargePageHeapSizeThreshold = 134217728 {product}
uintx MaxHeapSize := 1063256064 {product}
uintx MaxPermSize = 67108864 {pd product}
uintx PermSize = 16777216 {pd product}
java version "1.6.0_24"
```
as it defaults to `-server`, but with the `-client` option I get:
```
$ java -client -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'
uintx AdaptivePermSizeWeight = 20 {product}
uintx ErgoHeapSizeLimit = 0 {product}
uintx InitialHeapSize := 16777216 {product}
uintx LargePageHeapSizeThreshold = 134217728 {product}
uintx MaxHeapSize := 268435456 {product}
uintx MaxPermSize = 67108864 {pd product}
uintx PermSize = 12582912 {pd product}
java version "1.6.0_24"
```
so with `-server` most of the memory limits and initial allocations are much higher for this `java` version.
These values can change for different combinations of architecture, operating system and jvm version however. Recent versions of the jvm have removed flags and re-moved many of the distinctions between server and client.
Remember too that you can see all the details of a running `jvm` using `jvisualvm`. This is useful if you have users who or modules which set `JAVA_OPTS` or use scripts which change command line options. This will also let you monitor, in real time, *heap* and *permgen* space usage along with lots of other stats.
|
Real differences between "java -server" and "java -client"?
|
[
"",
"java",
"jvm",
"jvm-hotspot",
""
] |
Following on from [this question](https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values) what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:
```
bool CharIsHex(char c) {
c = Char.ToLower(c);
return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}
```
|
From [my answer](https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values#223854) to the question you linked to:
```
bool is_hex_char = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
```
|
You can write it as an extension method:
```
public static class Extensions
{
public static bool IsHex(this char c)
{
return (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
}
}
```
This means you can then call it as though it were a member of `char`.
```
char c = 'A';
if (c.IsHex())
{
Console.WriteLine("We have a hex char.");
}
```
|
Char.IsHex() in C#
|
[
"",
"c#",
"algorithm",
""
] |
I've always used a `*.h` file for my class definitions, but after reading some boost library code, I realised they all use `*.hpp`. I've always had an aversion to that file extension, I think mainly because I'm not used to it.
What are the advantages and disadvantages of using `*.hpp` over `*.h`?
|
Here are a couple of reasons for having different naming of C vs C++ headers:
* Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically
* Naming, I've been on projects where there were libraries written in C and then wrappers had been implemented in C++. Since the headers usually had similar names, i.e. Feature.h vs Feature.hpp, they were easy to tell apart.
* Inclusion, maybe your project has more appropriate versions available written in C++ but you are using the C version (see above point). If headers are named after the language they are implemented in you can easily spot all the C-headers and check for C++ versions.
Remember, C is **not** C++ and it can be very dangerous to mix and match unless you know what you are doing. Naming your sources appropriately helps you tell the languages apart.
|
I use .hpp because I want the user to differentiate what headers are C++ headers, and what headers are C headers.
This can be important when your project is using both C and C++ modules: Like someone else explained before me, you should do it very carefully, and its starts by the "contract" you offer through the extension
# .hpp : C++ Headers
*(Or .hxx, or .hh, or whatever)*
This header is for C++ only.
If you're in a C module, don't even try to include it. You won't like it, because no effort is done to make it C-friendly (too much would be lost, like function overloading, namespaces, etc. etc.).
# .h : C/C++ compatible or pure C Headers
This header can be included by both a C source, and a C++ source, directly or indirectly.
It can included directly, being protected by the `__cplusplus` macro:
* Which mean that, from a C++ viewpoint, the C-compatible code will be defined as `extern "C"`.
* From a C viewpoint, all the C code will be plainly visible, but the C++ code will be hidden (because it won't compile in a C compiler).
For example:
```
#ifndef MY_HEADER_H
#define MY_HEADER_H
#ifdef __cplusplus
extern "C"
{
#endif
void myCFunction() ;
#ifdef __cplusplus
} // extern "C"
#endif
#endif // MY_HEADER_H
```
Or it could be included indirectly by the corresponding .hpp header enclosing it with the `extern "C"` declaration.
For example:
```
#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP
extern "C"
{
#include "my_header.h"
}
#endif // MY_HEADER_HPP
```
and:
```
#ifndef MY_HEADER_H
#define MY_HEADER_H
void myCFunction() ;
#endif // MY_HEADER_H
```
|
*.h or *.hpp for your class definitions
|
[
"",
"c++",
"header",
""
] |
What's the difference between `Char.IsDigit()` and `Char.IsNumber()` in C#?
|
`Char.IsDigit()` is a subset of `Char.IsNumber()`.
Some of the characters that are 'numeric' but not digits include 0x00b2 and 0x00b3 which are superscripted 2 and 3 ('²' and '³') and the glyphs that are fractions such as '¼', '½', and '¾'.
Note that there are quite a few characters that `IsDigit()` returns `true` for that are not in the ASCII range of 0x30 to 0x39, such as these Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'.
This snippet of code tells you which code points differ:
```
static private void test()
{
for (int i = 0; i <= 0xffff; ++i)
{
char c = (char) i;
if (Char.IsDigit( c) != Char.IsNumber( c)) {
Console.WriteLine( "Char value {0:x} IsDigit() = {1}, IsNumber() = {2}", i, Char.IsDigit( c), Char.IsNumber( c));
}
}
}
```
|
I found the answer:
> Char.IsNumber() determines if a Char
> is of any numeric Unicode category.
> This contrasts with IsDigit, which
> determines if a Char is a radix-10
> digit.
>
> Valid numbers are members of the
> following categories in
> [UnicodeCategory](http://msdn.microsoft.com/en-us/library/system.globalization.unicodecategory.aspx "Decimal digit character, that is, a character in the range 0 through 9. Signified by the Unicode designation \"Nd\" (number, decimal digit). The value is 8."):
>
> 1. **`DecimalDigitNumber`**
> Decimal digit character, that is, a character in the range 0 through 9. Signified by the Unicode designation "Nd" (number, decimal digit). The value is 8.
> 2. **`LetterNumber`**
> Number represented by a letter, instead of a decimal digit, for example, the Roman numeral for five, which is "V". The indicator is signified by the Unicode designation "Nl" (number, letter). The value is 9.
> 3. **`OtherNumber`**
> Number that is neither a decimal digit nor a letter number, for example, the fraction ½. The indicator is signified by the Unicode designation "No" (number, other). The value is 10.
## Conclusion
* **`Char.IsDigit`**:
Valid digits are members of the `DecimalDigitNumber` category only.
* **`Char.IsNumber`**:
Valid numbers are members of the `DecimalDigitNumber`, `LetterNumber`, or `OtherNumber` category.
|
Difference between Char.IsDigit() and Char.IsNumber() in C#
|
[
"",
"c#",
".net",
"unicode",
""
] |
I'm programming an online game for two reasons, one to familiarize myself with server/client requests in a realtime environment (as opposed to something like a typical web browser, which is not realtime) and to actually get my hands wet in that area, so I can proceed to actually properly design one.
Anywho, I'm doing this in C++, and I've been using winsock to handle my basic, basic network tests. I obviously want to use a framelimiter and have 3D going and all of that at some point, and my main issue is that when I do a send() or receive(), the program kindly idles there and waits for a response. That would lead to maybe 8 fps on even the best internet connection.
So the obvious solution to me is to take the networking code out of the main process and start it up in its own thread. Ideally, I would call a "send" in my main process which would pass the networking thread a pointer to the message, and then periodically (every frame) check to see if the networking thread had received the reply, or timed out, or what have you. In a perfect world, I would actually have 2 or more networking threads running simultaneously, so that I could say run a chat window and do a background download of a piece of armor and still allow the player to run around all at once.
The bulk of my problem is that this is a new thing to me. I understand the *concept* of threading, but I can see some serious issues, like what happens if two threads try to read/write the same memory address at the same time, etc. I know that there are already methods in place to handle this sort of thing, so I'm looking for suggestions on the best way to implement something like this. Basically, I need thread A to be able to start a process in thread B by sending a chunk of data, poll thread B's status, and then receive the reply, also as a chunk of data., ideally without any major crashing going on. ^\_^ I'll worry about what that data actually contains and how to handle dropped packets, etc later, I just need to get that happening first.
Thanks for any help/advice.
PS: Just thought about this, may make the question simpler. Is there a way to use the windows event handling system to my advantage? Like, would it be possible to have thread A initialize data somewhere, then trigger an event in thread B to have it pick up the data, and vice versa for thread B to tell thread A it was done? That would probably solve a lot of my problems, since I don't really need both threads to be able to work on the data at the same time, more of a baton pass really. I just don't know if this is possible between two different threads. (I know one thread can create its own messages for the event handler.)
|
**The easiest thing**
for you to do, would be to simply invoke the windows API **QueueUserWorkItem**. All you have to specify is the function that the thread will execute and the input passed to it. A thread pool will be automatically created for you and the jobs executed in it. New threads will be created as and when is required.
<http://msdn.microsoft.com/en-us/library/ms684957(VS.85).aspx>
**More Control**
You could have a more detailed control using another set of API's which can again manage the thread pool for you -
<http://msdn.microsoft.com/en-us/library/ms686980(VS.85).aspx>
**Do it yourself**
If you want to control all aspects of your thread creation and the pool management you would have to create the threads yourself, decide how they should end , how many to create etc (beginthreadex is the api you should be using to create threads. If you use MFC you should use AfxBeginThread function).
**Send jobs to worker threads - Io completion Ports**
In this case, you would also have to worry about how to communicate your jobs - i would recommend IoCOmpletionPorts to do that. It is the most scalable notification mechanism that i currently know of made for this purpose. It has the additional advantage that it is implemented in the kernel so you avoid all kinds of dead loack sitautions you would encounter if you decide to handroll something yourself.
This article will show you how with code samples -
<http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx>
**Communicate Back - Windows Messages**
You could use windows messages to communicate the status back to your parent thread since it is doing the message wait anyway. use the PostMessage function to do this. (and check for errors)
ps : You could also allocate the data that needs to be sent out on a dedicated pointer and then the worker thread could take care of deleting it after sending it out. That way you avoid the return pointer traffic too.
|
BlodBath's suggestion of non-blocking sockets is potentially the right approach.
If you're trying to avoid using a multithreaded approach, then you could investigate the use of setting up overlapped I/O on your sockets. They will not block when you do a transmit or receive, but have the added bonus of giving you the option of waiting for multiple events within your single event loop. When your transmit has finished, you will receive an event. (see [this](http://support.microsoft.com/kb/181611) for some details)
This is not incompatible with a multithreaded approach, so there's the option of changing your mind later. ;-)
On the design of your multithreaded app. the best thing to do is to work out all of the external activities that you want to be alerted to. For example, so far in your question you've listed network transmits, network receives, and user activity.
Depending on the number of concurrent connections you're going to be dealing with you'll probably find it conceptually simpler to have a thread per socket (assuming small numbers of sockets), where each thread is responsible for all of the processing for that socket.
Then you can implement some form of messaging system between your threads as RC suggested.
Arrange your system so that when a message is sent to a particular thread and event is also sent. Your threads can then be sent to sleep waiting for one of those events. (as well as any other stimulus - like socket events, user events etc.)
You're quite right that you need to be careful of situations where more than one thread is trying to access the same piece of memory. Mutexes and semaphores are the things to use there.
Also be aware of the limitations that your gui has when it comes to multithreading.
Some discussion on the subject can be found [in this question](https://stackoverflow.com/questions/120636/best-practice-regarding-number-of-threads-in-gui-applications).
But the abbreviated version is that most (and Windows is one of these) GUIs don't allow multiple threads to perform GUI operations simultaneously. To get around this problem you can make use of the message pump in your application, by sending custom messages to your gui thread to get *it* to perform gui operations.
|
Network Multithreading
|
[
"",
"c++",
"multithreading",
"networking",
""
] |
I'm writing a WinForms application and one of the tabs in my TabControl has a SplitContainer. I'm saving the SplitterDistance in the user's application settings, but the restore is inconsistent. If the tab page with the splitter is visible, then the restore works and the splitter distance is as I left it. If some other tab is selected, then the splitter distance is wrong.
|
I found the problem. Each tab page doesn't get resized to match the tab control until it gets selected. For example, if the tab control is 100 pixels wide in the designer, and you've just set it to 500 pixels during load, then setting the splitter distance to 50 on a hidden tab page will get resized to a splitter distance of 250 when you select that tab page.
I worked around it by recording the SplitterDistance and Width properties of the SplitContainer in my application settings. Then on restore I set the SplitterDistance to recordedSplitterDistance \* Width / recordedWidth.
|
There`s a more easy solution. If Panel1 is set as the fixed panel in SplitContainer.FixedPanel property it all behaves as expected.
|
Restoring SplitterDistance inside TabControl is inconsistent
|
[
"",
"c#",
".net",
"winforms",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.