Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
As I understand XPath, it is a way to navigate through elements in an XML document.
The direction is XPath -> element.
How do you go the other way around? That is, compute the XPath from a known element value?
For example, how would you find the xpath of the "faq" link in the stackoverflow header ?
Language is not that important, I am more interested in the algorithm and/or libraries/techniques that would help me compute the XPath. | Here's a simple JS function to do it. It uses only previousSibling, nodeType, and parentNode, so it should be portable to other languages. However, the result is not readable (for humans), and it will not be particularly robust in the face of page changes.
In my experience, XPath is more useful if written by hand. However, you can certainly make an algorithm that will generate prettier (if probably slower) results.
```
function getXPath(node)
{
if(node == document)
return "/";
var xpath = "";
while (node != null && node.nodeType != Node.DOCUMENT_NODE)
{
print(node.nodeType);
var pos = 1, prev;
while ((prev = node.previousSibling) != null)
{
node = prev
pos++;
}
xpath = "/node()[" + pos + "]" + xpath;
node = node.parentNode;
}
return xpath;
}
``` | Since XPath can select the n'th child element (ie /parentelement/child\_element[2]), if you can figure out where in the tree the element is, then you should be able to generate an XPath back to it. | Is there a way to compute an XPath from a known value in a web page? | [
"",
"javascript",
"xpath",
""
] |
I've got a minimal app I just created, using VS 2008 SP1 on Vista x64. Its a Console app, created with the wizard, no MFC or anything, I'm building it in 64bit.
When I run the debug exe, on my development box, by pressing F5 in Visual Studio 2008, I get this error:
```
TestApp.exe - Unable To Locate Component
This application has failed to start because MSVCR90.dll was not found.
Re-installing the application may fix this problem.
OK
```
I don't get this error when I run the release exe, it works as expected.
This problem started when I added some include dependencies on iostream and fstream and started calling some winsock API calls.
Any suggestions?
UPDATE: I copied msvcr90.dll (not msvcrd90.dll) into the correct folder, and now I get a different error:
---
## Microsoft Visual C++ Runtime Library
Runtime Error!
Program: [snip]...
R6034
An application has made an attempt to load the C runtime library incorrectly.
Please contact the application's support team for more information.
---
## OK
* Alex | Thanks again for all the help with this. It turns out I'd just made a mistake and not noticed that a library I was using was statically linked against a different version of the MSVC runtime. That was causing on end of problems. | You application is using the DLL CRT runtime. The machine you want to run it on requires the installation of the debug CRT runtime dll's (which is a pain in the ass...). I think the better solution is to change the compile options to use the static linked CRT runtime (that means the runtime is linked into your application instead of using the DLL version).
In visual studio go into the Properites for your project then select the Configuration Properties / C++ / Code Generation and change the "Runtime Library" from "multi-threaded debug dll" to "multi-threaded debug".
You may like to do the same for the release build as well because some versions of the OS will not come with the V9 release CRT libraries pre-installed, or you can include the v9 release crt dll as part of your install. | VS2008 C++ app fails to start in Debug mode: This application has failed to start because MSVCR90.dll was not found | [
"",
"c++",
"visual-studio-2008",
"64-bit",
""
] |
I'm working on an application that processes audio data.
I'm using java (I've added MP3SPI, Jlayer, and Tritonus). I'm extracting the audio data from a .wav file to a byte array. The audio data samples I'm working with are 16 bits stereo.
According to what I've read the format for one sample is:
AABBCCDD
where AABB represents left channel and CCDD rigth channel (2 bytes for each channel).
I'd need to convert this sample into a double value type. I've reading about data format. Java uses Big endian, .wav files use little endian. I'm a little bit confused. Could you please help me with the conversion process?
Thanks you all | Warning: integers and bytes are signed. Maybe you need to mask the low bytes when packing them together:
```
for (int i =0; i < length; i += 4) {
double left = (double)((bytes [i] & 0xff) | (bytes[i + 1] << 8));
double right = (double)((bytes [i + 2] & 0xff) | (bytes[i + 3] << 8));
... your code here ...
}
``` | When you use the ByteBuffer ([java.nio.ByteBuffer](http://java.sun.com/javase/7/docs/api/)) you can use the method order;
[order]
public final ByteBuffer order(ByteOrder bo)
```
Modifies this buffer's byte order.
Parameters:
bo - The new byte order, either BIG_ENDIAN or LITTLE_ENDIAN
Returns:
This buffer
```
After this you can get the above mentioned values with;
getChar()
getShort()
getInt()
getFloat()
getDouble()
What a great language is Java ;-) | How to convert a .WAV audio data sample into an double type? | [
"",
"java",
"audio",
"signal-processing",
"wav",
"sampling",
""
] |
I am writing a tag-based ASP.net system. Using the following db scheme:
`Topic <many-many> TagTopicMap <many-many> Tag`
Basically it is a 3NF approach (toxi) that I found from the following: <http://www.pui.ch/phred/archives/2005/04/tags-database-schemas.html>
Here is the code snippet I have:
```
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Topic>(t => t.TagTopicMaps);
options.LoadWith<TagTopicMap>(tt => tt.Tag);
var db = new lcDbDataContext();
db.LoadOptions = options;
db.Log = w;
var x = from topic in db.Topics
orderby topic.dateAdded descending
select topic;
ViewData["TopicList"] = x.Take(10);
```
When I execute this, the result is fine, but it comes up with 11 single SQL queries, one for getting the list of top 10 topics:
```
SELECT TOP (10) [t0].[Id], [t0].[title], [t0].[dateAdded]
FROM [dbo].[Topics] AS [t0] ORDER BY [t0].[dateAdded] DESC
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1
```
And 10 of those other for getting details of the tags individually.
I tried to switch the two loadwith statements on and off, and found the following things happen:
```
loadwith<topic> : no difference for on or off.
loadwith<tagtopicmap>: 11 Queries when on, much more when off.
```
In short, ONLY the second loadwith option is working as expected. The first one doesn't have any effect!
I also tried to make the resultset ToList(). But even more problem coming out: for the tags detail part, it only retrieve those UNIQUE items, all those repeating tags (that same tag might appear in a number of topic, of course!) are dropped by the query.
One last thing, following is the code I used in aspx to retrieve the data, in case of making the result tolist(), I change (IQueryable) to (IList):
```
<% foreach (var t in (IQueryable)ViewData["TopicList"])
{
var topic = (Topic)t;
%>
<li>
<%=topic.title %> ||
<% foreach (var tt in (topic.TagTopicMaps))
{ %>
<%=tt.Tag.Name%>,
<%} %>
</li>
<%
}
%>
``` | The short answer is: LinqToSql has several quirks like this, and sometimes you have to use work-arounds...
The Linq2Sql LoadWith option simply causes an inner join between the database tables, so you can force similar behavior by rewritting your Linq statement to something like (please forgive any typos, I'm used to writting Linq in VB syntax...):
```
var x = from topic in db.Topics
join topicMap in topic.TagTopicMaps
orderby topic.dateAdded descending
group topicMap by topicMap.topic into tags = Group;
```
This syntax may be horribly wrong, but the basic idea is that you force Linq2Sql to evaluate the join between Topics and TagTopicMaps, and then use grouping (or "group join", "let", etc.) to preserve the object heirarchy in the result set. | Set the EnabledDefferedLoad on your datacontext class to false. | LINQ options.loadwith problem | [
"",
"c#",
"linq",
"linq-to-sql",
"3nf",
""
] |
I'm using **Python 2** to parse JSON from **ASCII encoded** text files.
When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I have to use the data with some libraries that only accept string objects. I *can't change the libraries* nor update them.
Is it possible to get string objects instead of Unicode ones?
### Example
```
>>> import json
>>> original_list = ['a', 'b']
>>> json_list = json.dumps(original_list)
>>> json_list
'["a", "b"]'
>>> new_list = json.loads(json_list)
>>> new_list
[u'a', u'b'] # I want these to be of type `str`, not `unicode`
```
(One easy and clean solution for 2017 is to use a recent version of Python — i.e. **Python 3** and forward.) | ### A solution with `object_hook`
It works for both Python 2.7 **and** 3.x.
```
import json
def json_load_byteified(file_handle):
return _byteify(
json.load(file_handle, object_hook=_byteify),
ignore_dicts=True
)
def json_loads_byteified(json_text):
return _byteify(
json.loads(json_text, object_hook=_byteify),
ignore_dicts=True
)
def _byteify(data, ignore_dicts = False):
if isinstance(data, str):
return data
# If this is a list of values, return list of byteified values
if isinstance(data, list):
return [ _byteify(item, ignore_dicts=True) for item in data ]
# If this is a dictionary, return dictionary of byteified keys and values
# but only if we haven't already byteified it
if isinstance(data, dict) and not ignore_dicts:
return {
_byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
for key, value in data.items() # changed to .items() for Python 2.7/3
}
# Python 3 compatible duck-typing
# If this is a Unicode string, return its string representation
if str(type(data)) == "<type 'unicode'>":
return data.encode('utf-8')
# If it's anything else, return it in its original form
return data
```
Example usage:
```
>>> json_loads_byteified('{"Hello": "World"}')
{'Hello': 'World'}
>>> json_loads_byteified('"I am a top-level string"')
'I am a top-level string'
>>> json_loads_byteified('7')
7
>>> json_loads_byteified('["I am inside a list"]')
['I am inside a list']
>>> json_loads_byteified('[[[[[[[["I am inside a big nest of lists"]]]]]]]]')
[[[[[[[['I am inside a big nest of lists']]]]]]]]
>>> json_loads_byteified('{"foo": "bar", "things": [7, {"qux": "baz", "moo": {"cow": ["milk"]}}]}')
{'things': [7, {'qux': 'baz', 'moo': {'cow': ['milk']}}], 'foo': 'bar'}
>>> json_load_byteified(open('somefile.json'))
{'more json': 'from a file'}
```
### How does this work and why would I use it?
[Mark Amery's function](https://stackoverflow.com/a/13105359/1709587) is shorter and clearer than these ones, so what's the point of them? Why would you want to use them?
Purely for **performance**. Mark's answer decodes the JSON text fully first with Unicode strings, then recurses through the entire decoded value to convert all strings to byte strings. This has a couple of undesirable effects:
* A copy of the entire decoded structure gets created in memory
* If your JSON object is *really* deeply nested (500 levels or more) then you'll hit Python's maximum recursion depth
This answer mitigates both of those performance issues by using the `object_hook` parameter of `json.load` and `json.loads`. From [the documentation](https://docs.python.org/2/library/json.html#json.load):
> `object_hook` is an optional function that will be called with the result of any object literal decoded (a `dict`). The return value of object\_hook will be used instead of the `dict`. This feature can be used to implement custom decoders
Since dictionaries nested many levels deep in other dictionaries get passed to `object_hook` *as they're decoded*, we can byteify any strings or lists inside them at that point and avoid the need for deep recursion later.
Mark's answer isn't suitable for use as an `object_hook` as it stands, because it recurses into nested dictionaries. We prevent that recursion in this answer with the `ignore_dicts` parameter to `_byteify`, which gets passed to it at all times *except* when `object_hook` passes it a new `dict` to byteify. The `ignore_dicts` flag tells `_byteify` to ignore `dict`s since they already been byteified.
Finally, our implementations of `json_load_byteified` and `json_loads_byteified` call `_byteify` (with `ignore_dicts=True`) on the result returned from `json.load` or `json.loads` to handle the case where the JSON text being decoded doesn't have a `dict` at the top level. | While there are some good answers here, I ended up using [PyYAML](http://pyyaml.org/) to parse my JSON files, since it gives the keys and values as `str` type strings instead of the `unicode` type. Because JSON is a subset of [YAML](https://en.wikipedia.org/wiki/YAML), it works nicely:
```
>>> import json
>>> import yaml
>>> list_org = ['a', 'b']
>>> list_dump = json.dumps(list_org)
>>> list_dump
'["a", "b"]'
>>> json.loads(list_dump)
[u'a', u'b']
>>> yaml.safe_load(list_dump)
['a', 'b']
```
### Notes
Some things to note though:
* I get *string objects* because all my entries are **ASCII encoded**. If I would use Unicode encoded entries, I would get them back as *unicode objects* — there is no conversion!
* You should (probably always) use PyYAML's `safe_load` function; if you use it to load JSON files, you don't need the "additional power" of the `load` function anyway.
* If you want a YAML parser that has more support for the 1.2 version of the spec (and [correctly parses very low numbers](https://stackoverflow.com/questions/30458977/yaml-loads-5e-6-as-string-and-not-a-number)) try [Ruamel YAML](https://bitbucket.org/ruamel/yaml): `pip install ruamel.yaml` and `import ruamel.yaml as yaml` was all I needed in my tests.
### Conversion
As stated, there isn't any conversion! If you can't be sure to only deal with ASCII values (and you can't be sure most of the time), better use a **conversion function**:
I used the one [from Mark Amery](https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python/13105359#13105359) a couple of times now, it works great and is very easy to use. You can also use a similar function as an `object_hook` instead, as it might gain you a performance boost on big files. See the slightly more involved [answer from Mirec Miskuf](https://stackoverflow.com/a/33571117/11666) for that. | How to get string objects instead of Unicode from JSON | [
"",
"python",
"json",
"serialization",
"unicode",
"python-2.x",
""
] |
I tend to use ArrayLists of structures. It is then very easy to cycle through the list with a foreach.
The problem I have is I cant use a foreach to modify the structures contents and have to use a for and messy typecasts.
```
((dataStructure)files[x]).name = here;
```
Is there a tidier way to do it? | I know this sounds simplistic but **[just say no to mutable value types](https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil)**.
They're almost *never* the right solution to the problem. There are a *very* few exceptions, but classes are almost *always* the way to go.
In addition, if you're really using an `ArrayList` then you'll be incurring an unboxing cost already... (As Konrad says, if you can use .NET 2.0 then use generics.)
If you really insist on using mutable structures, then use a `for` loop instead of `foreach`. But please, please change to classes anyway. | Yes, there is: don't use an untyped `ArrayList`, these types are deprecated in favour of the generic types in `System.Collections.Generic`. In your case: [`List<T>`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).
You still can't use it in conjunction with a `foreach` loop to modify structure values but at least you don't have to cast. | Modify contents in foreach | [
"",
"c#",
"arraylist",
"structure",
"casting",
""
] |
I'm writing a custom tracelistener to write trace messages to a file adding rotation (for example changing the file name each day).
In the override of the `Flush` method, I call `Flush` on the underlying `StreamWriter`, but if I set `autoflush='false'` in the application configuration, `Flush` does not get called when the application is terminated.
What is the correct method to finalize a custom trace listener when the application exits?
EDIT: I overrode the `Dispose(bool disposing)` method, since the base `TraceListener` class already implements the disposable pattern, but, as far as I can say, the method is not called. If I implement an explicit destructor, the destructor is called, but at that point I shouldn't assume that the stream reference is still valid, right? | if your software does not call to Trace.Close on termination then you cannot ensure any flush is done.
See [this article](https://web.archive.org/web/20200111044134/http://geekswithblogs.net:80/akraus1/articles/81629.aspx) for more details. | I would suggest that you do this in the dispose method of your custom `TraceListener` class just before you close the underlying `StreamWriter`. | Finalizing a custom TraceListener with autoflush='false' (C#, .net) | [
"",
"c#",
".net",
"configuration",
"trace",
""
] |
I have an input box inside and iframe. If i type and press the back key to erase the text, the back key event is taken as browser back and goes to the previous page. What could be the cause.? | please tell which browser you have tested with.
My guess would be that you have focus outside the field? is there a script putting focus on the document containing ths input box in the iframe? | i even cann't raise same event. I press BackSpace in iframe, I press BackSpace in input, I press BackSpace in main page.
Which browser do you work with?
Is there any javascript code in the page? | Input Box inside an iframe | [
"",
"javascript",
"browser",
"iframe",
""
] |
I'm trying to write a class that when asked on, will call on a class and make it into a class member. Here's a quick example of what I mean:
```
class foo{
myClass Class;
foo();
};
foo::foo()
{
//Create the class and set it as the foo::Class variable
}
```
I'm sure this is actually an easy thing to do. Any help would be appreciated
Thanks
**Edit:** Sorry for the bad terminology. I'll try to go over what I want to do more concisely. I'm creating a class(*foo*), that has a varaible(*Class*) with the class definition of (*myClass*). I need to create a *myClass* object and assign it to *Class*, with-in the class *foo*. Through the help of everyone, I have kind of achieved this.
My problem now is that the object I created gives me a "Unhandled Exception"..."Access violation reading location 0x000000c0" in *Class*, on the first line of *myClass*'s function that I'm trying to execute. *Thanks for your help!*
*note:* I'm currently using emg-2's solution. | There is no need to do anything. Assuming that myClass has a default constructor, it will be used to construct the Class (you could use better names here, you know) instance for you. If you need to pass parameters to the constructor, use an initialisation list:
```
foo :: foo() : Class( "data" ) {
}
``` | If you only want to composite, use Neil solution. If you want an aggregation (i.e. you will assign outside objects to myClass\*Class), you should use a pointer:
```
class foo{
myClass * Class;
void createClass();
};
// can't use name foo, because its a name reserved for a constructor
void foo::createClass() {
Class = new myClass();
}
``` | Calling a class inside a class | [
"",
"c++",
"class",
""
] |
I am writing a SharePoint timer job, which needs to pull the content of a web page, and send that HTML as an email.
I am using HttpWebRequest and HttpWebResponse objects to pull the content.
The emailing functionality works fine except for one problem.
The web page which serves up the content of my email contains images.
When the html of the page is sent as an email, the image URLs inside the HTML code are all relative URLs, they are not resolved as an absolute URL.
How do i resolve the image URLs to their absolute paths inside the web page content?
Is there any straight forward way to do this? I don't want to run a Regex over the html code to replace all relative URLs with absolute URLS. | Found this cool Codeplex tool called HtmlAgilityPack.
<http://www.codeplex.com/htmlagilitypack>
Using this API, we can parse Html like we can parse XML documents. We can also query and search nodes using XPath.
I used the following code snippet to fix the Image URLs
```
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlMessage);
//This selects all the Image Nodes
HtmlNodeCollection hrefNodes = htmlDoc.DocumentNode.SelectNodes("//img");
foreach (HtmlNode node in hrefNodes)
{
string imgUrl = node.Attributes["src"].Value;
node.Attributes["src"].Value = webAppUrl + imgUrl;
}
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
htmlDoc.OptionOutputAsXml = false;
htmlDoc.Save(sw);
htmlMessage = sb.ToString();
``` | Try adding a [`base`](http://www.w3.org/TR/REC-html40/struct/links.html#h-12.4) element to the head of the html document you retrieve. As `href` attribute you should use the url of the page you are retrieving. | Sending a web page by email programmatically. Image URLs not resolved | [
"",
"c#",
"asp.net",
"email",
""
] |
How can I implement a bipartite matching algorithm (probably based on a max-flow algorithm) in C or C++ ?
To be specific, I have this input in a file:
(1,3)
(1,5)
(2,5)
(M,F) --> where M represents id of MALE and F is id of FEMALE.
I need to find the maximum number of matches and show matched couples.
Like:
matches: 1&3 , 2&5
I have read in some books I can base this problem on a "maximum flow in a network" algorithm, but I couldn't find any specific info other than the sentence "this problem can be solved by .... algorithm".
I have little knowledge about max-flow, and dont know how to implement it either... | Yes, bipartite matching can be reduced to maximum flow:
1. You're given sets of nodes `M` and `F`. Add a directed edge from a node `m` in `M` to a node `f` in `F` if you've got the pair `(m, f)` in your file.
2. Add a single node `S` with a directed edge from `S` to every node in `M` (this is your "super-source" node).
3. Add a single node `T` with a directed edge from every node in `F` to `T` (this is your "super-sink" node).
4. Now, you need to find the maximum flow (with all your edges of weight 1) from `S` to `T`.
So what the heck is maximum flow? A *flow* from `S` to `T` is a set of edges such that for each node (except `S` and `T`), the weight of its *in-flux* edges is the same as the weight of its *out-flux* edges. Imagine that your graph is a series of pipes, and you're pouring water in the system at `S` and letting it out at `T`. At every node in between, the amount of water going in has to be the same as the amount of water coming out.
Try to convince yourself that a flow corresponds to a matching of your original sets. (Given a flow, how to you get a matching? Given a matching, how to you get a flow?)
Finally, to find the maximum flow in a graph, you can use the [Ford-Fulkerson algorithm](http://en.wikipedia.org/wiki/Ford-Fulkerson_algorithm). The above wikipedia page gives a good description of it, with pseudo-code. | Yes, if you already have code to solve the max-flow problem, you can use it to solve bipartite matching by transforming the graph as shown towards the end of [this](http://oucsace.cs.ohiou.edu/~razvan/courses/cs404/lecture21.pdf) lecture, but that's probably not the right approach if you are starting from scratch. If you just want to implement some fairly simple code to solve the problem for examples that don't get too huge, you are better off using a simple augmenting path approach as outlined [here](http://www.maths.lse.ac.uk/Courses/MA314/matching.pdf). That gives you an O(|V||E|) approach that is pretty easy to code and adequate for all but very large graphs. If you want something with better worst-case performance, you could try the [Hopcraft-Karp](http://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm) algorithm, which finds multiple augmenting paths at once and has a O(sqrt(|V|)|E|) run time bound, but the Wikipedia article on it notes that:
> Several authors have performed
> experimental comparisons of bipartite
> matching algorithms. Their results in
> general tend to show that the
> Hopcroft–Karp method is not as good in
> practice as it is in theory: it is
> outperformed both by simpler
> breadth-first and depth-first
> strategies for finding augmenting
> paths, and by push-relabel
> techniques.
In any case, you should definitely understand and be able to implement a simple augmenting-path approach before trying to tackle either Hopcraft-Karp or one of the push-relable techniques mentioned in the references of the Wikipedia article.
Edit: For some reason, the links above aren't showing up correctly. Here are the URLs in question: (<http://oucsace.cs.ohiou.edu/~razvan/courses/cs404/lecture21.pdf>), (<http://www.maths.lse.ac.uk/Courses/MA314/matching.pdf>), and (<http://en.wikipedia.org/wiki/Hopcroft>–Karp\_algorithm). | Bipartite Matching | [
"",
"c++",
"c",
"algorithm",
"graph",
"matching",
""
] |
This warning is triggered multiple times in my code by the same declaration, which reads :
```
// Spreadsheet structure
typedef struct SPREADSHEET
{
int ID; // ID of the spreadsheet
UINT nLines; // Number of lines
void CopyFrom(const SPREADSHEET* src)
{
ID = src->ID;
nLines = src->nLines;
}
};
```
I don't want to just turn off that warning,
but rather change the code so that the warning doesn't come up !
NOTE : I don't want to declare any variables here (it's a header file), only define what the struct 'SPREADSHEET' should include... | Delete `typedef`. It's the C way of declaring structs, C++ does it automatically for you. | **If you use same header for both C and C++**, you need to add some identifier before the terminating "`;`", something like:
```
typedef struct BLAH { ... } BLAH;
```
**But** if you use it only for C++, instead simply remove "`typedef` " part (and don't add identifier before the terminating "`;`", as without "`typedef` " part that creates a variable).
---
Also, you may want to edit C-only-headers and wrap everything in `extern "C" { ... }`, to support C++, like:
```
#ifndef MY_HEADER_H
#define MY_HEADER_H
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// ... Content: Includes and Type-defs go here ...
#ifdef __cplusplus
} // extern C
#endif // __cplusplus
#endif // MY_HEADER_H
```
> I mean, else each C++ file which includes your C-only-header needs to wrap separately. | How can I remove the VS warning C4091: 'typedef ' : ignored on left of 'SPREADSHEET' when no variable is declared | [
"",
"c++",
"compiler-construction",
"struct",
"typedef",
"warnings",
""
] |
In [Code Complete 2](https://rads.stackoverflow.com/amzn/click/com/0735619670) (page 601 and 602) there is a table of "Cost of Common Operations".
The baseline operation integer assignment is given a value 1 and then the relative time for common operations is listed for Java and C++. For example:
```
C++ Java
Integer assignment 1 1
Integer division 5 1.5
Floating point square root 15 4
```
The question is has anyone got this data for C#? I know that these won't help me solve any problems specifically, I'm just curious. | Straight from the source, **[Know what things cost](http://msdn.microsoft.com/en-us/library/ms973852.aspx)**.
IIRC Rico Mariani had relative measures as the ones you asked for [on his blog](http://blogs.msdn.com/ricom/default.aspx), I can't find it anymore, though (I know it's in one of thoe twohudnred "dev" bookmarks...) | I implemented some of the tests from the book. Some raw data from my computer:
Test Run #1:
TestIntegerAssignment 00:00:00.6680000
TestCallRoutineWithNoParameters 00:00:00.9780000
TestCallRoutineWithOneParameter 00:00:00.6580000
TestCallRoutineWithTwoParameters 00:00:00.9650000
TestIntegerAddition 00:00:00.6410000
TestIntegerSubtraction 00:00:00.9630000
TestIntegerMultiplication 00:00:00.6490000
TestIntegerDivision 00:00:00.9720000
TestFloatingPointDivision 00:00:00.6500000
TestFloatingPointSquareRoot 00:00:00.9790000
TestFloatingPointSine 00:00:00.6410000
TestFloatingPointLogarithm 00:00:41.1410000
TestFloatingPointExp 00:00:34.6310000
Test Run #2:
TestIntegerAssignment 00:00:00.6750000
TestCallRoutineWithNoParameters 00:00:00.9720000
TestCallRoutineWithOneParameter 00:00:00.6490000
TestCallRoutineWithTwoParameters 00:00:00.9750000
TestIntegerAddition 00:00:00.6730000
TestIntegerSubtraction 00:00:01.0300000
TestIntegerMultiplication 00:00:00.7000000
TestIntegerDivision 00:00:01.1120000
TestFloatingPointDivision 00:00:00.6630000
TestFloatingPointSquareRoot 00:00:00.9860000
TestFloatingPointSine 00:00:00.6530000
TestFloatingPointLogarithm 00:00:39.1150000
TestFloatingPointExp 00:00:33.8730000
Test Run #3:
TestIntegerAssignment 00:00:00.6590000
TestCallRoutineWithNoParameters 00:00:00.9700000
TestCallRoutineWithOneParameter 00:00:00.6680000
TestCallRoutineWithTwoParameters 00:00:00.9900000
TestIntegerAddition 00:00:00.6720000
TestIntegerSubtraction 00:00:00.9770000
TestIntegerMultiplication 00:00:00.6580000
TestIntegerDivision 00:00:00.9930000
TestFloatingPointDivision 00:00:00.6740000
TestFloatingPointSquareRoot 00:00:01.0120000
TestFloatingPointSine 00:00:00.6700000
TestFloatingPointLogarithm 00:00:39.1020000
TestFloatingPointExp 00:00:35.3560000
(1 Billion Tests Per Benchmark, Compiled with Optimize, AMD Athlon X2 3.0ghz, using Jon Skeet's microbenchmarking framework available at <http://www.yoda.arachsys.com/csharp/benchmark.html>)
Source:
```
class TestBenchmark
{
[Benchmark]
public static void TestIntegerAssignment()
{
int i = 1;
int j = 2;
for (int x = 0; x < 1000000000; x++)
{
i = j;
}
}
[Benchmark]
public static void TestCallRoutineWithNoParameters()
{
for (int x = 0; x < 1000000000; x++)
{
TestStaticRoutine();
}
}
[Benchmark]
public static void TestCallRoutineWithOneParameter()
{
for (int x = 0; x < 1000000000; x++)
{
TestStaticRoutine2(5);
}
}
[Benchmark]
public static void TestCallRoutineWithTwoParameters()
{
for (int x = 0; x < 1000000000; x++)
{
TestStaticRoutine3(5,7);
}
}
[Benchmark]
public static void TestIntegerAddition()
{
int i = 1;
int j = 2;
int k = 3;
for (int x = 0; x < 1000000000; x++)
{
i = j + k;
}
}
[Benchmark]
public static void TestIntegerSubtraction()
{
int i = 1;
int j = 6;
int k = 3;
for (int x = 0; x < 1000000000; x++)
{
i = j - k;
}
}
[Benchmark]
public static void TestIntegerMultiplication()
{
int i = 1;
int j = 2;
int k = 3;
for (int x = 0; x < 1000000000; x++)
{
i = j * k;
}
}
[Benchmark]
public static void TestIntegerDivision()
{
int i = 1;
int j = 6;
int k = 3;
for (int x = 0; x < 1000000000; x++)
{
i = j/k;
}
}
[Benchmark]
public static void TestFloatingPointDivision()
{
float i = 1;
float j = 6;
float k = 3;
for (int x = 0; x < 1000000000; x++)
{
i = j / k;
}
}
[Benchmark]
public static void TestFloatingPointSquareRoot()
{
double x = 1;
float y = 6;
for (int x2 = 0; x2 < 1000000000; x2++)
{
x = Math.Sqrt(6);
}
}
[Benchmark]
public static void TestFloatingPointSine()
{
double x = 1;
float y = 6;
for (int x2 = 0; x2 < 1000000000; x2++)
{
x = Math.Sin(y);
}
}
[Benchmark]
public static void TestFloatingPointLogarithm()
{
double x = 1;
float y = 6;
for (int x2 = 0; x2 < 1000000000; x2++)
{
x = Math.Log(y);
}
}
[Benchmark]
public static void TestFloatingPointExp()
{
double x = 1;
float y = 6;
for (int x2 = 0; x2 < 1000000000; x2++)
{
x = Math.Exp(6);
}
}
private static void TestStaticRoutine() {
}
private static void TestStaticRoutine2(int i)
{
}
private static void TestStaticRoutine3(int i, int j)
{
}
private static class TestStaticClass
{
}
``` | Cost of common operations for C#? | [
"",
"c#",
"performance",
"optimization",
"operators",
""
] |
Can I do that thing that twitter and many other sites do where a url shows a users page.
www.mysite.com/the\_user\_name
In php... or how does one do it? | Look into how to use [the mod\_rewrite module in .htaccess](https://stackoverflow.com/questions/623161/help-with-basic-htaccess-modrewrite).
Here's some ALA goodness:
1. [How to Succeed With URLs](http://www.alistapart.com/articles/succeed/)
2. [URLS! URLS! URLS!](http://www.alistapart.com/articles/urls/) | The easiest method would be to use [`mod_rewrite`](http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html) in Apache (as opposed to doing it in PHP). Here's a good [beginner's guide](http://www.workingwith.me.uk/articles/scripting/mod_rewrite). | Can I do use a direct URL like twitter or myspace in PHP | [
"",
"php",
"html",
"url",
""
] |
I have a database table structured like this (irrelevant fields omitted for brevity):
```
rankings
------------------
(PK) indicator_id
(PK) alternative_id
(PK) analysis_id
rank
```
All fields are integers; the first three (labeled "(PK)") are a composite primary key. A given "analysis" has multiple "alternatives", each of which will have a "rank" for each of many "indicators".
I'm looking for an efficient way to compare an arbitrary number of analyses whose ranks for any alternative/indicator combination differ. So, for example, if we have this data:
```
analysis_id | alternative_id | indicator_id | rank
----------------------------------------------------
1 | 1 | 1 | 4
1 | 1 | 2 | 6
1 | 2 | 1 | 3
1 | 2 | 2 | 9
2 | 1 | 1 | 4
2 | 1 | 2 | 7
2 | 2 | 1 | 4
2 | 2 | 2 | 9
```
...then the ideal method would identify the following differences:
```
analysis_id | alternative_id | indicator_id | rank
----------------------------------------------------
1 | 1 | 2 | 6
2 | 1 | 2 | 7
1 | 2 | 1 | 3
2 | 2 | 1 | 4
```
I came up with a query that does what I want for 2 analysis IDs, but I'm having trouble generalizing it to find differences between an arbitrary number of analysis IDs (i.e. the user might want to compare 2, or 5, or 9, or whatever, and find any rows where at least one analysis differs from any of the others). My query is:
```
declare @analysisId1 int, @analysisId2 int;
select @analysisId1 = 1, @analysisId2 = 2;
select
r1.indicator_id,
r1.alternative_id,
r1.[rank] as Analysis1Rank,
r2.[rank] as Analysis2Rank
from rankings r1
inner join rankings r2
on r1.indicator_id = r2.indicator_id
and r1.alternative_id = r2.alternative_id
and r2.analysis_id = @analysisId2
where
r1.analysis_id = @analysisId1
and r1.[rank] != r2.[rank]
```
(It puts the analysis values into additional fields instead of rows. I think either way would work.)
How can I generalize this query to handle many analysis ids? (Or, alternatively, come up with a different, better query to do the job?) I'm using SQL Server 2005, in case it matters.
If necessary, I can always pull all the data out of the table and look for differences in code, but a SQL solution would be preferable since often I'll only care about a few rows out of thousands and there's no point in transferring them all if I can avoid it. (However, if you have a compelling reason not to do this in SQL, say so--I'd consider that a good answer too!) | This will return your desired data set - Now you just need a way to pass the required analysis ids to the query. Or potentially just filter this data inside your application.
```
select r.* from rankings r
inner join
(
select alternative_id, indicator_id
from rankings
group by alternative_id, indicator_id
having count(distinct rank) > 1
) differ on r.alternative_id = differ.alternative_id
and r.indicator_id = differ.indicator_id
order by r.alternative_id, r.indicator_id, r.analysis_id, r.rank
``` | I don't know wich database you are using, in SQL Server I would go like this:
```
-- STEP 1, create temporary table with all the alternative_id , indicator_id combinations with more than one rank:
select alternative_id , indicator_id
into #results
from rankings
group by alternative_id , indicator_id
having count (distinct rank)>1
-- STEP 2, retreive the data
select a.* from rankings a, #results b
where a.alternative_id = b.alternative_id
and a.indicator_id = b. indicator_id
order by alternative_id , indicator_id, analysis_id
```
BTW, THe other answers given here need the count(distinct rank) !!!!! | SQL: Find rows where field value differs | [
"",
"sql",
"sql-server",
""
] |
This should be a simple one but I'm looking for the best answer with at least some regard for performance as well as elegance.
I have a list of strings and *some* of the values are of the form q1, q2, q3 etc.
I'd like to select these.
What would be the best method of doing this? | Seems like you're trying to microoptimize, which means you'll spend a lot of effort to make your program run the same speed. Focus on clarity of code first, and then optimize what is actually slow.
**Assuming you have profiled and found this to be your application's bottleneck in real-world scenarios:**
It is inelegant (and often a performance drag) to use **exceptions in non-exceptional** cases. See <http://www.developerfusion.com/code/4650/validating-an-integer/>, for example.
Depending on the constraints of your situation, you're probably better off changing your `IsInteger()` to do one of:
```
bool int.TryParse(string s, out int result);
```
(See <http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx>)
or:
```
Microsoft.VisualBasic.Information.IsNumeric(object expression)
```
(See <http://www.hanselman.com/blog/ExploringIsNumericForC.aspx>)
or
```
x >= '0' && x < '9'
```
And then:
```
.Where(c => c[0] == 'q' && IsInteger(c[1]))
``` | The best answer is to use either Regex or [Jay Bazuzi's int.TryParse suggestion](https://stackoverflow.com/questions/850999/using-linq-how-do-you-filter-a-list-of-strings-for-values-that-match-the-pattern/851033#851033).
As a quick example try this in [LINQPad](http://www.linqpad.net/):
```
void Main()
{
int n = 100;
string[] a = {"q2", "q3", "b"};
a = a.Concat(Enumerable.Repeat(0,n).Select(i => "qasd")).ToArray(); /* Random data */
/* Regex Method */
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^q[0-9]+$");
List<string> regMethod = a.Where(c => r.IsMatch(c)).ToList().Dump("Result");
/* IsInteger Method */
List<string> intMethod = a.Where(c => c.StartsWith("q") && IsInteger(c.Substring(1))).ToList().Dump("Result");
/* int.TryParse Method suggest by Jay Bazuzi */
int e = 0;
List<string> parseMethod = a.Where(c => c.StartsWith("q") && int.TryParse(c.Substring(1), out e)).ToList().Dump("Result");
}
public static bool IsInteger(string theValue)
{
try
{
Convert.ToInt32(theValue);
return true;
}
catch
{
return false;
}
}
```
Try commenting one of the two methods out at a time and try out the performance for different values of n.
My experience (on my Core 2 Duo Laptop) seems to suggest:
```
n = 100. Regex takes about 0.003 seconds, IsInteger takes about 0.01 seconds
n = 1,000. Regex takes about 0.004 seconds, IsInteger takes about 0.07 seconds
n = 10,000. Regex takes about 0.007 seconds, IsInteger takes about 0.67 seconds
n = 100,000. Regex takes about 0.046 seconds, IsInteger takes about 6.9 seconds
n = 1,000,000. Regex takes about 0.42 seconds, IsInteger takes about 1 minute and 6 seconds
```
ParseMethod has the same performance as Regex (slightly faster if done inline as in the code sample, about the same if done in a separate method, i.e. replacing the IsInteger method body).
NB: The cost of creating the strings is not accounted for (insert a date diff if you like), but the cost is the same for both methods
These numbers are much closer if the majority of the keys do not being with 'q' (IsInteger is never called), but the Regex is as good or better *even when this is the case*
I.e. (for filler string of "asdasd" rather than "qasd"):
```
n = 100. Regex takes about 0.003 seconds, IsInteger takes about 0.003 seconds
n = 1,000. Regex takes about 0.004 seconds, IsInteger takes about 0.004 seconds
n = 10,000. Regex takes about 0.005 seconds, IsInteger takes about 0.005 seconds
n = 100,000. Regex takes about 0.023 seconds, IsInteger takes about 0.025 seconds
n = 1,000,000. Regex takes about 0.21 seconds, IsInteger takes about 0.22 seconds
```
Again ParseMethod has the same performance as Regex.
**Conclusion:** Use either Regex or the TryParse, it will be much faster in the worst case and as fast otherwise
However, are there better/quicker ways of selecting the int values out of a collection of strings? Perhaps a generic filter that is somehow compiled faster? | Using LINQ how do you filter a list of strings for values that match the pattern "q1, q2" etc.? | [
"",
"c#",
"linq",
""
] |
I'm almost sure the answer to this is "None at all!" but I'll ask anyway. If you have a conditional statement in PHP which echos a line of html, is there any difference performance-wise between these 2 examples:
```
<?php if ($output) { ?>
<h2><?=$output;?></h2>
<?php } ?>
```
and
```
<?php if ($output) { echo "<h2>".$output."</h2>"; } ?>
``` | The answer literally is "None at all". Consider
```
<span>
<?php
echo $myMessage;
?>
</span>
```
and
```
<?php
echo "<span>\n";
echo $myMessage;
echo "</span>";
?>
```
I'm going from memory (of a few years ago), but at that point the Zend bytecode compiler produces essentially identical output; "literal" HTML was compiled into an echo statement containing the text. | I don't think there is a noticeable performance difference.
I use whatever variant makes my code more readable. | is there any difference between echoing a line of output or closing the php tags and writing out the html code? | [
"",
"php",
"html",
""
] |
Currently I have a simple IRC bot written in python.
Since I migrated it to python 3.0 which differentiates between bytes and unicode strings I started having encoding issues. Specifically, with others not sending UTF-8.
Now, I could just tell everyone to send UTF-8 (which they should regardless) but an even better solution would be try to get python to default to some other encoding or such.
So far the code looks like this:
```
data = str(irc.recv(4096),"UTF-8", "replace")
```
Which at least doesn't throw exceptions. However, I want to go past it: I want my bot to default to another encoding, or try to detect "troublesome characters" somehow.
Additionally, I need to figure out what this mysterious encoding that mIRC uses actually is - as other clients appear to work fine and send UTF-8 like they should.
How should I go about doing those things? | Ok, after some research turns out chardet is having troubles with python 3. The solution as it turns out is simpler than I thought. I chose to fall back on CP1252 if UTF-8 doesn't cut it:
```
data = irc.recv ( 4096 )
try: data = str(data,"UTF-8")
except UnicodeDecodeError: data = str(data,"CP1252")
```
Which seems to be working. Though it doesn't detect the encoding, and so if somebody came in with an encoding that is neither UTF-8 nor CP1252 I will again have a problem.
This is really just a temporary solution. | [chardet](https://pypi.python.org/pypi/chardet) should help - it's the canonical Python library for detecting unknown encodings. | Python IRC bot and encoding issue | [
"",
"python",
"unicode",
"encoding",
"irc",
""
] |
In my epic quest of making C++ do things it shouldn't, I am trying to put together a compile time generated class.
Based on a preprocessor definition, such as (rough concept)
```
CLASS_BEGIN(Name)
RECORD(xyz)
RECORD(abc)
RECORD_GROUP(GroupName)
RECORD_GROUP_RECORD(foo)
RECORD_GROUP_RECORD(bar)
END_RECORDGROUP
END_CLASS
```
While I am fairly sure I generate a class that reads the data from the file system using this sort of structure (Maybe even doing it using Template Metaprogramming), I don't see how I can generate both the functions to access the data and the function to read the data.
I would want to end up with a class something like this
```
class Name{
public:
xyz_type getxyz();
void setxyz(xyz_type v);
//etc
list<group_type> getGroupName();
//etc
void readData(filesystem){
//read xyz
//read abc
//etc
}
};
```
Does anyone have any idea if this is even possible?
--EDIT--
To clarify the intended usage for this. I have files in a standard format I want to read. The format is defined already, so it is not open to change. Each file can contain any number records, each of which can contain any number sub records.
The numerous record types each contain a diffrent set of sub records, but they can be are defined. So for example the Heightmap record must contain a Heightmap, but can optional contain normals.
So I would want to define a Record for that like so:
```
CLASS_BEGIN(Heightmap)
RECORD(VHDT, Heightmap, std::string) //Subrecord Name, Readable Name, Type
RECORD_OPTIONAL(VNML, Normals, std::string)
END_CLASS
```
For which I would want to output something with the functionality of a class like this:
```
class Heightmap{
public:
std::string getHeightmap(){
return mHeightmap->get<std::string>();
}
void setHeightmap(std::string v){
mHeight->set<std::string>(v);
}
bool hasNormal(){
return mNormal != 0;
}
//getter and setter functions for normals go here
private:
void read(Record* r){
mHeightmap = r->getFirst(VHDT);
mNormal = r->getFirst(VNML);
}
SubRecord* mHeightmap, mNormal;
}
```
The issue I am having is that I need every preprocessor definition twice. Once for defining the function definition within the class, and once for creating the read function. As the preprocessor is purely functional, I cannot push the data to a queue and generate the class on the END\_CLASS marco definition.
I cannot see a way around this issue, but wondered if anyone who has a greater understanding of C++ did. | You might be able to solve this problem using boost [tuples](http://www.boost.org/doc/libs/1_39_0/libs/fusion/doc/html/index.html). It will result in a design which is different to what you are thinking of now, but it should allow you to solve the problem in a generic way.
The following example defines a record of the form "std::string,bool" and then reads that data in from a stream.
```
#include "boost/tuple/tuple.hpp"
#include <iostream>
#include <sstream>
using namespace ::boost::tuples;
```
The functions are used to read the data from an istream. The first overload stops the iteration through the tuple after we reach the last record type:
```
//
// This is needed to stop when we have no more fields
void read_tuple (std::istream & is, boost::tuples::null_type )
{
}
template <typename TupleType>
void read_tuple (std::istream & is, TupleType & tuple)
{
is >> tuple.template get_head ();
read_tuple (is, tuple.template get_tail ());
}
```
The following class implements the getter member for our Record. Using the RecordKind as our key we get the specific member that we're interested in.
```
template <typename TupleType>
class Record
{
private:
TupleType m_tuple;
public:
//
// For a given member - get the value
template <unsigned int MBR>
typename element <MBR, TupleType>::type & getMember ()
{
return m_tuple.template get<MBR> ();
}
friend std::istream & operator>> (std::istream & is
, Record<TupleType> & record)
{
read_tuple (is, record.m_tuple);
}
};
```
The next type is the meta description for our record. The enumeration gives us a symbolic name that we can use to access the members, ie. the field names. The tuple then defines the types of those fields:
```
struct HeightMap
{
enum RecordKind
{
VHDT
, VNML
};
typedef boost::tuple < std::string
, bool
> TupleType;
};
```
Finally, we construct a record and read in some data from a stream:
```
int main ()
{
Record<HeightMap::TupleType> heightMap;
std::istringstream iss ( "Hello 1" );
iss >> heightMap;
std::string s = heightMap.getMember < HeightMap::VHDT > ();
std::cout << "Value of s: " << s << std::endl;
bool b = heightMap.getMember < HeightMap::VNML > ();
std::cout << "Value of b: " << b << std::endl;
}
```
And as this is all template code, you should be able to have records nested in records. | If you are looking for a way to serialize/deserialize data with C++ code generation, I would look at Google protobufs (<http://code.google.com/p/protobuf/>) or Facebook's Thrift (<http://incubator.apache.org/thrift/>).
For protobufs, you write a data definition like so:
```
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
```
A Person C++ class is then generated that lets you load, save and access this data. You can also generate python, java, etc. | C++ Code Generation | [
"",
"c++",
"templates",
"c-preprocessor",
"code-generation",
""
] |
I have this question about best practices in following examples:
```
interface Request;
interface Service {
void process(Request request)
}
class MyService implements Service;
class YourService implements Service;
class MyRequest implements Request;
class YourRequest implements Request;
```
But how to ensure that `MyService` will always receive `MyRequest` and `YourService` will get `YourRequest` only, and not in the opposite way? Obvious answer "if-instance-of-check" in `MyService.process(...)` seems ugly and somehow against SOLID principles. Maybe there are better ways around?
Maybe generics would be good solution? (But then, how to use them in code that has to run under Java 1.4?) | If the design of the contract is that each Service can process any kind of Request, then your implementation of MyService , which only takes MyRequest (and breaks if other kinds of Requests are passed in), is wrong.
If the design of the contract is that Service and Request subclasses maps to each other, e.g., MyService can (and should) *only* process a MyRequest, then you will need to change the interface of Service. Otherwise, the current interface as written in the question does not do what the question describes it to do. One way to fix is to parameterize the Service interface:
```
interface Service<R> {
void process(R request);
}
```
then your concrete MyService will be
```
public class MyService implements Service<MyRequest> {
public void process (MyRequest r) {/*blah*/}
}
```
You can see an example of this in action in the JDK - the Comparator interface does exactly this, for exactly the same reason. <http://java.sun.com/javase/6/docs/api/java/util/Comparator.html>
I cant see why you would, but if you still want to restrict the hierachy of MyRequest to be a request, then you can swap `Service<R>` with `Service<R extends Request>`
edit: this obviously doesnt run in 1.4, so to do the same thing[1] , you will need to use a visitor pattern. Its uglier, but 1.4 is ugly =)
```
interface Service {
void process(Request visitor);
}
interface RequestVisitor {
void visitMyRequest(MyService service);
void visitYourRequest(YourService service);
void visitTheOtherRequest(TheOtherService service);
}
interface Request extends RequestVisitor { /* and any extra methods required for request*/ }
public class MyService implements Service {
public process(Request r) {r.visitMyRequest(this);}
public void doSpecialMyProcessing(MyRequest request) { /* your code using MyRequest*/ }
}
public class YourService implements Service {
public process(Request r) {r.visitYourRequest(this);}
public void doSpecialYourProcessing(YourRequest request) { /* your code using YourRequest */ }
}
public class MyRequest implements Request {
void visitMyRequest(MyService service) {
service.doSpecialMyProcessing(this);
}
void visitYourRequest(YourService service) {
throw new UnsupportedOperation("Cannot call visitYourRequest in MyRequest!");
}
void visitTheOtherRequest(TheOtherService service) {
throw new UnsupportedOperation("Cannot call visitTheOtherRequest in MyRequest!");
}
}
public class YourRequest implements Request {
void visitMyRequest(MyService service) {
throw new UnsupportedOperation("Cannot call visitMyRequest in YourRequest !");
}
void visitYourRequest(YourService service) {
service. doSpecialYourProcessing(this);
}
void visitTheOtherRequest(TheOtherService service) {
throw new UnsupportedOperation("Cannot call visitTheOtherRequest in YourRequest !");
}
}
```
[1] *actually its not the same*, because now you will need to write a method for each request subtype. In 1.4, you would have to cast and do instanceof etc, to achieve what 1.5 can do with generics. | Put simply, you are establishing an interface that you then don't want to adhere to, so it's not really an ideal design.
What I mean is, if MyService implements Service, then it must be able to take any kind of request. Otherwise it isn't following the defined contract.
I would question why you have the Service interface at all in this instance, and if you do need it (for other methods) whether it's appropriate for the process(Request request) method to be on there if subclasses are not going to honour it. | Interfaces declaring methods with abstracts as parameters | [
"",
"java",
"interface",
""
] |
Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.
```
def to_binary(self):
'Return the binary representation as a string.'
data = []
# Binary version number.
data.append(struct.pack('<I', [2]))
# Image size.
data.append(struct.pack('<II', *self.image.size))
# Attribute count.
data.append(struct.pack('<I', len(self.attributes)))
# Attributes.
for attribute in self.attributes:
# Id.
data.append(struct.pack('<I', attribute.id))
# Type.
data.append(struct.pack('<H', attribute.type))
# Extra Type.
if attribute.type == 0:
data.append(struct.pack('<I', attribute.typeEx))
return ''.join(data)
```
What I dislike:
* Every line starts with `data.append(struct.pack(`, distracting from the unique part of the line.
* The byte order (`'<'`) is repeated over and over again.
* You have to remember to return the boilerplate `''.join(data)`.
What I like:
* The format specifiers appear near the attribute name. E.g., it's easy to see that `self.image.size` is written out as two unsigned ints.
* The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.
Is there a more readable/pythonic way to do this? | ```
from StringIO import StringIO
import struct
class BinaryIO(StringIO):
def writepack(self, fmt, *values):
self.write(struct.pack('<' + fmt, *values))
def to_binary_example():
data = BinaryIO()
data.writepack('I', 42)
data.writepack('II', 1, 2)
return data.getvalue()
``` | You can try to implement some sort of [declarative syntax](http://www.oreillynet.com/pub/a/python/2003/07/31/declarative_python.html) for your data.
Which may result in something like:
```
class Image(SomeClassWithMetamagic):
type = PackedValue(2)
attribute = PackedValue('attributes') # accessed via self.__dict__
#or using decorators
@pack("<II")
def get_size():
pass
#and a generic function in the Superclass
def get_packed():
stuff
```
etc...
Other examples would be SQLAlchemy's declarative\_base, ToscaWidgets and sprox | More Pythonic conversion to binary? | [
"",
"python",
""
] |
Programming an iPhone App, I need to use Google Maps api to get directions and routes. Unfortunatelly, Google Maps works around javascript.
Any idea how to do this? | You can implement this by using a UIWebView. When it comes to using JavaScript to access the Google Maps service through its Google Maps APIs, you simply take advantage of the UIWebView method:
```
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
```
Note that you will need to escape in the string representing your script, all of the occurrences of double quotes as needed.
As an example, the following method, needed to center a map, is taken from chapter 12 of iPhone SDK programming, by Maher Ali:
```
-(void) centerMap:(NSUInteger) index{
CLLocation *loc = [locations objectAtIndex:index];
NSString *js =
[NSString stringWithFormat:
@"var map = new GMap2(document.getElementById(\"map_canvas\"));"
"map.setMapType(G_HYBRID_MAP);"
"map.setCenter(new GLatLng(%lf, %lf), 18);"
"map.panTo(map.getCenter());"
"map.openInfoWindow(map.getCenter(),"
"document.createTextNode(\"Loc: (%i/%i), Time: %@\"));",
[loc coordinate].latitude, [loc coordinate].longitude,
index+1, [locations count],
[loc timestamp]];
[webView stringByEvaluatingJavaScriptFromString:js];
}
```
Also, bear in mind the following from the Apple documentation:
> JavaScript execution time is limited to 10 seconds for each top-level entry point. If your script executes for more than 10 seconds, Safari stops executing the script. This is likely to occur at a random place in your code, so unintended consequences may result. This limit is imposed because JavaScript execution may cause the main thread to block, so when scripts are running, the user is not able to interact with the webpage.
>
> JavaScript allocations are also limited to 10 MB. Safari raises an exception if you exceed this limit on the total memory allocation for JavaScript. | Before doing this you should be aware that it's against Google's Terms and Conditions to use Maps data in a Paid application.
From <http://code.google.com/apis/maps/terms.html>
> 9.1 Free, Public Accessibility to Your Maps API Implementation. Your Maps API
> Implementation must be generally
> accessible to users without charge.
> You may require users to log in to
> your Maps API Implementation if you do
> not require users to pay a fee. Unless
> you have entered into a separate
> written agreement with Google or
> obtained Google's written permission,
> your Maps API Implementation must not:
>
> (a) require a fee-based subscription
> or other fee-based restricted access;
> or (b) operate only behind a firewall
> or only on an internal network (except
> during the development and testing
> phase).
>
> 10.8 use the Static Maps API other than in an implementation in a web
> browser;
I've included section 10.8 as well. This is a debatable one as you could argue that UIWebView is a browser but still be aware of it.
If you do decide to go ahead and use it the following is a really good implementation that bridges most of the code you'll need, <http://code.google.com/p/iphone-google-maps-component/> | Get Google Maps data into an iPhone | [
"",
"javascript",
"iphone",
"google-maps",
"maps",
""
] |
I have this code:
```
$query = "select id from votes where username = '$user' and article_id = $this->id";
```
I tried this code to sanitize it:
```
$query = sprintf("select id from votes where username = '$user' and article_id = $this->id",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
```
but I get this error for the mysql\_real\_escape lines:
```
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'mexautos'@'localhost' (using password: NO) in /home/mexautos/public_html/kiubbo/data/article.php on line 145 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/mexautos/public_html/kiubbo/data/article.php on line 145 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'mexautos'@'localhost' (using password: NO) in /home/mexautos/public_html/kiubbo/data/article.php on line 146 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/mexautos/public_html/kiubbo/data/article.php on line 146
```
I get the user name here, I dont know if its safe enough:
```
function getUsername(){ return $this->username; }
```
Thx | I would suggest using [prepared statements](http://us.php.net/manual/en/mysqli.prepare.php) for this instead of `sprintf` | You need a mysql connection before you can use mysql\_real\_escape\_string. | Sanitize user input destined for database in PHP | [
"",
"php",
"sql-injection",
"code-injection",
"sanitization",
"sanitize",
""
] |
How do I find out which class I am initialising a decorator in? It makes sense that I wouldn't be able to find this out as the decorator is not yet bound to the class, but is there a way of getting round this?
```
class A(object):
def dec(f):
# I am in class 'A'
def func(cls):
f(cls)
return func
@dec
def test(self):
pass
```
I need to know which class I am (indicated by the commented line). | I don't think this is possible. At the very moment when you define test, the class doesn't exist yet.
When Python encounters
```
class A(object):
```
it creates a new namespace in which it runs all code that it finds in the class definition (including the definition of test() and the call to the decorator), and when it's done, it creates a new class object and puts everything into this class that was left in the namespace after the code was executed.
So when the decorator is called, it doesn't know anything yet. At this moment, test is just a function. | I don't get the question.
```
>>> class A(object):
def dec(f):
def func(cls):
print cls
return func
@dec
def test(self):
pass
>>> a=A()
>>> a.test()
<__main__.A object at 0x00C56330>
>>>
```
The argument (`cls`) is the class, `A`. | How to access the parent class during initialisation in python? | [
"",
"python",
"decorator",
"introspection",
""
] |
I'm thinking about adding code to my application that would gather diagnostic information for later examination. Is there any C++ library created for such purpose? What I'm trying to do is similar to profiling, but it's not the same, because gathered data will be used more for debugging than profiling.
EDIT:
Platform: Linux
Diagnostic information to gather: information resulting from application logic, various asserts and statistics. | You might also want to check out [libcwd](http://carlowood.github.io/libcwd/):
> Libcwd is a thread-safe, full-featured debugging support library for C++
> developers. It includes ostream-based debug output with custom debug
> channels and devices, powerful memory allocation debugging support, as well
> as run-time support for printing source file:line number information
> and demangled type names.
* [List of features](http://carlowood.github.io/libcwd/www/features.html)
* [Tutorial](http://carlowood.github.io/libcwd/tutorial/index.html)
* [Quick Reference](http://carlowood.github.io/libcwd/www/quickreference.html)
* [Reference Manual](http://carlowood.github.io/libcwd/reference-manual/index.html)
Also, another interesting logging library is [pantheios](http://www.pantheios.org/):
> Pantheios is an Open Source C/C++ Logging API library, offering an
> optimal combination of 100% type-safety, efficiency, genericity
> and extensibility. It is simple to use and extend, highly-portable (platform
> and compiler-independent) and, best of all, it upholds the C tradition of you
> only pay for what you use. | I tend to use logging for this purpose. [Log4cxx](http://logging.apache.org/log4cxx/index.html) works like a charm. | Instrumentation (diagnostic) library for C++ | [
"",
"c++",
"debugging",
"profiling",
"runtime",
"instrumentation",
""
] |
Is there any way to set the minimum size of a popup window through JavaScript?
My problem is that when someone makes it as small as he can the content just looks stupid. | Most browsers have a minimum width and height.
Internet Explorer 7
minimum width > 250px
minimum height > 150px | When creating pop-ups, you can only set width and height. But since the pop-up was created, it means you can change the height and width of the window when the pop-up loads.
Simply place an onload event inside your pop-up window:
```
window.onload = function() {
if (document.body.scrollHeight) {
var winWidth = document.body.scrollWidth;
var winHeight = document.body.scrollHeight;
} else if (document.documentElement.scrollHeight) {
var winHeight = document.documentElement.scrollHeight;
var winWidth = document.documentElement.scrollWidth;
} else {
var winHeight = document.documentElement.offsetHeight;
var winWidth = document.documentElement.offsetWidth;
}
window.resizeTo(winWidth, winHeight);
}
```
**edit:** Tested in IE7,8, Chrome, Safari 4, Firefox 3. Working, but you might need to take into account the size of menu+address bars and such, as the window size will be the outer size, and this function will find the size of the content. So to be safe you should probably add a couple of pixels, and also turn off scrollbars in the popup to make sure they won't take up any space. | Setting the minimum size of a JavaScript popup window | [
"",
"javascript",
"popup",
"size",
"minimum",
""
] |
I'm trying to look up two pieces of metadata (volume and issue) on items which may have either a volume, issue, or both. The metadata is stored in a table with item ID, key (metadata field ID) and value.
This does work, but it seems overly complex and repetitive:
```
select volume.text_value as volume_value, issue.text_value as issue_value
from metadatavalue item
left outer join (select item_id, text_value from metadatavalue
where metadata_field_id = 90) volume
on item.item_id = volume.item_id
left outer join (select item_id, text_value from metadatavalue
where metadata_field_id = 91) issue
on item.item_id = issue.item_id
where item.metadata_field_id in (90, 91)
```
Is there a simpler way to write this query?
Thanks. | PostgreSQL supports a full outer join which can simplify the query:
```
select v.text_value as volume_value, i.text_value as issue_value
from ( select item_id, text_value
from metadatavalue
where metadata_field_id = 90) v
full join
( select item_id, text_value
from metadatavalue
where metadata_field_id = 91) i
using (item_id)
``` | ```
SELECT DISTINCT ON (item_id)
item_id,
CASE metadata_field_id
WHEN 90 THEN
text_value
ELSE (
SELECT text_value
FROM metadatavalue m
WHERE m.metadata_field_id = 90
AND m.item_id = i.item_id
)
END AS volume,
CASE metadata_field_id
WHEN 91 THEN
text_value
ELSE (
SELECT text_value
FROM metadatavalue m
WHERE m.metadata_field_id = 91
AND m.item_id = i.item_id
)
END AS issue
FROM metadatavalue
WHERE metadata_field_id IN (90, 91)
ORDER BY
item_id
```
Having an index on `(item_id, metadata_field)` will improve this query.
This will work better if there are few `items` with `metadata` of `90` and `91`, compared to overall number of `items`.
If almost all `items` have these `metadata`, just use:
```
SELECT *
FROM (
SELECT item_id,
(
SELECT text_value
FROM metadatavalue m
WHERE m.metadata_field_id = 90
AND m.item_id = i.item_id
) volume,
(
SELECT text_value
FROM metadatavalue m
WHERE m.metadata_field_id = 91
AND m.item_id = i.item_id
) issue
FROM items
) q
WHERE issue IS NOT NULL OR volume IS NOT NULL
``` | Outer join with conditions? | [
"",
"sql",
"postgresql",
""
] |
I'm working on a program that will parse a PE object for various pieces of information.
Reading the specifications though, I cannot find out why the MZ bytes are there, as I cannot find this on the list of machine types that these 2 bytes are supposed to represent.
Can anyone clarify? | The MZ signature is a signature used by the MS-DOS relocatable 16-bit EXE format.
The reason a PE binary contains an MZ header is for backwards compatibility. If the executable is run on a DOS-based system it will run the MZ version (which is nearly always just stub that says you need to run the program on a Win32 system).
Of course this is not as useful nowadays as it was back when the world was transitioning from DOS to whatever would come after it.
Back then there were a few programs that would actually bind together a DOS version and a Win32 version in a single binary.
And as with most things dealing with Windows history, Raymond Chen has some interesting articles about this subject:
* [Why does a corrupted binary sometimes result in "Program too big to fit in memory"?](https://devblogs.microsoft.com/oldnewthing/20060130-00/?p=32483)
* [What's the difference between the COM and EXE extensions?](https://devblogs.microsoft.com/oldnewthing/20080324-00/?p=23033) | Thety are the initials of a Microsoft programmer and identify the file as a DOS executable see <http://en.wikipedia.org/wiki/DOS_executable> for a bit more info. | What is the MZ signature in a PE file for? | [
"",
"c++",
"header",
"portable-executable",
""
] |
I am making a console application where I drop files onto the .exe from Explorer and it will move them to the appropriate folder based on rules I have set in the logic of the program.
The program works great, but when I select more than 25 files and drop them on my .exe I get an error:
> Windows cannot access the specified device, path, or file. You may not have the appropriate permissions to access the item.
If I only drop 24 files from the same set it works fine.
What am I doing wrong? | Depending on your platform, you may be running into the maximum command line length. See [Here](http://support.microsoft.com/kb/830473) for more info.
"On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters. On computers running Microsoft Windows 2000 or Windows NT 4.0, the maximum length of the string that you can use at the command prompt is 2047 characters." | Is the number of files causing the maximum length of the command line (and thus arguments) to be exceeded, which causes this error? | Why won't my console app work with 25 arguments or more? | [
"",
"c#",
"command-line-arguments",
""
] |
I once saw this line of code:
```
std::cout %lt;%lt; "Hello world!" %lt;%lt; std:: endl;
```
And am wondering what `%lt;%lt;` means. | You must have seen that online. Someone uploaded this line:
```
std::cout << "Hello world!" << std::endl;
```
Which was translated to this for output to html:
```
std::cout << "Hello world!" << std::endl;
```
Because, of course, `<` is the html entity for `<`.
Finally, something somewhere decided to change the ampersands to percent signs, possibly as part of a url-encoding scheme. | Looks like "%lt;" is supposed to be escaped for http transmission. Like:
```
%lt;%lt;
```
was supposed to be:
```
<<
``` | What does the '%lt' mean in C++? (NOT modulus, I know what that does) | [
"",
"c++",
"operators",
""
] |
I'm trying to get the sample code from Mozilla that consumes a REST web service to work under Firefox 3.0.10. The following code does NOT work in Firefox but does in IE 8!
1. Why is this not working?
2. Does IE 8 have support for XMLHttpRequest? Most examples I've seen use the ActiveX
allocation. What should I be doing? XMLHttpRequest seems more standardized.
Sample:
```
var req = new XMLHttpRequest();
req.open('GET', 'http://localhost/myRESTfulService/resource', false); // throws 'undefined' exception
req.send(null);
if(req.status == 0)
dump(req.responseText);
```
The open statement is throwing an exception with the description 'undefined'. This is strange as I allocate the req object, am running it in Firefox, and checked to make sure it is defined before calling open (which it says it is of type 'object').
I've also tried the asynchronous version of this with no luck.
**EDIT 2:** Below is my most recent code:
```
function createRequestObject() {
if( window.XMLHttpRequest ) {
return new XMLHttpRequest();
}
else if( window.ActiveXObject ) {
return new ActiveXObject( "Microsoft.XMLHTTP" );
}
return null;
}
function handleResponse( req ) {
document.writeln( "Handling response..." ); // NEVER GETS CALLED
if( req.readyState == 0 ) {
document.writeln( "UNITIALIZED" );
}
else if( req.readyState == 1 ) {
document.writeln( "LOADING" );
}
else if( req.readyState == 2 ) {
document.writeln( "LOADED" );
}
else if( req.readyState == 3 ) {
document.writeln( "INTERACTIVE" );
}
else if( req.readyState == 4 ) {
document.writeln( "COMPLETE" );
if( req.status == 200 ) {
document.writeln( "SUCCESS" );
}
}
}
document.writeln( "" );
var req = createRequestObject();
try {
document.writeln( "Opening service..." );
req.onreadystatechange = function() { handleResponse( req ); };
req.open('POST', 'http://localhost/test/test2.txt', true); // WORKS IN IE8 & NOT FIREFOX
document.writeln( "Sending service request..." );
req.send('');
document.writeln( "Done" );
}
catch( err ) {
document.writeln( "ERROR: " + err.description );
}
```
***EDIT 3:*** Alright, I reworked this in jQuery. jQuery works great in IE but it throws 'Undefined' when running from Firefox. I double checked and 'Enable JavaScript' is turned on in Firefox - seems to work fine in all other web pages. Below is the jQuery code:
```
function handleResponse( resp ) {
alert( "Name: " + resp.Name );
alert( "URL: " + resp.URL );
}
$(document).ready( function() {
$("a").click( function(event) {
try {
$.get( "http://localhost/services/ezekielservices/configservice/ezekielservices.svc/test",
"{}",
function(data) { handleResponse( data ); },
"json" );
}
catch( err ) {
alert("'$.get' threw an exception: " + err.description);
}
event.preventDefault();
});
} ); // End 'ready' check
```
**Summary of Solution:**
Alright, web lesson 101. My problem was indeed cross-domain. I was viewing my site unpublished (just on the file system) which was hitting a published service. When I published my site under the same domain it worked.
Which also brings up an important distinction between IE and Firefox. When IE experiences this scenario, it prompts the user whether or not they accept the cross-domain call. Firefox throws an exception. While I'm fine with an exception, a more descriptive one would have been helpful.
Thanks for all those who helped me. | unless '<http://www.mozilla.org/>' is the domain from which this request originates, this wont work because of same origin policy
**edit:**
Ok, a good status is 200, not 0.
see <http://dogself.com/telluriumTest/> and click on "stackoverflow test". its using your code and working.
specifically this code:
```
function test(){
var req = new XMLHttpRequest();
req.open('GET', 'index2.htm', false);
req.send(null);
if(req.status == 200)
alert("got some stuff back:"+req.responseText);
}
``` | dont use onreadystatechange when sending synchronous request ('false'), put the handler right after the send() function. It seems FF doesnt execute the onreadystatechange function if request is synchronous.
<http://support.mozilla.com/tiki-view_forum_thread.php?locale=ca&comments_parentId=124952&forumId=1> | Why is this XMLHttpRequest sample from Mozilla is not working in Firefox 3? | [
"",
"javascript",
"ajax",
"firefox",
"rest",
"xmlhttprequest",
""
] |
I have a column *groups*. *Groups* has different type stored in group\_types (buyers, sellers, referee). Only when the group is of type buyer it has another type (more specialized) like electrical and mechanical.
I'm a bit puzzled with how I will store this in a database.
Someone can suggest me a database structure?
thanks | Store your `group_types` as a hieararchical table (with `nested sets` or `parent-child` model):
`Parent-child`:
```
typeid parent name
1 0 Buyers
2 0 Sellers
3 0 Referee
4 1 Electrical
5 1 Mechanic
```
```
SELECT *
FROM mytable
WHERE group IN
(
SELECT typeid
FROM group_types
START WITH
typeid = 1
CONNECT BY
parent = PRIOR typeid
)
```
will select all buyers in `Oracle`.
`Nested sets`:
```
typeid lower upper Name
1 1 2 Buyers
2 3 3 Sellers
3 4 4 Referee
4 1 1 Electrical
5 2 2 Mechanic
```
```
SELECT *
FROM group_types
JOIN mytable
ON group BETWEEN lower AND upper
WHERE typeid = 1
```
will select all buyers in any database.
`Nested sets` is implementable anywhere and more performant, if you don't need hierarchical ordering or frequent updates on `group_types`.
`Parent-child` is implementable easily in `Oracle` and `SQL Server` and with a little effort in `MySQL`. It allow easy structure changing and hierarchical ordering.
See this article in my blog on how to implement it in `MySQL`:
* [**Hierarchical queries in `MySQL`**](http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/) | You could possibly store additional types like, `buyer_mechanical` or `buyer_electrical`. | database model structure | [
"",
"sql",
"database",
""
] |
I want to trigger a javascript function when one of the elements in a specific form has been changed. Is this possible using jquery?
Does anybody has an example how to do this? | ```
$(function () {
$('form#id input[name=joe]').change( function() { alert('it changed!'); });
} );
``` | If you have a text field like this:
```
<input type='text' id='myInput'>
```
You can do this:
```
function executeOnChange() {
alert('new value = ' + $(this).val());
}
$(function() { // wait for DOM to be ready before trying to bind...
$('#myInput').change(executeOnChange);
});
```
[Here is an example of this in action](http://jsbin.com/ilupa).
Please note you have to lose focus on the text field in order for the `change` event to fire.
If you want to select the input by name instead of ID, you can change `$('#myInput')` to `$('input[name=myName]')`. For more on selectors, [check out the documentation](http://docs.jquery.com/Selectors). | JQuery form update listener | [
"",
"javascript",
"jquery",
""
] |
I have a very basic `LEFT OUTER JOIN` to return all results from the left table and some additional information from a much bigger table. The left table contains 4935 records yet when I LEFT OUTER JOIN it to an additional table the record count is significantly larger.
As far as I'm aware it is absolute gospel that a `LEFT OUTER JOIN` will return all records from the left table with matched records from the right table and null values for any rows which cannot be matched, as such it's my understanding that it should be impossible to return more rows than exist in the left table, but it's happening all the same!
SQL query is as follows:
```
SELECT
SUSP.Susp_Visits.SuspReason, SUSP.Susp_Visits.SiteID
FROM
SUSP.Susp_Visits
LEFT OUTER JOIN
DATA.Dim_Member ON SUSP.Susp_Visits.MemID = DATA.Dim_Member.MembershipNum
```
Perhaps I have made a mistake in the syntax or my understanding of `LEFT OUTER JOIN` is incomplete, hopefully someone can explain how this could be occurring? | A LEFT OUTER JOIN will return all records from the LEFT table joined with the RIGHT table where possible.
If there are matches, though, it will still return *all rows that match.* Therefore, one row in the LEFT table that matches two rows in the RIGHT table will return as **two rows**, just like an INNER JOIN.
---
Looking at the edited query for this specific question, it appears you are only returning data from the LEFT table. Therefore, if you only want data from the LEFT table, and you only want one row returned for each row in the LEFT table, then you have no need to perform a JOIN at all and can just do a SELECT directly from the LEFT table. | ```
Table1 Table2
_______ _________
1 2
2 2
3 5
4 6
SELECT Table1.Id,
Table2.Id
FROM Table1
LEFT OUTER JOIN Table2 ON Table1.Id=Table2.Id
```
Results:
```
1,null
2,2
2,2
3,null
4,null
``` | How can a LEFT OUTER JOIN return more records than exist in the left table? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I need an example C# source code that abstracts databases (easy to change from one database to another with minimal code modification). Do you know some sample sites or tutorials with good quality?
Specific target databases are as follows:
1. Microsoft SQL Server
2. Oracle
3. MySQL
3. DB2
My specific requirements and encountered issues are the following:
1. Abstraction of classes used in data access.
2. Using parameters in calling stored procedures. In Microsoft SQL Server @ is fine. Other databases does not support @.
3. Converting query syntax from one database to another. Do we have some sort of "generic" query and then make some classes that generates queries it to a target database?
4. Strictly typed datasets in the data access layer. I remember from experience that the TableAdapter and Query wizard of Visual Studio failed for MySQL.
Thank you in advance for your expertise and time. | Have a look at
* [LLBLGEN](http://www.llblgen.com/) (commercial)
* [NHibernate](https://www.hibernate.org/343.html) (free)
* [MyGeneration](http://www.mygenerationsoftware.com/) (free)
* [NetTiers](http://nettiers.net/) (kind of free)
and other ORMs | Although I highly recommend [NHibernate](https://www.hibernate.org/343.html), you may also want to look at the Data Access application block of [Microsoft's Enterprise Library](http://www.codeplex.com/entlib).
Of course, any ORM should provide the functionality you need. | C# Database abstraction for Microsoft SQL Server, Oracle, MySQL and DB2 | [
"",
"c#",
"mysql",
"oracle",
"sql-server-2005",
""
] |
I have this code:
```
$thisTime = gmmktime(0, 0, 0);
for($i=0; $i<=95; $i++)
{
$perfTimeNumber = ($i+1);
$perfTimestamp = $thisTime;
$perfTime = date("H:i", $perfTimestamp);
echo '<option value="'. $perfTimeNumber .'" selected="'.$sel.'">' .$perfTime .'</option>';
$thisTime = $thisTime+(15*60);
}
```
This works fine to generate a select input with options from 01:00 through to 24:45 at 15 minute intervals.
However, if I change the code and add an if statement I get some odd results...
```
$thisTime = gmmktime(0, 0, 0);
for($i=0; $i<=95; $i++)
{
$perfTimeNumber = ($i+1);
$perfTimestamp = $thisTime;
$perfTime = date("H:i", $perfTimestamp);
if ($perfTime == '19:30') {
$sel = "selected";
}
echo '<option value="'. $perfTimeNumber .'" selected="'.$sel.'">' .$perfTime .'</option>';
$thisTime = $thisTime+(15*60);
}
```
The idea is to (arbitrarily!) make the select input default to 19.30. The code above adds
`selected = "selected"` to every option after 19:30, not just the 19:30 option. If I change the if statement slightly to be `if ($perfTime = '19:30') { ...` i.e., having a single `=` instead of `==` it creates a set of options all with the value of 19:30. What am I doing wrong? | Short answer: Because every single echo operation uses the current value of $sel. I assume it's initially blank, so the first N echos contain selected=''. If test succeeds, $sel is set to "selected", and every later print includes selected='selected'. If you use $perfTime = '19:30', it's an assignment, so the test always succeeds, and $sel is always 'selected'.
Quick fix: Add an else clause that sets $sel = ''. However, there are other oddities that make me think this is only a code snippit (i.e. always using $thisTime for $perfTimestamp , rather than something loop indexed, so it always prints the same time?). | This is because you never reset `$sel`.
Try this instead:
```
$sel = $perfTime == '19:30' ? 'selected' : '';
``` | why isn't this php loop working? | [
"",
"php",
"for-loop",
"if-statement",
""
] |
I need a sanity check on my strategy to best fulfill the requirements of a project. Basically I have an xml file that will need to be parsed periodically and html output displayed (xslt is not an option).
My thought is that I can use a single .jsp page to check an application variable that stores the last parsed date to know if it's 'time' (x days have passed) to re-generate the file. If it is, I can parse the xml via jsp and write the results to a static html file which is then dynamically included into the same jsp for rendering, if not I skip the regeneration and simply include the html file. including the html file rather than just rendering the display is to save the response / processing time for subsequent visits.
My question is whether this is a smart way to go about things, my specific concerns are 1) will I be able to overwrite an html file that may or may not be in use by visitors and 2) will the dynamic include via jsp work this way without a page redirect.
Thanks in advance for any thoughts and enduring the long post -
b | I'd use a cache (eg. ehcache) to store the generated html, with the required ttl.
Rendering could be handled by a servlet (you could use a jsp, but cleaner in a servlet) which would lookup the html from the cache, and simply return it as the response.
If the html was not in the cache, either because it had not been generated or it had expired then it would get generated and stored in the cache.
The generation of the html from the xml could even be handled by a separate thread to avoid any delays to the user while it was being generated. | Doing the XML generation (translation) in a Servlet might make more sense. I say this because you'll most likely have a bunch of Java code. The Servlet is probably more appropriate than a JSP for a bunch of programmatic processing. | Is this a valid strategy for generating then including html into jsp file? | [
"",
"java",
"jsp",
""
] |
I'm using the toolkit:DataGrid from CodePlex.
I'm generating the columns in code.
How can I set the equivalent of **{Binding FirstName}** in code?
Or alternatively, how can I just **set the value**, that's all I need to do, not necessarily bind it. I just want the value from my model property in the cell in the datagrid.
```
DataGridTextColumn dgtc = new DataGridTextColumn();
dgtc.Header = smartFormField.Label;
dgtc.Binding = BindingBase.Path = "FirstName"; //PSEUDO-CODE
dgtc.CellValue= "Jim"; //PSEUDO-CODE
CodePlexDataGrid.Columns.Add(dgtc);
``` | Untested, but the following should work:
```
dgtc.Binding = new Binding("FirstName");
``` | The first answer about the new Binding is correct for me, too. The main problem to use that answer was that Binding belongs to four namespaces 8-(. The correct namespace is System.Windows.Data (.NET 4, VS2010). This leads to a more complete answer:
```
dgtc.Binding = new System.Windows.Data.Binding("FirstName");
```
A side note:
In my case the context to set the binding was the iteration over the columns of the DataGrid. Before it is possible to change the binding it is necessary to cast the base class DataGridColumn to DataGridTextColumn. Then it is possible to change the binding:
```
int pos = 0;
var dgtc = dataGrid.Columns[pos] as DataGridTextColumn;
dgtc.Binding = new System.Windows.Data.Binding("FirstName");
``` | How can I set the binding of a DataGridTextColumn in code? | [
"",
"c#",
"wpf",
"datagrid",
""
] |
Buffer overrun problems are well known. Thus we were blessed with standard library functions such as wcscat\_s(). And the kind folks at Microsoft have created similar safe string functions such as as StringCbCat().
But I have a problem where I need to search *a bit of memory* for a string. The Standard library function:
```
wcsstr( wchar_t* pMem, wchar_t* pStr )
```
seems great, but...
Sometimes my memory contains garbage, sometimes strings. And when it is garbage I sometimes run off an allocated memory page, [=Access Violation]. I can write my own function yes. But my question is if there is any "standard" function to do safe string search such as:
```
"wcsstr_s( wchar_t* pMem, size_t uiSize, wchar_t* pStr )" ?
```
Thanx
**[EDIT]**
Thanks and kudos to Charles Bailey for a perfect answer to my question. Thanks to others for their efforts too.
And to those of you who doubted the saneness of my scenario: Yes of course it would be good to not ever have garbage in my memory. But I can imagine several scenarios where this situation could occur. In my particular case it is reverse-engineering, and the memory I am serching is in fact not "my memory", it belongs to another process which I cannot control.
(One other hypothetical scenario could be a tricky debugging situation where corrupted memory needs to be tracked down.) | Assuming that your `pStr` is null terminated and that `uiSize` is the number of `wchar_t` of readable memory at `pMem`:
```
wchar_t* pSubStr = std::search( pMem, pMem + uiSize, pStr, pStr + std::wcslen( pStr ) );
// Optionally, change to the 'conventional' strstr return value
if( pSubStr == pMem + uiSize)
pSubStr = 0;
``` | Probably not the answer you were looking for, but perhaps the best solution here would be to properly initialise your strings and pointers. If your memory contains garbage, why not do the decent thing and set
```
yourString[0] = '\0';
```
If it really is just an arbitrary bit of buffer, you might be better off using something like [memcmp](http://www.cplusplus.com/reference/clibrary/cstring/memcmp/) and slide the memory buffer's pointer along `N` characters (where `N` is the number of characters you're interested in minus the length of the string you're comparing). That might not be the most efficient implementation, but should be a fairly robust approach I should think.
**[Edit]** Your question intrigued me enough to do a little experimentation. Given that you seem to be looking for more C-styled answer, here's a little snippet of code I came up with to elaborate on my memcmp suggestion:
```
// SearchingMemoryForStrings.cpp : Defines the entry point for a win32 consol application
// Purpose : Demonstrates a way to search a section of memory for a particular string
//
#include <stdio.h>
#include <string.h>
#define VALUE_NOT_FOUND (-1)
int FindStringInBuffer( const char* pMemBuffer, const size_t& bufferSizeInBytes, const char* pStrToFind )
{
int stringFound = VALUE_NOT_FOUND; // Return value which will be >= 0 if we find the string we're after
const char* pMemToMatch = NULL; // An offset pointer to part of 'pMemBuffer' which we'll feed to memcmp to find 'pStrToFind'
// Set up some constants we'll use while searching
size_t lenOfStrToFind = strlen( pStrToFind );
size_t lastSearchablePosition = bufferSizeInBytes - lenOfStrToFind;
// Search the memory buffer, shifting one character at a time for 'pStrToFind'
for( size_t i = 0; i <= lastSearchablePosition; i++ ) {
pMemToMatch = &pMemBuffer[i];
if( memcmp(pMemToMatch, pStrToFind, lenOfStrToFind) == 0 ) {
// We found the string we're looking for
stringFound = i;
break;
}
}
return stringFound;
}
void ReportResult( int returnVal, const char* stringToFind )
{
if( returnVal == VALUE_NOT_FOUND ) {
// Fail!
printf("Error, failed to find '%s' - search function returned %d\n", stringToFind, returnVal );
}
else {
// Win!
printf("Success, found '%s' at index %d\n", stringToFind, returnVal );
}
}
void FindAndReport( const char* pMemBuffer, const size_t& bufferSizeInBytes, const char* pStrToFind )
{
int result = FindStringInBuffer( pMemBuffer, bufferSizeInBytes, pStrToFind );
ReportResult( result, pStrToFind );
}
int main( int argc, char* argv[] )
{
const int SIZE_OF_BUFFER = 1024; // Some aribitrary buffer size
char some_memory[SIZE_OF_BUFFER]; // The buffer of randomly assigned memory to look for our string
const char* stringToFind = "This test should pass";
const char* stringYouWontFind = "This test should fail";
FindAndReport( some_memory, SIZE_OF_BUFFER, stringYouWontFind ); // Should fail gracefully
// Set the end of the buffer to the string we're looking for
memcpy( &some_memory[SIZE_OF_BUFFER-strlen(stringToFind)], stringToFind, strlen(stringToFind) );
FindAndReport( some_memory, SIZE_OF_BUFFER, stringToFind ); // Should succeed this time and report an index of 1003
// Try adding at some arbitrary position
memcpy( &some_memory[100], stringToFind, strlen(stringToFind) );
FindAndReport( some_memory, SIZE_OF_BUFFER, stringToFind ); // Should still succeed but report the offset as 100
FindAndReport( some_memory, SIZE_OF_BUFFER, stringYouWontFind ); // Should still fail
return 0;
}
```
That snippet compiled under Visual Studio 2008 as a Win32 console app. Gives me the following:
```
Error, failed to find 'This test should fail' - search function returned -1
Success, found 'This test should pass' at index 1003
Success, found 'This test should pass' at index 100
Error, failed to find 'This test should fail' - search function returned -1
```
The `FindStringInBuffer` function is the bit you'll want and if you need to cope with wide characters, you'll need to do some conversion, but this should at least give you some ideas that you can proceed with. If you do come up with a wchar version, I'd be interested to see what the solution looks like (I've not dealt with them myself). | C++ (Really) Safe Standard String Search? | [
"",
"c++",
"string",
"search",
"standards",
""
] |
> **Possible Duplicate:**
> [Can I "multiply" a string (in C#)?](https://stackoverflow.com/questions/532892/can-i-multiply-a-string-in-c)
In Python I can do this:
```
>>> i = 3
>>> 'hello' * i
'hellohellohello'
```
**How can I multiply strings in C# similarly to in Python?** I could easily do it in a for loop but that gets tedious and non-expressive.
Ultimately I'm writing out to console recursively with an indented level being incremented with each call.
```
parent
child
child
child
grandchild
```
And it'd be easiest to just do `"\t" * indent`. | There is an extension method for it in [this post](https://stackoverflow.com/questions/532892/can-i-multiply-a-string-in-c/532912#532912).
```
public static string Multiply(this string source, int multiplier)
{
StringBuilder sb = new StringBuilder(multiplier * source.Length);
for (int i = 0; i < multiplier; i++)
{
sb.Append(source);
}
return sb.ToString();
}
string s = "</li></ul>".Multiply(10);
``` | If you just need a single character you can do:
```
new string('\t', i)
```
See [this post](https://stackoverflow.com/questions/532892/can-i-multiply-a-string-in-c) for more info. | Multiplying strings in C# | [
"",
"c#",
"string",
"indentation",
""
] |
i am using java.
i want to draw rectangle based on mousedrag event. if user dragging the mouse, then the rectangle on the applet should increase or decrease basing on current mouse coordinates.
i have the following code.
in the following code i am using [b]SelectionArea[/b] class which extends a canvas on which i am performing drawing operation. i am using [b]image[/b] variable in this class for double buffering to reduce flickering and to save the applet's previous state(i.e drawing content of applet)
but the code is working fine if i draw first rectangle. if i start to draw second rectangle the previously drawn rectangle is disappearing. i want the previously drawn rectangle to be on the screen
can any one tell me how to solve this.
```
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*
* This displays a framed area. When the user drags within
* the area, this program displays a rectangle extending from
* where the user first pressed the mouse button to the current
* cursor location.
*/
public class RectangleDemo extends Applet {
SelectionArea drawingPanel;
Label label;
public void init() {
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridBag);
drawingPanel = new SelectionArea(this);
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
gridBag.setConstraints(drawingPanel, c);
add(drawingPanel);
label = new Label("Drag within the framed area.");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
c.weighty = 0.0;
gridBag.setConstraints(label, c);
add(label);
drawingPanel.setVisible(true);
validate();
}
public void paint(Graphics g){
drawingPanel.repaint();
}
public void update(Graphics g){
paint(g);
}
```
}
```
class SelectionArea extends Canvas implements ActionListener, MouseListener, MouseMotionListener{
Rectangle currentRect;
RectangleDemo controller;
//for double buffering
Image image;
Graphics offscreen;
public SelectionArea(RectangleDemo controller) {
super();
this.controller = controller;
addMouseListener(this);
addMouseMotionListener(this);
}
public void actionPerformed(ActionEvent ae){
repaintoffscreen();
}
public void repaintoffscreen(){
image = createImage(this.getWidth(), this.getHeight());
offscreen = image.getGraphics();
Dimension d = getSize();
if(currentRect != null){
Rectangle box = getDrawableRect(currentRect, d);
//Draw the box outline.
offscreen.drawRect(box.x, box.y, box.width - 1, box.height - 1);
//repaint();
}
}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me){ }
public void mouseClicked(MouseEvent me){}
public void mouseMoved(MouseEvent me){}
public void mousePressed(MouseEvent me) {
currentRect = new Rectangle(me.getX(), me.getY(), 0, 0);
repaintoffscreen();
}
public void mouseDragged(MouseEvent me) {
System.out.println("here in dragged()");
currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
repaintoffscreen();
repaint();
}
public void mouseReleased(MouseEvent me) {
currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
repaintoffscreen();
repaint();
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
Rectangle getDrawableRect(Rectangle originalRect, Dimension drawingArea) {
int x = originalRect.x;
int y = originalRect.y;
int width = originalRect.width;
int height = originalRect.height;
//Make sure rectangle width and height are positive.
if (width < 0) {
width = 0 - width;
x = x - width + 1;
if (x < 0) {
width += x;
x = 0;
}
}
if (height < 0) {
height = 0 - height;
y = y - height + 1;
if (y < 0) {
height += y;
y = 0;
}
}
//The rectangle shouldn't extend past the drawing area.
if ((x + width) > drawingArea.width) {
width = drawingArea.width - x;
}
if ((y + height) > drawingArea.height) {
height = drawingArea.height - y;
}
return new Rectangle(x, y, width, height);
}
```
}
also if i run this code on full screen mode then i am seeing that the rectangle is appering on screen only after i released the mouse. but i want the rectangle to be on the screen while dragging the mouse and it should change it's dimension according to the current mouse coordinates.
can any one help me pls. | homework?
basically what you need to do is:
1. on mouse down keep the mouse-down coordinates and repaint
2. on mouse move keep current mouse coordinates and repaint
3. on mouse up, nullify the mouse-down coordinates to indicate there is no rect, and repaint.
4. on paint, draw background and then rect between mousedown and cur-mouse coordinates.
if you don't want to keep a background image, you can do a trick with the Graphics xor function, drawing the same rect twice will erase the old rect, so you can use it to restore the old image straight on the graphics object.
Edit: code xor usage sample:
```
public void paint(Graphics g)
{
g.setXORMode(Color.black);
// draw old rect if there is one. this will erase it
// draw new rect, this will draw xored
g.setDrawMode(); // restore normal draw mode
}
```
Xor has the an interesting property:
```
xor(xor(x)) = x
```
so xoring the same pixel twice restores it's original color. | There are a couple issues that need to be addressed.
First, regarding only one rectangle can be drawn, this is due to the design of your program. In your code, whenever the `repaintoffscreen` method is called, the `currectRect` field is used to draw a rectangle. However, there is no provision to keep holding onto rectangles which were made in the past.
One way to keep a hold of past rectangles would be perhaps to make another field which is, for example, a `List<Rectangle>` which is used to store past rectangles. Then, when the mouse is released, `add` the current rectangle to that list.
Then, in order for all rectangles, `currentRect` and past rectangles to appear, `repaintoffscreen` will need to not only perform `getDrawableRect` and `offscreen.drawRect` using the `currentRect` but also with the past rectangles which are stored in the `List<Rectangle>`. (Hint, use a `for` loop to iterate through the list.)
Second, regarding the rectangle not appearing until after releasing the mouse button, rather than using the `mouseDragged` method, maybe using the `mouseMoved` method along with a check to see that the mouse button is depressed may be a workaround. (I think I've also had trouble dealing with the `mouseDragged` method in the past.)
The [`MouseEvent`](http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html) passed into the `mouseMoved` method can be used to check if a button is depressed by the [`getButton`](http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html#getButton()) method:
```
public void mouseMoved(MouseEvent e)
{
// Check if button1 is pressed.
if (e.getButton() == MouseEvent.BUTTON1)
{
// Perform sizing of rectangle and off-screen drawing, and repaint.
}
}
``` | how to draw rectangle on java applet using mouse drag event | [
"",
"java",
"applet",
"drawing",
"awt",
""
] |
In C++, I understand that it is possible to create a Singleton base class using templates. It is described in the book, Modern C++ Design, by Andrei Alexandrescu.
Can something like this be achieved in Java? | I have yet to see a satisfactory solution for this in Java. There are many examples using templates in C++ or generics in .NET, but Java's generics implementation has some limitations with static members that make this difficult.
The best option I've seen is to use a static HashMap, and a factory class. This allows you to make a single factory that can serve multiple Singletons of any class.
For an implementation, see [this post](http://forums.sun.com/thread.jspa?messageID=10630400#10630400). | Because Java's generics are not reified, it isn't possible to implement a generalized Singleton in the same way. Because the generic types are "erased" from the compiled code, the singleton would have to be explicitly initialized at runtime.
The upshot is, a Singleton template would not provide much value in Java. | Generalized Singleton base class in Java | [
"",
"java",
"design-patterns",
"generics",
"templates",
"singleton",
""
] |
How Can I Check To See If App was Started From A CD/DVD in C#? | Get the path where the exe was start from with Application.StartupPath property.
then use new DriveInfo(driveletter\_from\_path).DriveType to determine whether it is a CD or harddisk. | You can do something like that :
```
FileInfo file = new FileInfo(Process.GetCurrentProcess().MainModule.FileName);
DriveInfo drive = new DriveInfo(file.Directory.Root.ToString());
switch (drive.DriveType)
{
case DriveType.CDRom:
MessageBox.Show("Started from CD/DVD");
break;
case DriveType.Network:
MessageBox.Show("Started from network");
break;
case DriveType.Removable:
MessageBox.Show("Started from removable drive");
break;
default:
break;
}
``` | How Can I Check To See If App was Started From A CD/DVD in C#? | [
"",
"c#",
""
] |
I have some code:
```
import javax.activation.MimetypesFileTypeMap;
...
..
.
String filename = "foo.xls"; // Where this can be any file name .doc, .pdf or whatever
String headerContentType = new MimetypesFileTypeMap().getContentType(filename);
```
It seems javax.activation.MimetypesFileTypeMap class is inside `rt.jar` which comes with JRE System library (jdk1.6.0\_10) but not in jdk1.5.0
I would like to avoid the use of 1.6 libraries. Anyone knows an easy and quick alternative? | This comes from the [activation](http://java.sun.com/javase/technologies/desktop/javabeans/jaf/downloads/index.html) framework. This is included as standard in Java 6, but is also available as a separate download (for use with Java 1.4 and above) | The particular class is actually part of the java bean s activation framework;
[JAF Download](http://java.sun.com/javase/technologies/desktop/javabeans/jaf/downloads/index.html)
It should not be dependant on 1.6 as far as I know. So simply download the jar, and ensure you have the mimetypes.default available on your classpath. | Alternative to javax.activation.MimetypesFileTypeMap().getContentType(filename); | [
"",
"java",
"java-6",
"java-5",
""
] |
I have a date range where a start date is 2 years prior to today.
e.g.) '05/29/2007' ~ '05/29/2009'.
How can I break above date range so that I would get a list like the following?
(start date starts with "05/27/2007", not "05/29/2007" since the start of weekday is Sunday and '05/27/2007' is the first day of week for '05/29/2007' and the same reasoning for the last EndDate, 05/30/2009, which is Saturday)
```
StartDate EndDate
05/27/2007 06/02/2007
06/03/2007 06/09/2007
...
05/24/2009 05/30/2009
```
**[UPDATE]** here is my final query
```
WITH hier(num, lvl) AS (
SELECT 0, 1
UNION ALL
SELECT 100, 1
UNION ALL
SELECT num + 1, lvl + 1
FROM hier
WHERE lvl < 100
)
SELECT num, lvl,
DATEADD(dw, -DATEPART(dw, '2007-05-29'), '2007-05-29') + num * 7,
DATEADD(dw, -DATEPART(dw, '2007-05-29'), '2007-05-29') + (num + 1) * 7
FROM hier
where num <= 104 --; 52 weeks/year * 2
ORDER BY num
``` | ```
WITH hier(num, lvl) AS (
SELECT 0, 1
UNION ALL
SELECT 100, 1
UNION ALL
SELECT num + 1, lvl + 1
FROM hier
WHERE lvl < 100
)
SELECT DATEADD(dw, -DATEPART(dw, '29.05.2007'), '29.05.2007') + num * 7,
DATEADD(dw, -DATEPART(dw, '29.05.2007'), '29.05.2007') + (num + 1) * 7
FROM hier
WHERE DATEADD(dw, -DATEPART(dw, '29.05.2007'), '29.05.2007') + num * 7 < '29.05.2009'
ORDER BY
num
```
This will generate a rowset with the ranges you need. | You need to make sure that @@DATEFIRST is properly sent, then you can simply use the code below. Read up on DATEFIRST though so that you understand it fully.
```
SET DATEFIRST 1
DECLARE @my_date DATETIME
SET @my_date = '2007-05-29'
SELECT
DATEADD(dw, -DATEPART(dw, @my_date), @my_date) AS StartDate,
DATEADD(dw, 6 - DATEPART(dw, @my_date), @my_date) AS EndDate
``` | Grouping Date Range by Week | [
"",
"sql",
"t-sql",
"datetime",
"date-range",
""
] |
I am playing GWT. I am looking for basic argument checking. I do not require invariants or result ensures.
What I am interested about it best practises on the topic.
For example, in c# I use one of this options:
1. `if (arg1 != null) throw new ArgumentNulException....; // Official for public API;`
2. `Args.NotNull(arg1); // Home grown.`
3. `Contracts.Requires(arg1 != null); // Internal contract validation.`
What is the best place for me to start?
Ok, what I found for now.
1. [Validate method arguments](http://www.javapractices.com/topic/TopicAction.do?Id=5)
2. [Programming With Assertions](http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html) | I typically just do it myself, per the recommendations of [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) by Josh Bloch, so:
```
if (arg == null) throw new NullPointerException("arg cannot be null");
```
or
```
if (arg < 0) throw new IllegalArgumentException("arg must be positive");
```
I'd highly recommend getting a copy of [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) if you don't already have it. | According to the [wikipedia page of Design by Contract](http://en.wikipedia.org/wiki/Design_by_contract), popular tools for this methodology with Java are:
iContract2, Contract4J, jContractor, Jcontract, C4J, CodePro Analytix, STclass, Jass preprocessor, OVal with AspectJ, Java Modeling Language (JML), SpringContracts for the Spring framework, or Modern Jass, Custos using AspectJ,JavaDbC using AspectJ, JavaTESK using extension of Java.
Reading up on one of those is probably a good idea.
I have no personal experience of any of them but Pragmatic Programmer says good things about the original iContract so that might be a good place to start.
You could always try doing it on your own by using Javas built-in assertions:
`assert Expression1;`
or
`assert Expression1 : Expression2 ;`
Where Expression1 results in a boolean and Expression2 is the value your testing (optional). Try it out. | Argument checking or Design-by-Contract in java (GWT). Where to start? | [
"",
"java",
"design-by-contract",
""
] |
I'm trying to post a form with php, and I want the form to be handled depending on the value of cmd. Specifying this after the filename does not work..what is the correct way to do this?
```
echo "<form name=\"statusForm\" action=\"edit_status.php?cmd=submitinfo\" method=\"post\" enctype=\"multipart/form-data\">
```
Where/how can I specify ?cmd=submitinfo | ```
echo "<form name=\"statusForm\" action=\"edit_status.php\" method=\"post\" enctype=\"multipart/form-data\"><input type=\"hidden\" name=\"cmd\" value=\"submitinfo\"/>
``` | Your form method is POST, and so you could probably just as easily do what you want with a hidden field:
```
<input type="hidden" name="cmd" value="submitinfo" />
```
Then just use the `$_POST` variable, as with your other form parameters, on the edit status page. | How to specify a command when posting a form, using php? | [
"",
"php",
"forms",
""
] |
I'm storing data in a HashMap with (key: String, value: ArrayList). The part I'm having trouble with declares a new ArrayList "current," searches the HashMap for the String "dictCode," and if found sets current as the returned value ArrayList.
```
ArrayList current = new ArrayList();
if(dictMap.containsKey(dictCode)) {
current = dictMap.get(dictCode);
}
```
The "current =..." line returns a compiler error of:
```
Error: incompatible types
found : java.lang.Object
required: java.util.ArrayList
```
I don't understand this... does that HashMap return an Object instead of the ArrayList I stored in it as the value? How do I convert this object into an ArrayList?
Thank you. | How is the HashMap declaration expressed in that scope? It should be:
```
HashMap<String, ArrayList> dictMap
```
If not, it is assumed to be Objects.
For instance, if your code is:
```
HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);
```
that will not work. Instead you want:
```
HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);
```
The way generics work is that the type information is available to the compiler, but is not available at runtime. This is called type erasure. The implementation of HashMap (or any other generics implementation) is dealing with Object. The type information is there for type safety checks during compile time. See the [Generics documentation](http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html).
Also note that [`ArrayList`](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html) is also implemented as a generic class, and thus you might want to specify a type there as well. Assuming your `ArrayList` contains your class `MyClass`, the line above might be:
```
HashMap<String, ArrayList<MyClass>> dictMap
``` | ```
public static void main(String arg[])
{
HashMap<String, ArrayList<String>> hashmap =
new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("Hello");
arraylist.add("World.");
hashmap.put("my key", arraylist);
arraylist = hashmap.get("not inserted");
System.out.println(arraylist);
arraylist = hashmap.get("my key");
System.out.println(arraylist);
}
null
[Hello, World.]
```
Works fine... maybe you find your mistake in my code. | HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList? | [
"",
"java",
"arraylist",
""
] |
How can I hide a `<td>` tag using JavaScript or inline CSS? | What do you expect to happen in it's place? The table can't reflow to fill the space left - this seems like a recipe for buggy browser responses.
Think about hiding the contents of the td, not the td itself. | ```
.hide{
visibility: hidden
}
<td class="hide"/>
```
**Edit-**
Just for you
The difference between display and visibility is this.
**"display":** has many properties or values, but the ones you're focused on are "none" and "block". "none" is like a hide value, and "block" is like show. If you use the "none" value you will **totally** hide what ever html tag you have applied this css style. If you use "block" you will see the html tag and it's content. very simple.
**"visibility":** has many values, but we want to know more about the "hidden" and "visible" values. "hidden" will work in the same way as the "block" value for display, but this will hide tag and it's content, but it will not hide the phisical space of that tag. For example, if you have a couple of text lines, then and image (picture) and then a table with three columns and two rows with icons and text. Now if you apply the visibility css with the hidden value to the image, the image will disappear but the space the image was using will remaing in it's place, in other words, you will end with a big space (hole) between the text and the table. Now if you use the "visible" value your target tag and it's elements will be visible again. | How can I hide a TD tag using inline JavaScript or CSS? | [
"",
"javascript",
"html",
"css",
"visibility",
""
] |
I'm at a loss here. I've got a specific group of users upstairs whose sessions seem to expire completely randomly. It's not just when they leave the site sitting for a while, it can expire while they're browsing around. For me and most of our users everything works just fine. It's not a browser issue, we've got people in FF and all IE versions that both function correctly, and people in FF and IE that don't work.
My `gc_maxlifetime` is at `43200` and the garbage collection is a crazy low `1/1000` (not that that should matter). Is it possible there's something else running on the server that's randomly deleting some of our sessions? What should I check? That still wouldn't explain why only this specific group seems to be affected.
I have a few Session settings that are different from the default:
```
session.gc_maxlifetime = 43200
session.gc_divisor = 1000
session.save_path = /var/lib/php/session
session.use_only_cookies = Off
session.bug_compat_42 = Off
```
The first three I'm not worried about, but could the last two be causing this behavior? I don't actually ever send cookies through the URL, so I have no good reason for having use\_only\_cookies off. I have no guarantees that the misfits who made this app before I got here didn't exploit the `bug_compat_42` thing to set session variables, but again, I would expect an issue with that to be less random.
Edit:
On further investigation, I've found that the Session is not being destroyed at all, but the end-user is getting a new session ID. The old session still exists intact on the server, but a new one is randomly started while they're browsing. | The issue here turns out to be that their browser was setting the session cookie to expire prematurely. I've solved the issue with this dirty, dirty hack that you should never have to use, ever. I'm not proud of this, but if this shines some light on anything feel free to let me in:
```
if (!headers_sent()) {
if ($_COOKIE["PHPSESSID"] != "") {
setcookie("PHPSESSID", $_COOKIE["PHPSESSID"], time()+43200, "/", ".mydomain.com");
}
}
``` | Can you provide a little more information about your set up?
My first thought would be that there is something randomly cleaning out your temporary files directory. If you're using a standard LAMP set up, PHP will be storing the session data files into /tmp. If they're getting deleted from there by a cleaning process, you'd lose your sessions.
Edit: I'm re-thinking this now. If only a specific group of users is affected, that makes it much less likely.
How about cookie settings? I'd make sure that these people aren't using something like a dynamic proxy, and that your cookies are being set for the root domain of your site. Is it possible they might have some privacy-cleaning software such as CCleaner set up as a scheduled task that might be removing their cookies?
I'd get up there on one of their computers and throw Firebug onto one of the Firefox machines and examine the HTTP requests to see if the cookies are being sent properly. | PHP Sessions Expiring Unexpectedly | [
"",
"php",
"session",
""
] |
Is there a recommended way to wait on multiple inputs. For example I would like my program to be able to receive input from 3 sources:
Listen on a thread condition e.g. pthread\_cond\_wait()
Take data from Standard input e.g. getline()
Listen on a socket e.g. accept()
What is the best way to accomplish this? Do I need a thread for each different input source? Thanks | You can listen on multiple *file descriptors* without using multiple threads using the [`select(2)`](http://linux.die.net/man/2/select) system call. You can use [`pthread_cond_timedwait`](http://www.opengroup.org/onlinepubs/000095399/functions/pthread_cond_timedwait.html) to wait on a condition variable with a timeout, such that you don't wait more than a particular amount of time.
I think it's highly unusual to want to simultaneously wait on either a condition variable or a file descriptor of some sort -- if you're absolutely sure that that's what you want to do, you'll have to use multiple threads, with one thread calling either `pthread_cond_wait`/`pthread_cond_timedwait`, and the other thread calling `select` or some other I/O function. | No need for separate threads waiting for `accept(2)` and `stdin` - use `poll/select` here. Instead of conditional variable, create a pipe between threads (you already have threads if we talk about CVs), wait on it in the same `poll` and write to it when the event happens. | Waiting on multiple events C++ | [
"",
"c++",
"multithreading",
"posix",
"pthreads",
""
] |
This query will only return all records where Active=true and Exempt=false. It should be returning any records also where Active=true and Exempt IS NULL. I guess the .IsNotEqualTo doesn't compare to any records with a null value? Is there a way around this without setting a default?
```
UserCollection ActiveUsersNotExempt = new UserCollection();
ActiveUsersNotExempt = DB.Select().From<User>()
.Where(User.Columns.Active).IsEqualTo(true)
.And(User.Columns.Exempt).IsNotEqualTo(true)
.ExecuteAsCollection<UserCollection>();`
``` | Use AndExpression as follows to get a nested constraint (Exempt is not true or is null):
```
UserCollection ActiveUsersNotExempt = DB.Select().From<User>()
.Where(User.Columns.Active).IsEqualTo(true)
.AndExpression(User.Columns.Exempt).IsNotEqualTo(true)
.Or(User.Columns.Exempt).IsNull()
.ExecuteAsCollection<UserCollection>();`
``` | In SQL, operators applied to null do not return true OR false -- instead they return null. (One exception to this rule is the "IS" operator).
That is to say, the expression `exempt != true` is false when exempt is true, true when exempt is false, and null when exempt is null.
If you want your condition to match when exempt is false OR null, you need to construct a query like:
```
active = true AND (exempt = false OR exempt IS NULL)
```
or
```
active = true AND COALESCE(exempt, false) = false
```
Hopefully this gives you some insight into what's going on under the hood. | .IsNotEqualTo doesn't compare Nulls | [
"",
"c#",
".net",
"subsonic",
""
] |
I'm new to DOM parsing in PHP:
I have a HTML file that I'm trying to parse. It has a bunch of DIVs like this:
```
<div id="interestingbox">
<div id="interestingdetails" class="txtnormal">
<div>Content1</div>
<div>Content2</div>
</div>
</div>
<div id="interestingbox">
......
```
I'm trying to get the contents of the many div boxes using php.
How can I use the DOM parser to do this?
Thanks! | First i have to tell you that you can't use the same id on two different divs; there are classes for that point. Every element should have an unique id.
Code to get the contents of the div with id="interestingbox"
```
$html = '
<html>
<head></head>
<body>
<div id="interestingbox">
<div id="interestingdetails" class="txtnormal">
<div>Content1</div>
<div>Content2</div>
</div>
</div>
<div id="interestingbox2"><a href="#">a link</a></div>
</body>
</html>';
$dom_document = new DOMDocument();
$dom_document->loadHTML($html);
//use DOMXpath to navigate the html with the DOM
$dom_xpath = new DOMXpath($dom_document);
// if you want to get the div with id=interestingbox
$elements = $dom_xpath->query("*/div[@id='interestingbox']");
if (!is_null($elements)) {
foreach ($elements as $element) {
echo "\n[". $element->nodeName. "]";
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->nodeValue. "\n";
}
}
}
//OUTPUT
[div] {
Content1
Content2
}
```
Example with classes:
```
$html = '
<html>
<head></head>
<body>
<div class="interestingbox">
<div id="interestingdetails" class="txtnormal">
<div>Content1</div>
<div>Content2</div>
</div>
</div>
<div class="interestingbox"><a href="#">a link</a></div>
</body>
</html>';
//the same as before.. just change the xpath
[...]
$elements = $dom_xpath->query("*/div[@class='interestingbox']");
[...]
//OUTPUT
[div] {
Content1
Content2
}
[div] {
a link
}
```
Refer to the [DOMXPath](http://us.php.net/manual/en/class.domxpath.php) page for more details. | I got this to work using [simplehtmldom](http://simplehtmldom.sourceforge.net/) as a start:
```
$html = file_get_html('example.com');
foreach ($html->find('div[id=interestingbox]') as $result)
{
echo $result->innertext;
}
``` | how to use dom php parser | [
"",
"php",
"dom",
"html-parsing",
""
] |
I'm using listview control with the following parameters set:
```
this.listView1.BackColor = System.Drawing.Color.Gainsboro;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.listView1.FullRowSelect = true;
this.listView1.HideSelection = false;
this.listView1.Location = new System.Drawing.Point(67, 192);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(438, 236);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.DrawColumnHeader += new System.Windows.Forms.DrawListViewColumnHeaderEventHandler(this.listView1_DrawColumnHeader);
this.listView1.RetrieveVirtualItem += new System.Windows.Forms.RetrieveVirtualItemEventHandler(this.listView1_RetrieveVirtualItem);
this.listView1.DrawSubItem += new System.Windows.Forms.DrawListViewSubItemEventHandler(this.listView1_DrawSubItem);
```
Two rows are provided with some random text. Ownerdrawing is simple:
```
private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if (e.ColumnIndex == 0)
{
e.DrawBackground();
e.DrawText();
}
else
e.DrawDefault = true;
//Console.WriteLine("{0}\t\tBounds:{1}\tItem:{2}\tSubitem:{3}", (i++).ToString(), e.Bounds.ToString(), e.Item, e.SubItem);
}
```
the problem is: when i hover mouse on listview's content, i get flickering of first column. Debugging shows that DrawSubItem is called constantly while the mouse is over it.
Is it bug? How to avoid this behavour? | This is a bug in .NET's ListView and you cannot get around it by double buffering.
On virtual lists, the underlying control generates lots of custom draw events when the mouse is hover over column 0. These custom draw events cause flickering even if you enable DoubleBuffering because they are sent outside of the normal WmPaint msg.
I also seem to remember that this only happens on XP. Vista fixed this one (but introduced others).
You can look in at the code in [ObjectListView](http://objectlistview.sourceforge.net) to see how it solved this problem.
If you want to solve it yourself, you need to delve into the inner plumbing of the ListView control:
1. override WndProc
2. intercept the WmPaint msg, and set a flag that is true during the msg
3. intercept the WmCustomDraw msg, and ignore all msgs that occur outside of a WmPaint event.
Something like this::
```
protected override void WndProc(ref Message m) {
switch (m.Msg) {
case 0x0F: // WM_PAINT
this.isInWmPaintMsg = true;
base.WndProc(ref m);
this.isInWmPaintMsg = false;
break;
case 0x204E: // WM_REFLECT_NOTIFY
NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR));
if (nmhdr.code == -12) { // NM_CUSTOMDRAW
if (this.isInWmPaintMsg)
base.WndProc(ref m);
} else
base.WndProc(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
``` | I get a bunch of
```
'System.Drawing.NativeMethods' is inaccessible due to its protection level
```
and
```
The type name 'NMHDR' does not exist in the type 'System.Drawing.NativeMethods'
```
errors. I read somewhere that I have to include user32.dll but can't figure out how to do it in this case.
**Edit:** OK, I posted before even start to think. I created now my own ListView control and copied the struct from the objectListView code. It seems to work now. Here my code:
```
public class Listview : ListView
{
private bool isInWmPaintMsg=false;
[StructLayout(LayoutKind.Sequential)]
public struct NMHDR
{
public IntPtr hwndFrom;
public IntPtr idFrom;
public int code;
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x0F: // WM_PAINT
this.isInWmPaintMsg = true;
base.WndProc(ref m);
this.isInWmPaintMsg = false;
break;
case 0x204E: // WM_REFLECT_NOTIFY
NMHDR nmhdr = (NMHDR)m.GetLParam(typeof(NMHDR));
if (nmhdr.code == -12)
{ // NM_CUSTOMDRAW
if (this.isInWmPaintMsg)
base.WndProc(ref m);
}
else
base.WndProc(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
}
``` | Flickering in listview with ownerdraw and virtualmode | [
"",
"c#",
"winforms",
"listview",
""
] |
Take the following class and unit test.
```
public class Entity
{
public object Id { get; set; }
public override bool Equals(object obj)
{
return this == (Entity)obj;
}
public static bool operator == (Entity base1, Entity base2)
{
if (base1.Id != base2.Id)
{
return false;
}
return true;
}
public static bool operator != (Entity base1, Entity base2)
{
return (!(base1.Id == base2.Id));
}
}
```
---
```
[TestMethod]
public void Test()
{
Entity e1 = new Entity { Id = 1 };
Entity e2 = new Entity { Id = 1 };
Assert.IsTrue(e1 == e2); //Always fails
}
```
Can someone explain why its fails? | Because you are relying on an object reference for comparator:
```
public object Id { get; set; }
```
Replace
```
public static bool operator == (Entity base1, Entity base2)
{
if (base1.Id != base2.Id)
{
return false;
}
return true;
}
```
With
```
public static bool operator == (Entity base1, Entity base2)
{
return object.Equals(base1.Id, base2.Id);
}
``` | Your `Id` property is of type `object`. When you construct two instances using 1 as the Id for each of them, you'll end up with two different boxed objects. You're then comparing those objects using *reference* equality.
Suggested changes to fix this:
* Change the type of `Id` to be of type `int` if that's appropriate.
* Use the static `object.Equals` method to compare Ids instead of ==
Either of these will work, but the first is preferable IMO.
There are various other ways in which the implementation could be made cleaner if you're interested, but I understand this may just be a dummy example. Just a quick list at a glance:
* You should be overriding `GetHashCode` as well as `Equals`.
* Your `Equals` override shouldn't perform a cast unconditionally, as that will throw an exception if the object is of the wrong type. If the type is wrong, return false.
* Your current == implementation can be simplified to just
```
return base1.Id == base2.Id;
```
* Your == implementation should perform nullity checks
* It's generally best to implement != by returning `!(base1 == base2)` unless you want specialist behaviour.
* Overriding `Equals` in a non-sealed class can be problematic. Unless you're planning for inheritance, it would be worth sealing the class (IMO - this will probably be controversial). | Why does this object equality test fail? | [
"",
"c#",
""
] |
I need to write a function that will take a variable number of arguments. I read a little about params[], but I don't think that will work in my case. My function needs to take a variable number of ints and then a corresponding bool value for each of them. I have to iterate through each of these combinations and input them into a database. Just looking for someone to point me in the right direction. Thanks. | I would recommend building a struct and then passing those in as params. In my example, your struct represents a score of some kind:
```
public struct RaceScore
{
public bool FinishedRace;
public int Points;
}
```
Your method signature would then be:
```
public void SaveScores(params RaceScore[] scores)
```
Here's an example of calling SaveScores:
```
RaceScore score = new RaceScore() { FinishedRace = true, Points = 20 };
RaceScore score2 = new RaceScore() { FinishedRace = false, Points = 15 };
SaveScores(score, score2);
``` | You can do this with params, but the params needs to be some class or struct that holds your int + your bool. `KeyValuePair<TKey,TValue>` in the base class libraries would work, if you don't want to write your own class or struct.
If you're going to iterate through them, though, I'd recommend using `IEnumerable<T>` instead, though, as it's much simpler to use.
For example:
```
public void SaveValues(IEnumerable<KeyValuePair<int,bool>> values)
{
foreach(var pair in values)
{
int intVal = pair.Key;
bool boolVal = pair.Value;
// Do something here...
}
}
```
The same thing would work with params, ie:
```
public void SaveValues(params KeyValuePair<int,bool>[] values)
```
This, though, forces you to make an array. Using `IEnumerable<T>` will work with an array, but will also work with lists of values, or LINQ query results, etc. This makes generating calling this function easier in many cases. | Passing Variable Number of Arguments | [
"",
"c#",
""
] |
I'm writing a WPF application which will monitor a feed. When there are new items determined from the feed I want to spawn off small windows as a *notification*. If anyone's familiar with Growl on OS X, that kind of what I'm trying to do. Also, I'll point out that this is my first WPF application (and the first time I've done something that's not a web app for a while!).
I was originally do code like this:
```
foreach(var feedNotification in newFeedNotifications) {
var popupWindow = new PopupWindow() { ... };
popupWindow.Show();
}
```
The problem is that the above is **very** CPU intensive, the the point where it's taking about 50% CPU usage. Also, I want to be able to track the position of the on-screen notifications so that if the next check finds more to show it knows where the last currently visible one is and the new ones are shown below the others.
How would I go about achieving this while ensuring that the computer running the application is not being brought to a hault?
**Edit:** I'm using the .NET 3.5 SP1 framework | I'm not *100%* on this, but I think it would be much more efficient to spawn a new instance of the window into a collection maintained by your main window (or an object there-in). Then you could create an event that could be subscribed to by the newly spawned window. Once the new windows are watching for updates from the main window or object, you could just fire the event on the main window and let your notification windows take care of the rest.
As far as the notification window tracking, you could allow the notification windows to be alerted via another event hookup that there is a new window to display, and pass it to them (or allow them to retrieve it from the main object.) You can place that window directly beneath the currently visible notification by tracking when the window receives focus. So, the last window that received focus is the one that was last viewed. Once you have the existing window, it's just a matter of creating the new one in the same location (or slightly offset) then calling the focus of the window that's on top.
An alternative to tracking the active window via the focus check would be to just go through the collection of window objects contained in your main window, since the collection would be in order of creation. Hope this helps.
Found [this link](http://roecode.wordpress.com/2008/01/07/wpf-popup-control-part-1-the-quick-and-dirty-way/) a minute ago regarding popup controls that have some useful properties tied to them. | Is it absolutely necessary to create a new window for each notification? While I haven't measured this, it could be that creating new WPF windows is a CPU intensive task. If that is the case, then there isn't much that you can do to change your code to use less CPU.
Would it be possible to just create one notification window, and it will contain a list of all of the new notifications? I realize that this isn't how Growl works, but this would provide the same information, just in a different way. | Creating new windows in a WPF application | [
"",
"c#",
".net",
"wpf",
""
] |
The `arguments` object in JavaScript is an odd wart—it acts just like an array in most situations, but it's not *actually* an array object. Since it's [really something else entirely](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments), it doesn't have the useful functions from [`Array.prototype`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype) like `forEach`, `sort`, `filter`, and `map`.
It's trivially easy to construct a new array from an arguments object with a simple for loop. For example, this function sorts its arguments:
```
function sortArgs() {
var args = [];
for (var i = 0; i < arguments.length; i++)
args[i] = arguments[i];
return args.sort();
}
```
However, this is a rather pitiful thing to have to do simply to get access to the extremely useful JavaScript array functions. Is there a built-in way to do it using the standard library? | ## ES6 using rest parameters
If you are able to use ES6 you can use:
**[Rest Parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)**
```
function sortArgs(...args) {
return args.sort(function (a, b) { return a - b; });
}
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
```
As you can read in the [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)
> The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
If you are curious about the `...` syntax, it is called *Spread Operator* and you can read more [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
## ES6 using Array.from()
Using **[Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)**:
```
function sortArgs() {
return Array.from(arguments).sort(function (a, b) { return a - b; });
}
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
```
`Array.from` simply convert Array-like or Iterable objects into Array instances.
---
---
## ES5
You can actually just use `Array`'s [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) function on an arguments object, and it will convert it into a standard JavaScript array. You'll just have to reference it manually through Array's prototype:
```
function sortArgs() {
var args = Array.prototype.slice.call(arguments);
return args.sort();
}
```
Why does this work? Well, here's an excerpt from the [ECMAScript 5 documentation itself](http://es5.github.io/#x15.4.4.10):
> **NOTE**: The `slice` function is intentionally generic; it does not require that its **this** value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the `slice` function can be applied successfully to a host object is implementation-dependent.
Therefore, `slice` works on anything that has a `length` property, which `arguments` conveniently does.
---
If `Array.prototype.slice` is too much of a mouthful for you, you can abbreviate it slightly by using array literals:
```
var args = [].slice.call(arguments);
```
However, I tend to feel that the former version is more explicit, so I'd prefer it instead. Abusing the array literal notation feels hacky and looks strange. | It's also worth referencing [this Bluebird promises library wiki page](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments) that shows how to manage the `arguments` object into array in a way that makes the function optimizable **under V8 JavaScript engine**:
```
function doesntLeakArguments() {
var args = new Array(arguments.length);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
return args;
}
```
This method is used in favor of `var args = [].slice.call(arguments);`. The author also shows how a build step can help reduce the verbosity. | How can I convert the "arguments" object to an array in JavaScript? | [
"",
"javascript",
"arrays",
"sorting",
"arguments",
"variadic-functions",
""
] |
I'm trying to figure out the best way to install my Java app on client computers.
The main guideline here is that these clients are computer illiterates - so the less fuss the better.
I was thinking of using a model that would launch a Java Web Start app which would both take care of the registration and installation processes at once.
I want these clients (real estate agents, mostly) to be able to go to a link on the main page, there presented by a nice Web Start screen (or even embedded Java applet) where they have a single form to fill out and hit Install and the latest version of the program gets installed on their computer.
The guidelines here are:
1. The installed program should be fully executable (various JavaW weirdness should be avoided).
2. The installed program should run on startup.
Additionally/Optionally:
3. The Web Start/applet program that installs should be able to scan the computer for the existence of a previous version of the installed program and respond accordingly - meaning that if it's already installed, it only updates the JARs of the installed program if needed (shuts it down, updates and restarts).
This way I can call the JNLP from within the installed program as an autoupdate method.
I'd love some pointers on this - are there such systems already available? | Try [IzPack](http://izpack.org/features/). | Check out the latest Web Start. It does the jar-update magic automatically (as always) but ALSO allows you to do lazy loads of jar files. plus run offline.
If you want to populate the local cache then jar files should have versioned names and then your "update"-application can require these. They will then be ready when the program runs the next time. | Java Web Start Driven Installation | [
"",
"java",
"installation",
""
] |
I'm developing a php based CMS, and I'm currently re-writing it into a state that is usable for customers. (My first version was internal only; and a somewhat kludgy mess :P)
In my first version, I had a function called HandlePostBack() which checked for the existance of a significant number of $\_POST variables - the submit button from each possible form. If it was set, then the appropriate command would be executed.
I'm wondering if there is a better way? I could migrate to a switch, and look for a single $\_POST variable included in each form, and then execute the command. A minimum of code would be nice, so I can extend the system quickly and easily. | It seems to me your form system could use a bit of a reworking. Why not represent each form as a class, and make the `HandlePostBack` function a method? Then you could detect the form that's been submitted and handle it.
```
class ProfileForm extends Form {
private $form_items = array(
new FormItem('name', 'datatype', 'other_parameters'),
new FormItem('another_name', 'datatype', 'other_parameters'),
...
);
public function render() {
...
}
public function handlePostData() {
...
}
}
```
If you use a standard format for your submit button IDs (something like `<form_name>_submit`, you can do something like this on submission:
```
foreach ($_POST as $key => $value) {
if (substr($key, strlen($key) - 7) == '_submit') {
$className = ucfirst(substr($key, 0, strlen($key) - 7)) . 'Form';
$form = new $className();
$form->handlePostBack();
}
}
``` | I would try to do it differently.
Why do you need a central point for all your posts? This is really bad practice.
Don't try to improve over it, try rethinking the whole idea of having a central point and get rid of it. | Developing a robust PHP postback handler | [
"",
"php",
"mysql",
""
] |
I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)
If anything is unclear I'm very happy to clarify things.
I just implemented a [Trie](http://en.wikipedia.org/wiki/Trie) in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?
My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words **stackoverflow**, **stackbase** and **stackbased**, then the tree would look something like this:
```
[s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
```
Note that one can still think of the edges having one character (the first one of the child node).
*Find*-query is simple to implement.
*Insertion* is not hard, but somewhat more complex than I want.. :(
My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (*Find*(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)
1. k is identical to k'
2. k is a "proper" prefix of k'
3. k' is a "proper" prefix of k
4. k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.
It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?
Thanks :) | At a glance, it sounds like you've implemented a [Patricia Trie](http://portal.acm.org/citation.cfm?id=321481). This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion algorithm.
There's also another compression method you may want to look at: level compression. The idea behind path compression is to replace strings of single child nodes with a single super node that has a "skip" count. The idea behind level compression is to replace full or nearly full subtrees with a super node with a "degree" count that says how many digits of the key the node decodes. There's also a 3rd approach called width compression, but I'm afraid my memory fails me and I couldn't find a description of it with quick googling.
Level compression can shorten the average path considerably, but insertion and removal algorithms get quite complicated as they need to manage the trie nodes as similarly to dynamic arrays. For the right data sets, level compressed trees can be *fast*. From what I remember, they're the 2nd fastest approach for storing IP routing tables, the fastest is some sort of hash trie. | I don't see anything wrong with your approach. If you're looking for a spike solution, perhaps the action taken in case 4 is actually feasible for the first three cases, IE find the common prefix to `k` and `k'` and rebuild the node with that in mind. If it happens that the keys were prefixes of one-another, the resulting trie will still be correct, only the implementation did a bit more work than it really had to. but then again, without any code to look at it's hard to say if this works in your case. | Trie (Prefix Tree) in Python | [
"",
"python",
"algorithm",
"trie",
""
] |
I wrote a C# application that unlocks users when they are locked out of their account (Active Directory). The application searches for users in a specific OU and will list the locked out users in a ComboBox. Then you select that user from the ComboBox and choose unlock.
If you are logged in as an admin, it works perfect. If you are a normal user no.
I want to run my application with admin creds but under a normal user also as secure as possible.
I was reading that maybe program a windows service but I'm unclear on how to program my application to install, run as a service, and run under admin creds. | Looks like you want to impersonate the admin user. Here's an [article and demo](http://www.codeproject.com/KB/cs/cpimpersonation1.aspx). Looks to be written in .Net 1 but should get you started. Also check out the [WindowsIdentity](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx) class. | The goal behind this application strikes me as wrong. You are basically trying to create a means of allowing non-admin users to unlock accounts...which is, for good reason, a feature not available to normal users. | How to run c# application with admin creds? | [
"",
"c#",
"windows-services",
""
] |
I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python.
Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own? | I recommend you should use [StreamHub Comet Server](http://www.streamhub.com/) - its used by a lot of people - personally I use it with a couple of Django sites I run. You will need to write a tiny bit of Java to handle the streaming - I did this using [Jython](http://www.jython.org/). The front-end code is some real simple Javascript a la:
```
StreamHub hub = new StreamHub();
hub.connect("http://myserver.com/");
hub.subscribe("newsfeed", function(sTopic, oData) { alert("new news item: " + oData.Title); });
```
The documentation is pretty good - I had similar problems as you trying to get started with the sparse docs of Cometd et al. For a start I'd read [Getting Started With Comet and StreamHub](http://streamhub.blogspot.com/2009/07/getting-started-with-streamhub-and.html), download and see how some of the examples work and reference the API docs if you need to:
* [Javascript API JSDoc](http://www.streamhub.com/doc/2.0.3/jsdoc/)
* [Streaming from Java Javadoc](http://www.streamhub.com/doc/2.0.3/javadoc/) | [Orbited](http://www.orbited.org/) seems as a nice solution. Haven't tried it though.
---
***Update***: things have changed in the last 2.5 years.
We now have websockets in all major browsers, except IE (naturally) and a couple of very good abstractions over it, that provide many methods of emulating real-time communication.
* [socket.io](http://socket.io/) along with [tornadio](https://github.com/MrJoes/tornadio) (socket.io 0.6) and [tornadio2](https://github.com/MrJoes/tornadio2) (socket.io 0.7+)
* [sock.js](https://github.com/sockjs/sockjs-client) along with [SockJS-tornado](https://github.com/MrJoes/sockjs-tornado) | Python Comet Server | [
"",
"python",
"cometd",
"python-stackless",
""
] |
When I close my C# application, I am getting the a windows sound that indicates an error. However, when I debug through the close process, I get all the way back up into the Program class...
It gets past Application.Run(..), exits the static void Main() function, and then makes the error noise.
Other than the noise there is nothing indicative of an error. I don't even know where to begin looking! Any ideas? | Something is going wrong in the cleanup, that could be very hard to find. There are two ways to attack this:
Enhance the chances of detecting it while you're still in control (in Main) by wrapping everything in your Main in a try/catch and add some code after the Application.Run to get as much of the cleanup going as possible. A few things I can think of:
```
GC.Collect();
GC.WaitForPendingFinalizers();
Thread.Sleep(1000);
GC.Collect();
GC.WaitForPendingFinalizers();
```
Collect at least 2 times, maybe more. In the same spirit, add a few Application.DoEvents() in the OnClosing of the MainForm.
The other approach is more dependent on your code, to take a stab in the dark: look for all static fields/properties you can set to null and Disposable objects you can Dispose deterministically on Exit.
And all this in combination with Fredrik Mörks suggestion for the UnhandledException event. | One thing that you could to in order to maybe get some information is to hook up event listeners for the AppDomain.UnhandledException and Application.ThreadException events. It's a long shot, but may provide some info. You could add the following in the beginning of the Main function to set them up, and have them show any exception info in a message box:
```
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(delegate(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show(e.ExceptionObject.ToString());
});
Application.ThreadException += new ThreadExceptionEventHandler(delegate(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.ToString());
});
// run your app
}
``` | C# Error on Close | [
"",
"c#",
""
] |
I often have code based on a specific well defined algorithm. This gets well commented and seems proper. For most data sets, the algorithm works great.
But then the edge cases, the special cases, the heuristics get added to solve particular problems with particular sets of data. As number of special cases grow, the comments get more and more hazy. I fear going back and looking at this code in a year or so and trying to remember why each particular special case or heuristic was added.
I sometimes wish there was a way to embed or link graphics in the source code, so I could say effectively, "in the graph of this data set, this particular feature here was causing the routine to trigger incorrectly, so that's why this piece of code was added".
What are some best-practices to handle situations like this?
Special cases seem to be always required to handle these unusual/edge cases. How can they be managed to keep the code relatively readable and understandable?
Consider an example dealing with feature recognition from photos (not exactly what I'm working on, but the analogy seems apt). When I find a particular picture for which the general algorithm fails and a special case is needed, I record as best I can that information in a comment, (or as someone suggested below, a descriptive function name). But what is often missing is a permanent link to the particular data file that exhibits the behavior in question. While my comment should describe the issue, and would probably say "see file foo.jp for an example of this behavior", this file is never in the source tree, and can easily get lost.
In cases like this, do people add data files to the source tree for reference? | If you have a knowledge base or a wiki for the project, you could add the graph in it, linking to it in the method as per [Matthew's Fowler quot](https://stackoverflow.com/questions/958003/how-to-manage-special-cases-and-heuristics/958028#958028)e and also in the source control commit message for the edge case change.
```
//See description at KB#2312
private object SolveXAndYEdgeCase(object param)
{
//modify param to solve for edge case
return param;
}
Commit Message: Solution for X and Y edge case, see description at KB#2312
```
It is more work, but a way to document cases more thoroughly than mere test cases or comments could. Even though one might argue that test cases should be documentation enough, you might not want store the whole failing data set in it, for instance.
Remember, vague problems lead to vague solutions. | Martin Fowler said in his refactoring book that when you feel the need to add a comment to your code, first see if you can encapsulate that code into a method and give the method a name that would replace the comment.
so as an abstract you could create a method named.
```
private bool ConditionXAndYHaveOccurred(object param)
{
// code to check for conditions x and y
return result;
}
private object ApplySolutionForEdgeCaseWhenXAndYHappen(object param)
{
//modify param to solve for edge case
return param;
}
```
Then you can write code like
```
if(ConditionXAndYHaveOccurred(myObject))
{
myObject = ApplySolutionForEdgeCaseWhenXAndYHappen(myObject);
}
```
Not a hard and fast concrete example, but it would help with readability in a year or two. | How to manage special cases and heuristics | [
"",
"c++",
"c",
""
] |
I want to write a series of Extension methods to simplify math operations. For example:
Instead of
```
Math.Pow(2, 5)
```
I'd like to be able to write
```
2.Power(5)
```
which is (in my mind) clearer.
The problem is: how do I deal with the different numeric types when writing Extension Methods? Do I need to write an Extension Method for each type:
```
public static double Power(this double number, double power) {
return Math.Pow(number, power);
}
public static double Power(this int number, double power) {
return Math.Pow(number, power);
}
public static double Power(this float number, double power) {
return Math.Pow(number, power);
}
```
Or is there a trick to allow a single Extension Method work for any numeric type?
Thanks! | Unfortunately I think you are stuck with the three implementations. The only way to get multiple typed methods out of a single definition is using generics, but it is not possible to write a generic method that can do something useful specifically for numeric types. | You only need to override Decimal and Double as is noted in this question: [here](https://stackoverflow.com/questions/828807/what-is-the-base-class-for-c-numeric-value-types) | How do I properly write Math extension methods for int, double, float, etc.? | [
"",
"c#",
"extension-methods",
""
] |
I have a process which updates a tree to the database, and in doing so, performs reads to check for duplicates entities.
I'm finding that trying to do a criteria.uniqueResult() midway through this process causes the following error:
> org.hibernate.PropertyValueException:
> not-null property references a null or
> transient value
Digging through the stack trace, I see that the uniqueResult() is flushing the session, attempting to perform updates that aren't ready to go to the database yet.
```
at org.hibernate.engine.Cascade.cascade(Cascade.java:153)
at org.hibernate.event.def.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:154)
at org.hibernate.event.def.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:145)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:88)
at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:58)
at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:996)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1589)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
at org.hibernate.impl.CriteriaImpl.uniqueResult(CriteriaImpl.java:328)
at com.inversion.dal.BaseDAO.findUniqueByCriterion(BaseDAO.java:59)
```
Have I set something up wrong here?
Any help greatly appreciated.
Marty | hibernate remembers with objects needs to be saved. when issuing a select, hibernate will flush these changes. this ensures the select will return the correct results.
setting flushmode to anything else than FlushMode.AUTO will prevent this behaviour. But the error is in your code, where you pass an incomplete object to hibernate to persist or update. So the correct solution is to pass the object later to hibernate, when it is complete. | Turn off auto-flushing on the Session object to fix this exception.
```
Session s;
// if you're doing transactional work
s.setFlushMode(FlushMode.COMMIT);
// if you want to control flushes directly
s.setFlushMode(FlushMode.MANUAL);
```
This is not your error however. Something earlier in your code is causing the in memory objects to be in an invalid state which is trying to be persisted to the DB during the autoflush. | Hibernate calls flush on find- causes not-null error | [
"",
"java",
"hibernate",
"transactions",
""
] |
I have a `checkboxlist` wich contains a list of services loaded from a database table. Each of these services can only be executed alone or with some other specific services. For example, if I select "Transfer Property" I cannot select "Register" at the same time.
I have a table which contains the relationships between Services and what Services can be selected together with each service (did I explained it right?).
What I need is to Click a service and then Disable/Disallow Checking of all the services that don't are related to that service, and Re-enable that items when i Uncheck the parent item...
Is there a good way to do this? I mean, is there any way to do this? | First of all, your CheckBoxList will need to have AutoPostBack set to true.
I believe the key to what youre looking for is
```
CheckBoxList1.Items.FindByText(service).Enabled = false;
```
or this works too
```
CheckBoxList1.Items.FindByText(service).Attributes.Add("disabled", "disabled");
```
in context, it could look something like this:
```
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
//first reset all to enabled
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
CheckBoxList1.Items[i].Attributes.Remove("disabled", "disabled");
}
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
//get list of items to disable
string selectedService = CheckBoxList1.Items[i].Text;
List<string> servicesToDisable = getIncompatibleFor(selectedService);//this function is up to u
foreach (string service in servicesToDisable)
{
CheckBoxList1.Items.FindByText(service).Attributes.Add("disabled", "disabled");
}
}
}
}
``` | ```
void ControlCheckBoxList(int selected, bool val)
{
switch (selected)
{
case 1:
case 2:
case 3:
checkedListBox1.SetItemChecked(5, !val);
break;
case 6:
checkedListBox1.SetItemChecked(1, true);
break;
default:
checkedListBox1.ClearSelected();
break;
}
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
ControlCheckBoxList(e.Index, e.NewValue == CheckState.Checked ? true : false);
}
``` | How to activate/deactivate checklist items dynamically according to checked items? | [
"",
"c#",
".net",
"asp.net",
"visual-studio-2008",
""
] |
Is there an easy way to find parse errors in javascript code?
Last week I was debugging a javascript problem where the first javascript function that was called gave an 'object expected' error. I later determined that this was because the browser wasn't able to parse my javascript code. I eventually solved the problem but it was a painful process that involved pouring over my code line by line, trying to find my mistake.
There must be an easier way. | Use a tool like [Jslint](http://jslint.com) or an alternative browser.
Until recently, IE was the only browser that did not have built in development assistance. Other browsers will a) not come to a grinding halt on the first error they encounter, and b) tell you what and where the problem in your code is.
My favorite "quick ad easy" way to test IE syntax problems is to load the page up in [Opera](http://opera.com). It parses code like IE but will give you meaningful error messages.
I'll clarify with an example:
```
var foo = {
prop1 : 'value',
prop2 : 'value',
prop2 : 'value', // <-- the problem
};
```
If I remember correctly: In IE6 and IE7 the code will break because IE demands leaving the last comma out. The parser throws a fit and the browser simply stops. It may alert some errors but the line numbers (or even filenames) will not be reliable. Firefox and Safari, however, simply ignore the comma. Opera runs the code, but will print an error on the console indicating line number (and more).
Easiest way to write JavaScript is with [Firefox](http://getfirefox.com) + [Firebug](http://getfirebug.com/). Test with IE and have Opera tell you what is breaking when it does. | What browser are you using? IE8 has great build-in feature to debug javascript, for Firefox, Firebug is great. | Finding Parse Errors in Javascript | [
"",
"javascript",
""
] |
How can I get the class that defined a method in Python?
I'd want the following example to print "`__main__.FooClass`":
```
class FooClass:
def foo_method(self):
print "foo"
class BarClass(FooClass):
pass
bar = BarClass()
print get_class_that_defined_method(bar.foo_method)
``` | ```
import inspect
def get_class_that_defined_method(meth):
for cls in inspect.getmro(meth.im_class):
if meth.__name__ in cls.__dict__:
return cls
return None
``` | I don't know why no one has ever brought this up or why the top answer has 50 upvotes when it is slow as hell, but you can also do the following:
```
def get_class_that_defined_method(meth):
return meth.im_class.__name__
```
For python 3 I believe this changed and you'll need to look into `.__qualname__`. | Get class that defined method | [
"",
"python",
"python-2.6",
"python-datamodel",
""
] |
Is there any way to bulk-delete a bunch of objects matching a given query in LINQ or LINQ-to-Entities? The only references that I can find are outdated, and it seems silly to iterate over and manually delete all objects I wish to remove. | The question is an old one (from before EF5 existed). For anyone who's using EF5, [EntityFramework.Extended](https://github.com/loresoft/EntityFramework.Extended) does this in a snap. | A while back I wrote a 4 part blog series (Parts [1](http://blogs.msdn.com/alexj/archive/2007/12/07/rolling-your-own-sql-update-on-top-of-the-entity-framework-part-1.aspx), [2](http://blogs.msdn.com/alexj/archive/2008/01/15/rolling-your-own-sql-update-on-top-of-the-entity-framework-part-2.aspx), [3](http://blogs.msdn.com/alexj/archive/2008/02/11/rolling-your-own-sql-update-on-top-of-the-entity-framework-part-3.aspx) and [4](http://blogs.msdn.com/alexj/archive/2008/02/11/rolling-your-own-sql-update-on-top-of-the-entity-framework-part-4.aspx)) covering doing bulk updates (with one command) in the Entity Framework.
While the focus of that series was update, you could definitely use the principles involved to do delete.
So you should be able to write something like this:
```
var query = from c in ctx.Customers
where c.SalesPerson.Email == "..."
select c;
query.Delete();
```
All you need to do is implement the Delete() extension method. See the post series for hints on how...
Hope this helps | Bulk-deleting in LINQ to Entities | [
"",
"c#",
"database",
"linq",
"entity-framework",
"linq-to-entities",
""
] |
I'm trying to implement a C# method that can log a message with a format string and a variable number of printf-style arguments. Ideally, it would work identically to the C function I pasted below, although idiomatic to C# of course.
```
static
void
LogMessage(const char * iFormat, ...)
{
va_list argp;
FILE * fp;
fp = fopen("log.txt", "a");
if (fp != NULL) {
va_start(argp, iFormat);
vfprintf(fp, iFormat, argp);
va_end(argp);
fprintf(fp, "\n");
fclose(fp);
}
}
```
This function is convenient for me, as it allows me to make the following calls:
```
LogMessage("Testing");
LogMessage("Testing %s", "1 2 3");
LogMessage("Testing %d %d %d", 1, 2, 3);
``` | ```
static void LogMessage(string format, params object[] args) {
File.AppendAllText("log.txt", string.Format(format, args));
}
LogMessage("Testing {0} {1}", 1, "hi");
``` | You want to create a [variadic function](http://en.wikipedia.org/wiki/Variadic_function)
C# uses the [params](http://msdn.microsoft.com/en-us/library/w5zay9db.aspx) keyword to do this
```
static void LogMessage(string formatString, params string[] formatArguments)
{
string.Format(formatString, formatArguments);
}
```
Please note that the params keyword can only be used on the **last** parameter in the method signature and that it requires the parameter to be an **array**.
This is merely syntactic sugar for actually passing an array. | Log a message with a variable number of printf-style arguments | [
"",
"c#",
"logging",
"variadic-functions",
""
] |
Having a look on the PHP documentation, the following two methods of the `DateTime` object would both seem to solve my problem:
* [DateTime::diff](http://au.php.net/manual/en/datetime.diff.php) : Get the difference and use that to determine which is more ancient.
* [DateTime::getTimestamp](http://au.php.net/manual/en/datetime.gettimestamp.php) : Get the UNIX timestampt and compare those.
Both these methods are marked in the [doco](http://au.php.net/datetime) as being available in version >= 5.3 (and, not surprisingly, if I try to call them I find they don't exist). I can't find any specific documentation for 5.2.8 so I am not sure if there are equivalent methods in my version. I have [Googled](http://www.google.com.au/search?q=compare+DateTime+PHP&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) the problem and found an eclectic range of solutions, none of which answer my very simple requirements:
* How do I compare two DateTime objects?
* Where can I find the doco for previous PHP versions? Specifically version 5.2.8?
For some context, I have the following code:
```
$st_dt = new DateTime(verifyParam ('start_date'));
$end_dt = new DateTime(verifyParam ('end_date'));
// is the end date more ancient than the start date?
if ($end_dt < $start_dt)
```
Apparently there is no comparison operator on this guy.
## Edit
*Apparently* my assumptions were completely false (thanks Milen for illustrating this so effectively). There is a comparison operator and it works just fine thanks. Sometimes I really miss a compiler. The bug is in the code above, I am sure you will find it much faster than I did :). | The following seems to confirm that there are comparison operators for the DateTime class:
```
dev:~# php
<?php
date_default_timezone_set('Europe/London');
$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
?>
bool(false)
bool(true)
bool(false)
dev:~# php -v
PHP 5.2.6-1+lenny3 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 26 2009 20:09:03)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
dev:~#
``` | From [the official documentation](http://php.net/manual/en/datetime.diff.php#example-2554):
> As of PHP 5.2.2, DateTime objects can be compared using [comparison operators](http://php.net/manual/en/language.operators.comparison.php).
```
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");
var_dump($date1 == $date2); // false
var_dump($date1 < $date2); // true
var_dump($date1 > $date2); // false
```
For PHP versions before 5.2.2 (actually for any version), you can use [diff](http://php.net/manual/en/datetime.diff.php).
```
$datetime1 = new DateTime('2009-10-11'); // 11 October 2013
$datetime2 = new DateTime('2009-10-13'); // 13 October 2013
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // +2 days
``` | How do I compare two DateTime objects in PHP 5.2.8? | [
"",
"php",
"datetime",
""
] |
Say I want to manipulate some files on a floppy drive or a USB card reader. How do I check to see if the drive in question is ready? (That is, has a disk physically inserted.)
The drive letter *exists*, so os.exists() will always return True in this case. Also, at this point in the process I don't yet know any file names, so checking to see if a given file exists also won't work.
Some clarification: the issue here is exception handling. Most of the win32 API calls in question just throw an exception when you try to access a drive that isn't ready. Normally, this would work fine - look for something like the free space, and then catch the raised exception and assume that means there isn't a disk present. However, even when I catch any and all exceptions, I still get an angry exception dialog box from Windows telling me the floppy / card reader isn't ready. So, I guess the real question is - how do I suppress the windows error box? | And the answer, as with so many things, turns out to be in [an article about C++/Win32 programming from a decade ago](http://bcbjournal.org/articles/vol2/9806/Detecting_disk_errors.htm).
The issue, in a nutshell, is that Windows handles floppy disk errors slightly differently than other kinds of drive errors. By default, no matter what you program does, or **thinks** it's doing, Windows will intercept any errors thrown by the device and present a dialog box to the user rather than letting the program handle it - the exact issue I was having.
But, as it turns out, there's a Win32 API call to solve this issue, primarily `SetErrorMode()`
In a nutshell (and I'm handwaving a way a lot of the details here), we can use `SetErrorMode()` to get Windows to stop being quite so paranoid, do our thing and let the program handle the situation, and then reset the Windows error mode back to what it was before as if we had never been there. (There's probably a Keyser Soze joke here, but I've had the wrong amount of caffeine today to be able to find it.)
Adapting the C++ sample code from the linked article, that looks about like this:
```
int OldMode; //a place to store the old error mode
//save the old error mode and set the new mode to let us do the work:
OldMode = SetErrorMode(SEM_FAILCRITICALERRORS);
// Do whatever we need to do that might cause an error
SetErrorMode(OldMode); //put things back the way they were
```
Under C++, detecting errors the right way needs the `GetLastError()' function, which we fortunately don't need to worry about here, since this is a Python question. In our case, Python's exception handling works fine. This, then, is the function I knocked together to check a drive letter for "readiness", all ready for copy-pasting if anyone else needs it:
```
import win32api
def testDrive( currentLetter ):
"""
Tests a given drive letter to see if the drive is question is ready for
access. This is to handle things like floppy drives and USB card readers
which have to have physical media inserted in order to be accessed.
Returns true if the drive is ready, false if not.
"""
returnValue = False
#This prevents Windows from showing an error to the user, and allows python
#to handle the exception on its own.
oldError = win32api.SetErrorMode( 1 ) #note that SEM_FAILCRITICALERRORS = 1
try:
freeSpace = win32file.GetDiskFreeSpaceEx( letter )
except:
returnValue = False
else:
returnValue = True
#restore the Windows error handling state to whatever it was before we
#started messing with it:
win32api.SetErrorMode( oldError )
return returnValue
```
I've been using this quite a bit the last few days, and it's been working beautifully for both floppies and USB card readers.
A few notes: pretty much any function needing disk access will work in the try block - all we're looking for in an exception due to the media not being present.
Also, while the python `win32api` package exposes all the functions we need, it dones't seem to have any of the flag constants. After a trip to the ancient bowels of MSDN, it turns out that SEM\_FAILCRITICALERRORS is equal to 1, which makes our life awfully easy.
I hope this helps someone else with a similar problem! | You can compare `len(os.listdir("path"))` to zero to see if there are any files in the directory. | How do I check if a disk is in a drive using python? | [
"",
"python",
"windows",
""
] |
Bear with me as I try to simplify my issue as much as possible.
I am creating a new ORM object. This object has an auto generated primary key which is created on the database using as an identity. Within this object, is a child object with a many to one relationship with the parent object. **One of the attributes I need to set to create the child object is primary key of the parent object, *which has not been generated yet*.** It is important to note that the primary key of the child object is a **composite key that includes the primary key of the parent object**.
[Diagram http://xs941.xs.to/xs941/09291/fieldrule.1degree221.png](http://xs941.xs.to/xs941/09291/fieldrule.1degree221.png)
In this diagram FieldRule is the *child table* and SearchRule is the *parent table*. The problem is that SearchRuleId has not been generated when I am creating FieldRule objects. So there is no way to link them.
How do I solve this problem?
---
Here is are some relevant snippets from the entity classes, which use annotation based mappings.
From *SearchRule.java* (Parent Class):
```
public class SearchRule implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = true)
@Column(name = "ID")
private Integer id;
@Basic(optional = false)
@Column(name = "Name", unique = true)
private String name;
@Basic(optional = false)
@Column(name = "Threshold")
private int threshold;
@Basic(optional = false)
@Column(name = "LastTouched", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date lastTouched;
@Column(name = "TouchedBy")
private String touchedBy;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "searchRule", fetch = FetchType.LAZY)
private Collection<FieldRule> fieldRuleCollection;
@JoinColumn(name = "IndexTemplateId", referencedColumnName = "ID")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private IndexTemplate indexTemplateId;
```
From *FieldRule.java* (Child Class):
```
public class FieldRule implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected FieldRulePK fieldRulePK;
@Basic(optional = false)
@Column(name = "RuleValue")
private String ruleValue;
@JoinColumns({@JoinColumn(name = "IndexTemplateId", referencedColumnName = "IndexTemplateId", insertable = false, updatable = false), @JoinColumn(name = "FieldNumber", referencedColumnName = "FieldNumber", insertable = false, updatable = false)})
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Field field;
@JoinColumn(name = "SearchRuleId", referencedColumnName = "ID", insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private SearchRule searchRule;
```
From *FieldRulePK.java* (Child PK Class):
```
@Embeddable
public class FieldRulePK implements Serializable {
@Basic(optional = false)
@Column(name = "IndexTemplateId")
private Integer indexTemplateId;
@Basic(optional = false)
@Column(name = "FieldNumber")
private Integer fieldNumber;
@Basic(optional = false)
@Column(name = "SearchRuleId")
private Integer searchRuleId;
``` | I think the problem is with the way you're doing your mapping, where you're trying to pull too many database concepts into your OO model. ORM was a little confusing to me as well, when I started doing it. What you need to understand is that the concept of a primary key field is a database concept and not an OO concept. In OO, each object reference is unique, and that's what you use to *identify* instances.
Object references do not really map well to the database world, and that's why we have primary key properties. With that said, the use of primary key properties should be kept to a minimal. What I find helpful is to minimize the type of primary key *properties* that map directly to the primary key *columns* (usually, integer properties that map to a primary key column).
Anyway, based on that, here's how I think you should do your mapping (changes highlighted with horizontal separators):
From *FieldRule.java* (Child Class):
```
public class FieldRule implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected FieldRulePK fieldRulePK;
@Basic(optional = false)
@Column(name = "RuleValue")
private String ruleValue;
```
---
```
// Removed field and searchRule mapping as those are already in the
// primary key object, updated setters/getters to pull properties from
// primary key object
public Field getField() {
return fieldRulePK != null ? fieldRulePK.getField() : null;
}
public void getField(Field field) {
// ... parameter validation ...
if (fieldRulePK == null) fieldRulePK = new FieldRulePK();
fieldRulePK.setField(field);
}
public SearchRule getSearchRule() {
return fieldRulePK != null ? fieldRulePK.getSearchRule() : null;
}
public void setSearchRule(SearchRule searchRule) {
// ... parameter validation ...
if (fieldRulePK == null) fieldRulePK = new FieldRulePK();
fieldRulePK.setSearchRule(searchRule);
}
```
---
From `FieldRulePK.java` (Child PK Class):
```
@Embeddable
public class FieldRulePK implements Serializable {
```
---
```
// Map relationships directly to objects instead of using integer primary keys
@JoinColumns({@JoinColumn(name = "IndexTemplateId", referencedColumnName = "IndexTemplateId", insertable = false, updatable = false), @JoinColumn(name = "FieldNumber", referencedColumnName = "FieldNumber", insertable = false, updatable = false)})
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Field field;
@JoinColumn(name = "SearchRuleId", referencedColumnName = "ID", insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private SearchRule searchRule;
```
---
`SearchRule.java` should be fine as it is.
I hope this all makes sense.
*Note that this is untested, it would take too much time for me to set up a test database and create all the necessary test code, but I hope it gives you an idea on how to proceed.* | Why do you have to set the primary key of the initial object in the sub-objects? With a proper mapping the reference will get set by the JPA application automatically.
So the answer is: do a correct mapping.
If you need a more detailed answer provide a more detailed question. Including:
* source code of the involved classes
* source code used to create and persist the instances
* exceptions experienced
* information on which jpa implementation you use
Edit, after more details where provided in the question:
I think your embeddable PK should look something like this:
```
@Embeddable
public class FieldRulePK implements Serializable {
@Basic(optional = false)
@Column(name = "IndexTemplateId")
private Integer indexTemplateId;
@Basic(optional = false)
@Column(name = "FieldNumber")
private Integer fieldNumber;
@ManyToOne( ... some not so trivial details here ..)
private SearchRule searchRule;
}
```
And the searchRule property of your FieldRule should be dropped. The entity reference in the embeddable should result in an id field in the database. | Handling creation of ORM objects prior to persistence/generation of primary keys? | [
"",
"java",
"orm",
"jpa",
"persistence",
"primary-key",
""
] |
### Error:
> Fatal error: Call to a member function
> bind\_param() on a non-object in
> /var/www/web55/web/pdftest/events.php
> on line 76
### Code:
```
public function countDaysWithoutEvents(){
$sql = "SELECT 7 - COUNT(*) AS NumDaysWithoutEvents
FROM
(SELECT d.date
FROM cali_events e
LEFT JOIN cali_dates d
ON e.event_id = d.event_id
WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())
AND c.category_id = ?
GROUP BY DAY(d.date)
) AS UniqueDates";
$stmt = $this->link->prepare($sql);
$stmt->bind_param('i', $this->locationID);
$stmt->execute();
$stmt->bind_result($count);
$stmt->close();
return $count;
}
```
`$this->link->prepare($sql)` creates a prepared statement for MySQLi.
Why am I getting this error? | `AND c.category_id = ?` - there is no table alias c in your query.
Besides that try
```
$stmt = $this->link->prepare($sql);
if (!$stmt) {
throw new ErrorException($this->link->error, $this->link->errno);
}
if (!$stmt->bind_param('i', $this->locationID) || !$stmt->execute()) {
throw new ErrorException($stmt->error, $stmt->errno);
}
``` | I think the problem is obviously with the **prepare** function..
The function is probably failing, in which case $stmt would be FALSE and hence not have the bind\_param method as a member.
> From the [php mysqli manual](http://www.php.net/manual/en/mysqli.prepare.php):
> mysqli\_prepare() returns a statement object or FALSE if an error occurred.
Check your query! Maybe there is a problem with your SELECT statement. And also check for FALSE before trying to execute any member function on what you think is an object returned by the prepare function.
```
if($stmt === FALSE)
die("Prepare failed... ");// Handle Error Here
// Normal flow resumes here
$stmt->bind_param("i","");
```
I would suspect that the statement may be erroring out because of the sub-query:
```
SELECT d.date
FROM cali_events e
LEFT JOIN cali_dates d
ON e.event_id = d.event_id
WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())
AND c.category_id = ?
GROUP BY DAY(d.date)
```
Instead, why don't you write your query like this:
```
public function countDaysWithoutEvents()
{
$count = FALSE;
$sql = "SELECT COUNT(d.date) ";
$sql .= " FROM cali_events e ";
$sql .= " LEFT JOIN cali_dates d ON e.event_id = d.event_id ";
$sql .= " WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE()) ";
$sql .= " AND c.category_id = ? ";
$sql .= " GROUP BY DAY(d.date) ";
$stmt = $this->link->prepare($sql);
if($stmt !== FALSE)
{
$stmt->bind_param('i', $this->locationID);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch(); // I think you need to do a fetch
// here to get the result data..
$stmt->close();
}else // Or, provide your own error
die("Error preparing Statement"); // handling here
return (7 - $count);
}
```
*P.S. I think you also had a missing a call to **fetch** as well..* (see example above) | Why do I get this function call error on an non-object when I am calling a function on an object? | [
"",
"php",
"mysqli",
"prepared-statement",
""
] |
I have a java program that runs a bunch of queries against an sql server database. The first of these, which queries against a view returns about 750k records. I can run the query via sql server management studio, and I get results in about 30 seconds. however, I kicked off the program to run last night. when I checked on it this morning, this query still had not returned results back to the java program, some 15 hours later.
I have access to the database to do just about anything I want, but I'm really not sure how to begin debugging this. What should one do to figure out what is causing a situation like this? I'm not a dba, and am not intimately familiar with the sql server tool set, so the more detail you can give me on how to do what you might suggest would be appreciated.
heres the code
```
stmt = connection.createStatement();
clientFeedRS = stmt.executeQuery(StringBuffer.toString());
```
EDIT1:
Well it's been a while, and this got sidetracked, but this issue is back. I looked into upgrading from jdbc driver v 1.2 to 2.0, but we are stuck on jdk 1.4, and v 2.0 require jdk 1.5 so that's a non starter. Now I'm looking at my connection string properties. I see 2 that might be useful.
```
SelectMethod=cursor|direct
responseBuffering=adaptive|full
```
Currently, with the latency issue, I am running with cursor as the selectMethod, and with the default for responseBuffering which is full. Is changing these properties likely to help? if so, what would be the ideal settings? I'm thinking, based on what I can find online, that using a direct select method and adaptive response buffering might solve my issue. any thoughts?
EDIT2:
WEll I ended changing both of these connection string params, using the default select method(direct) and specifying the responseBuffering as adaptive. This ends up working best for me and alleviates the latency issues I was seeing. thanks for all the help. | Be sure that your JDBC driver is configured to use a direct connection and not a cusror based connection. You can post your JDBC connection URL if you are not sure.
Make sure you are using a forward-only, read-only result set (this is the default if you are not setting it).
And make sure you are using updated JDBC drivers.
If all of this is not working, then you should look at the sql profiler and try to capture the sql query as the jdbc driver executes the statement, and run that statement in the management studio and see if there is a difference.
Also, since you are pulling so much data, you should be try to be sure you aren't having any memory/garbage collection slowdowns on the JVM (although in this case that doesn't really explain the time discrepancy). | I had similar problem, with a very simple request (SELECT . FROM . WHERE = .) taking up to 10 seconds to return a single row when using a jdbc connection in Java, while taking only 0.01s in sqlshell. The problem was the same whether i was using the official MS SQL driver or the JTDS driver.
The solution was to setup this property in the jdbc url :
***sendStringParametersAsUnicode=false***
Full example if you are using MS SQL official driver : ***jdbc:sqlserver://yourserver;instanceName=yourInstance;databaseName=yourDBName;sendStringParametersAsUnicode=false;***
Instructions if using different jdbc drivers and more detailled infos about the problem here : <http://emransharif.blogspot.fr/2011/07/performance-issues-with-jdbc-drivers.html>
> SQL Server differentiates its data types that support Unicode from the ones that just support ASCII. For example, the character data types that support Unicode are nchar, nvarchar, longnvarchar where as their ASCII counter parts are char, varchar and longvarchar respectively. By default, all Microsoft’s JDBC drivers send the strings in Unicode format to the SQL Server, irrespective of whether the datatype of the corresponding column defined in the SQL Server supports Unicode or not. In the case where the data types of the columns support Unicode, everything is smooth. But, in cases where the data types of the columns do not support Unicode, serious performance issues arise especially during data fetches. SQL Server tries to convert non-unicode datatypes in the table to unicode datatypes before doing the comparison. Moreover, if an index exists on the non-unicode column, it will be ignored. This would ultimately lead to a whole table scan during data fetch, thereby slowing down the search queries drastically.
In my case, i had 30M+ records in the table i was searching from. The duration to complete the request went from more than 10 seconds, to approximatively 0.01s after applying the property.
Hope this will help someone ! | sql server query running slow from java | [
"",
"java",
"sql-server-2005",
"jdbc",
"connection-string",
""
] |
I have inherited a number of grossly coded PHP files, whose output I need to alter programmatically.
To achieve this, I chose to run them through another PHP file, rewriter.php, which looks approximately like this:
```
<?php
if(!preg_match('/^([a-zA-Z0-9\-_]*)$/', $_GET['page']))
die('Incorrect page supplied.');
ob_start('changeOutput');
include($_GET['page'].'.php');
ob_end_flush();
function changeOutput ($buffer) {
...
}
?>
```
I use mod\_rewrite to force them to run through this file:
```
RewriteEngine On
RewriteRule ^([^\.]*)\.php$ rewriter.php?page=$1
```
However an error message is displayed which makes me believe that the include() statement is affected by the RewriteRule above, i.e. it tries to run rewriter.php through rewriter.php and so on.
I suppose there are many ways to tackle this problem but I am specifically looking for a way to escape the include() statement from being affected by mod\_rewrite. I looked through the module documentation but I couldn't find anything relevant.
Of course, alternatives to this approach are welcome too.
Thank you for your time and thinking.
Best regards,
Daniel | Sounds like you're looking for RewriteCond, which is essentially a conditional statement for mod\_rewrite
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !rewriter.php$
RewriteRule ^([^\.]*)\.php$ rewriter.php?page=$1 [L]
```
This will prevent your rule from being applied to URLs that end in rewriter.php. | You should first check if the file exists before including it:
```
if ($_GET['page'] != 'rewriter' && is_file($_GET['page'].'.php')) {
include $_GET['page'].'.php';
} else {
// file does not exist or is invalid
}
``` | PHP include() affected by mod_rewrite | [
"",
"php",
"apache",
"mod-rewrite",
""
] |
given the following:
```
class A : B {}
interface I
{
B TheObject {get;set;}
}
```
can I do this somehow?
```
class C : I
{
public A TheObject {get;set;}
}
```
note the interface has the base class and the implementation has the sub class. | Give this a try
```
class C : I
{
public A TheObject {get;set;}
B I.TheObject
{
get { return A; }
set { A = value as A; }
}
}
```
You may need to modify the B setter, depending on your needs. Implementing an interface this way has the following consequences. When dealing with a variable typed as a C you will not be able to access B TheObject. If you need to you will need to declare an I variable and assign it to your C var. Implementing I this way is known as an explicit implementation.
eg
```
C c = new C();
A a = c.TheObject; // TheObject is an A
I i = c;
B b = i.TheObject;
``` | You can't do it because the return type of the interface implementation must match. But, my reasoning behind why you can't do it was wrong (as pointed out in the comments). You must match the signature, but you can return a new A from C ...
```
public class C : I
{
public B TheObject { get { return new A(); } set {} }
}
``` | Can I implement an interface using a subclass in C#? | [
"",
"c#",
""
] |
Variable `x` is int with possible values: `-1, 0, 1, 2, 3`.
Which expression will be faster (in CPU ticks):
```
1. (x < 0)
2. (x == -1)
```
Language: C/C++, but I suppose all other languages will have the same.
P.S. I personally think that answer is `(x < 0)`.
More widely for gurus: what if `x` from `-1` to `2^30`? | That depends entirely on the ISA you're compiling for, and the quality of your compiler's optimizer. Don't optimize prematurely: **profile first to find your bottlenecks**.
That said, in x86, you'll find that both are equally fast in most cases. In both cases, you'll have a comparison (`cmp`) and a conditional jump (`jCC`) instructions. However, for `(x < 0)`, there may be some instances where the compiler can elide the `cmp` instruction, speeding up your code by *one whole cycle*.
Specifically, if the value `x` is stored in a register and was recently the result of an arithmetic operation (such as `add`, or `sub`, but there are many more possibilities) that sets the sign flag SF in the EFLAGS register, then there's no need for the `cmp` instruction, and the compiler can emit just a `js` instruction. There's no simple `jCC` instruction that jumps when the input was -1. | Try it and see! Do a million, or better, a billion of each and time them. I bet there is no statistical significance in your results, but who knows -- maybe on your platform and compiler, you might find a result.
This is a great experiment to convince yourself that premature optimization is probably not worth your time--and may well be "[the root of all evil--at least in programming](http://en.wikiquote.org/wiki/Donald_Knuth)". | What is faster (x < 0) or (x == -1)? | [
"",
"c++",
"c",
"performance",
"optimization",
"cpu",
""
] |
I want to copy the file c:\a1\b2\c3\foo.txt to d:\a1\b2\c3\foo.txt. The subdirectories don't exist on the D drive, and if I try to do a direct CopyTo() I'll get an IO exception.
I haven't been able to find any built-in c# function that does the dirty work of creating the missing directories. So I wrote this:
```
FileInfo file = new FileInfo(@"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");
if (!destDir.Exists) // false
CreateDirectory(destDir, null);
file.CopyTo(file.FullName.Replace("c:", "d:"), true);
private void CreateDirectory(DirectoryInfo endDir, Stack<DirectoryInfo> trail)
{
if (trail == null)
{
trail = new Stack<DirectoryInfo>();
trail.Push(endDir);
}
// remove last directory - c:\a1\b2\c3, c:\a1\b2, c:\a1
Match theMatch = Regex.Match(endDir.FullName, @".*(?=\\\w*\Z)");
DirectoryInfo checkDir = new DirectoryInfo(theMatch.ToString());
if (!checkDir.Exists)
{
trail.Push(checkDir);
CreateDirectory(checkDir, trail);
}
else
foreach (DirectoryInfo dir in trail)
Directory.CreateDirectory(dir.FullName);
}
```
That's pretty involved, and as they like to say on late-night informercials, "There's got to be a better way!"
Question: how would I make the function above move efficient? And am I missing a built-in method that already does everything I'm doing the hard way? | ```
Directory.CreateDirectory(@"c:\foo\bar\baz");
```
[Documented](http://msdn.microsoft.com/en-us/library/54a0at6s.aspx) as creating all required directories, and works for me.
> Any and all directories specified in
> path are created, unless they already
> exist or unless some part of path is
> invalid. The path parameter specifies
> a directory path, not a file path. If
> the directory already exists, this
> method does nothing. | Or you can just use `Directory.CreateDirectory()` directly, since it already creates all the intermediate paths. | CopyTo() to a directory that doesn't yet exist | [
"",
"c#",
"recursion",
"directory",
""
] |
My initial strategy at developing forms was like this: the form post back to the same page and in the page handler I start by looking for POST variables and taking appropriate actions, then display the page content. It was all looking rosy in the beginning. I would place a hidden field inside my form and the page to keep track of current state and I could implement a state machine on the page to display the page in View, Edit or Add states. But 2 months later my pages have turned into hideous stateful monsters, riddled with IFs and branches, impossible to maintain, the state exchanged between page and client in hidden fields has is 'weight challenged', I just can't stand how it all turned out.
What am I doing wrong? Is this inherently hard? I'm down a slippery slope of reinventing ASP web forms? How is this done properly?
The technology behind (PHP) is irrelevant. My question is basically how to do HTTP forms that do more than simply take 2 fields and forward you to a 'thank you' page. | You've really done nothing *wrong* per se, except ignore scalability. For your initial scope, the POST handing worked like a charm, but as applications grow, or more projects begin using your custom framework, more and more code gets repeated and you'll find yourself rewriting things you've already done from scratch which snowballs into a maintenance nightmare.
The solution is to use an established framework such as [CodeIgniter](http://codeigniter.com/), [CakePHP](http://cakephp.org/), [Symfony](http://www.symfony-project.org/) or any other so that you'll essentially never be repeating common tasks, and all your applications will have the same structure and flow. There are simple videos to get you started on any of these.
I assume you're trying to mimic the `ViewState` when you mention ASP.NET, which isn't really necessary. Each of these frameworks have built-in methods to handle form submission and validation - and combined with some client-side technology such as [jQuery](http://jquery.com), you can build rich applications quite easily. | if you want a more 'stateless' feel, check out sessions.
<https://www.php.net/manual/en/book.session.php>
your method works fairly well for small-scale and independent forms, but you need something a little better for your larger web applications. | HTTP forms using raw PHP | [
"",
"php",
"html",
"http",
""
] |
How to store .zip file in SQL SERVER 2005 database programatically?
And how to retrieve it back?
If you think that storing a .zip file into a database is not an elegant way, please tell me
the idea of making a better approach / standard practice for the same
I am using C#, Asp.net and Sql Server 2005
Please send me the code. | There are a couple of methods that you can employ. The simplest is to leave the files on the filesystem, and to store the file path inside SQL Server. Your app would retrieve the file path at runtime, and use said path to load the file. Storing in the filesystem also has it's disadvantages though - files aren't backed up with the database, changes to the file location, or file deletion won't update SQL Server, and so on.
Storing within SQL Server is certainly an option as well. You're on SQL Server 2005, so you won't be able to use the FILESTREAM feature (introduced in SQL Server 2008), but you will be able to store it in a native SQL Server blob type.
Here's [a good introduction](http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1273934_mem1,00.html) to blob types in SQL Server by Denny Cherry.
Here's [an example](http://www.akadia.com/services/dotnet_read_write_blob.html) of writing blobs using C#. | You can store a binary file in a `VARBINARY(MAX)` column in SQL Server 2005 or 2008. You can also use an `IMAGE` column (which was the only option until SQL Server 2005) but that will be less performant.
Here's the gist in C# 1.0 compatible code.
```
create table TBL_ZIP_BLOB
(
ID unqiuidentifier primary key clustered not null
default newid()
,BLOB varbinary(max) not null,
,NAME nvarchar(255) not null
)
public void InsertZipBlob(Guid id, byte[] bytes, string name)
{
SqlDbCommand.CommandText = @"insert into TBL_ZIP_BLOB(BLOB,NAME) values(@blob,@name)";
using( SqlCommand cmd = MethodToGetValidCommandObject() )
{
cmd.CommandText = "insert into TBL_ZIP_BLOB(ID, BLOB,NAME) values(@id,@blob,@name)";
cmd.Parameters.Add("@id",SqlDbType.UniqueIdentifier).Value = id;
cmd.Parameters.Add("@blob",SqlDbType.Image).Value = bytes;
cmd.Parameters.Add("@name",SqlDbType.NVarChar,128).Value = name;
cmd.ExecuteNonQuery();
}
}
public void SendZipBlobToResponse(Guid id, HttpResponse response)
{
byte[] bytes = new byte[0];
string name = "file.zip";
using( SqlCommand cmd = MethodToGetValidCommandObject() )
{
cmd.ComandText = "select BLOB,NAME from TBL_ZIP_BLOB where ID = @id";
cmd.Parameters.Add("@id",SqlDbType.UniqueIdentifier).Value = id;
using( IDataReader reader = cmd.ExecuteReader() )
{
if( reader.Read() )
{
name = (string)reader["NAME"];
bytes = (byte[])reader["BLOBIMG"];
}
}
}
if (bytes.Length > 0)
{
response.AppendHeader( "Content-Disposition", string.Format("attachment; filename=\"{0}\""),name);
response.AppendHeader( "Content-Type","application/zip" );
const int CHUNK = 1024;
byte[] buff = new byte[CHUNK];
for( long i=0; i<Bytes.LongLength; i+=CHUNK )
{
if( i+CHUNK > bytes.LongLength )
buff = new byte[Bytes.LongLength-i];
Array.Copy( Bytes, i, buff, 0, buff.Length );
response.OutputStream.Write( buff, 0, buff.Length );
response.OutputStream.Flush();
}
}
}
``` | Store and Retrieve .ZIP file in SQL SERVER 2005 | [
"",
"c#",
"asp.net",
"sql-server-2005",
""
] |
Is there a way (e.g., via an event?) to determine when a Swing component becomes 'displayable' -- as per the Javadocs for [`Component`.getGraphics](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html#getGraphics())?
The reason I'm trying to do this is so that I can then call `getGraphics()`, and pass that to my 'rendering strategy' for the component.
I've tried adding a `ComponentListener`, but `componentShown` doesn't seem to get called. Is there anything else I can try?
Thanks.
And additionally, is it OK to keep hold of the `Graphics` object I receive? Or is there potential for a new one to be created later in the lifetime of the `Component`? (e.g., after it is resized/hidden?) | Add a HierarchyListener
```
public class MyShowingListener {
private JComponent component;
public MyShowingListener(JComponent jc) { component=jc; }
public void hierarchyChanged(HierarchyEvent e) {
if((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED)>0 && component.isShowing()) {
System.out.println("Showing");
}
}
}
JTable t = new JTable(...);
t.addHierarchyListener(new MyShowingListener(t));
``` | You can listen for a resize event. When a component is first displayed, it is resized from 0,0 to whatever the layout manager determines (if it has one). | When is a Swing component 'displayable'? | [
"",
"java",
"swing",
"graphics",
""
] |
I have some data
```
id ref
== ==========
1 3536757616
1 3536757617
1 3536757618
```
and want to get the result
```
1 3536757616/7/8
```
so essentially the data is aggregated on id, with the refs concatenated together, separated by a slash '/', but with any common prefix removed so if the data was like
```
id ref
== ==========
2 3536757628
2 3536757629
2 3536757630
```
I would want to get the result
```
2 3536757629/28/30
```
I know I can simply concatenate the refs by using
```
SELECT distinct
id,
stuff ( ( SELECT
'/ ' + ref
FROM
tableA tableA_1
where tableA_1.id = tableA_2.id
FOR XML PATH ( '' ) ) , 1 , 2 , '' )
from TableA tableA_2
```
to give
```
1 3536757616/ 3536757617/ 3536757618
2 3536757628/ 3536757629/ 3536757630
```
but it's the bit that removes the common element that I'm after.....
---
Code for test data :
```
create table tableA (id int, ref varchar(50))
insert into tableA
select 1, 3536757616
union select 1, 3536757617
union select 1, 3536757618
union select 2, 3536757628
union select 2, 3536757629
union select 2, 3536757630
``` | ```
WITH hier(cnt) AS
(
SELECT 1
UNION ALL
SELECT cnt + 1
FROM hier
WHERE cnt <= 100
)
SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY id) = 1 THEN ref ELSE ' / ' + SUBSTRING(ref, mc + 1, LEN(ref)) END
FROM (
SELECT MIN(common) AS mc
FROM (
SELECT (
SELECT MAX(cnt)
FROM hier
WHERE SUBSTRING(initref, 1, cnt) = SUBSTRING(ref, 1, cnt)
AND cnt <= LEN(ref)
) AS common
FROM (
SELECT TOP 1 ref AS initref
FROM tableA
) i,
tableA
) q
) q2, tableA
FOR XML PATH('')
---
3536757616 / 17 / 18 / 28 / 29 / 30
```
Same thing with groups:
```
WITH hier(cnt) AS
(
SELECT 1
UNION ALL
SELECT cnt + 1
FROM hier
WHERE cnt <= 100
)
SELECT (
SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY a2.ref) = 1 THEN ref ELSE ' / ' + SUBSTRING(ref, mc + 1, LEN(ref)) END
FROM tableA a2
WHERE a2.id = q2.id
FOR XML PATH('')
)
FROM (
SELECT id, MIN(common) AS mc
FROM (
SELECT a.id,
(
SELECT MAX(cnt)
FROM hier
WHERE SUBSTRING(i.initref, 1, cnt) = SUBSTRING(a.ref, 1, cnt)
AND cnt <= LEN(ref)
) AS common
FROM (
SELECT id, MIN(ref) AS initref
FROM tableA
GROUP BY
id
) i
JOIN tableA a
ON i.id = a.id
) q
GROUP BY
id
) q2
---
3536757616 / 7 / 8
3536757628 / 29 / 30
``` | I named my table #T, and using the following SELECT statement
```
select id, number, substring(#t.ref, 1, v.number), count(id)
from master.dbo.spt_values v
inner join #t on v.number <= len(#t.ref)
where v.name is null and v.number > 0
group by id, number, substring(#t.ref, 1, v.number)
order by id, count(id) desc, number desc
```
you get a result set where the first record of each id contains the maximum length and the longest initial string for each id.
That's not a complete solution, but a good starting point: iterate over the id's, issue a SELECT TOP 1 to retrieve the longest string, and concatenate the string diffs for each record with the same id. | TSQL query to concatenate and remove common prefix | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
For the example, I'm trying to replace
```
<script type='text/javascript'>some stuff</script>
```
with:
```
<div type='text/javascript'>some stuff</div>
```
I'm currently testing with:
```
alert( o.replace( /(?:<\s*\/?\s*)(script)(?:\s*([^>]*)?\s*>)/gi ,'div') );
```
But what I'm getting is:
```
divsomestuffdiv
```
How can I get this to only replace the "script" portion and preserve the other markup and attribute characters? | You have keep the opening and closing tag brackets. So try this:
```
o.replace(/(<\s*\/?\s*)script(\s*([^>]*)?\s*>)/gi ,'$1div$2')
``` | DOM methods are better suited for this than regular expressions. This way you'll manipulate your document logically instead of as plaintext:
```
var els = document.getElementsByTagName('script');
for (var i = 0, el; el = els[i]; i++) {
var new = document.createElement('div');
new.type = el.type;
el.parentNode.replaceChild(el, new);
}
``` | Trying to replace html tags using regex | [
"",
"javascript",
"replace",
"element",
""
] |
A simple scenario: a custom class that raises an event. I wish to consume this event inside a form and react to it.
How do I do that?
Note that the form and custom class are separate classes. | ```
public class EventThrower
{
public delegate void EventHandler(object sender, EventArgs args) ;
public event EventHandler ThrowEvent = delegate{};
public void SomethingHappened() => ThrowEvent(this, new EventArgs());
}
public class EventSubscriber
{
private EventThrower _Thrower;
public EventSubscriber()
{
_Thrower = new EventThrower();
// using lambda expression..could use method like other answers on here
_Thrower.ThrowEvent += (sender, args) => { DoSomething(); };
}
private void DoSomething()
{
// Handle event.....
}
}
``` | Inside your form:
```
private void SubscribeToEvent(OtherClass theInstance) => theInstance.SomeEvent += this.MyEventHandler;
private void MyEventHandler(object sender, EventArgs args)
{
// Do something on the event
}
```
You just subscribe to the event on the other class the same way you would to an event in your form. The three important things to remember:
1. You need to make sure your method (event handler) has the appropriate declaration to match up with the delegate type of the event on the other class.
2. The event on the other class needs to be visible to you (ie: public or internal).
3. Subscribe on a valid instance of the class, not the class itself. | How to subscribe to other class' events in C#? | [
"",
"c#",
"events",
".net-2.0",
"event-handling",
""
] |
I am trying to create a bookmarklet, so that when you click on it, it will load example.com/yourdata.php in a div box.
How can I make it get the data from example.com?
IFRAME? or is there a better solution? | You may have issues with creating a bookmarklet within another page that grabs data from a different domain (to load into a `<div />` using Ajax).
Your best option is probably to insert an IFrame with the content as the source of the page.
If you want to do this as a very basic lightbox, you could do something like this:
```
(function() {
var iFrame = document.createElement('IFRAME');
iFrame.src = 'http://google.com';
iFrame.style.cssText = 'display: block; position:absolute; '
+ 'top: 10%; left: 25%; width: 50%; height: 50%';
document.body.insertBefore(iFrame, document.body.firstChild);
})();
```
And here is the same code in bookmarklet format:
```
javascript: (function() { var iFrame = document.createElement('IFRAME'); iFrame.src = 'http://google.com'; iFrame.style.cssText = 'display: block; position:absolute; top: 10%; left: 25%; width: 50%; height: 50%'; document.body.insertBefore(iFrame, document.body.firstChild); })();
```
You could also style this a lot more if you wanted something pretty. This is just a basic example of what is possible. As another person said, it would be easiest to make it pretty by loading jQuery using an Ajax request, but that is a little more involved. | Do an AJAX call directly in your bookmarklet, and then set the innerHTML of your div to the returned content. Not sure if there are security restrictions on this or not.
Edit: You don't want to use JQuery, as you can't easily load a javascript library from a bookmarklet. (Although maybe you could get it via AJAX and then eval it...)
You need to do a classic [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest).
Some [more info here](http://www.jibbering.com/2002/4/httprequest.html). | How to get javascript to load another html file? | [
"",
"javascript",
"bookmarklet",
""
] |
here is my code:
```
Comic[] comix = new Comic[3];
comix[0] = new Comic("The Amazing Spider-man","A-1","Very Fine",9240.00F);
comix[0].setPrice((Float)quality.get(comix[0].condition));
for(int i=0;i<comix.length;i++){
System.out.println("Title: " + comix[i].title);
}
```
Why am I getting a NullPointerException when this code runs? | You're only setting the value of `comix[0]`, but you're fetching `comix[1]`.title and `comix[2]`.title in the loop as well, as `comix.length` is 3. The default value for each element in an array of reference types is `null`. The length is the length of the entire array, not just the "populated" elements.
You may find [`List<T>`](http://java.sun.com/javase/6/docs/api/java/util/List.html) (the most commonly used implementation being [`ArrayList<T>`](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html)) easier to work with. | Because you've only defined what is inside comix[0], not comix[1] or comix[2] | Why am I getting a NullPointerException in this for loop? | [
"",
"java",
"exception",
"for-loop",
""
] |
There doesn't seem to be a `Peek` method on the DataReader in ado.net. I would like to be able to perform some one-off processing before I loop through my reader, and it would be nice to be able to look at the data in the first row without causing it to be skipped by the subsequent iteration. What is the best way to accomplish this?
I am using a `SqlDataReader`, but preferably the implementation would be as general as possible (i.e. apply to `IDataReader` or `DbDataReader`). | I would suggest something similar to Jason's solution, but using a wrapper that implements IDataReader instead, so:
```
sealed public class PeekDataReader : IDataReader
{
private IDataReader wrappedReader;
private bool wasPeeked;
private bool lastResult;
public PeekDataReader(IDataReader wrappedReader)
{
this.wrappedReader = wrappedReader;
}
public bool Peek()
{
// If the previous operation was a peek, do not move...
if (this.wasPeeked)
return this.lastResult;
// This is the first peek for the current position, so read and tag
bool result = Read();
this.wasPeeked = true;
return result;
}
public bool Read()
{
// If last operation was a peek, do not actually read
if (this.wasPeeked)
{
this.wasPeeked = false;
return this.lastResult;
}
// Remember the result for any subsequent peeks
this.lastResult = this.wrappedReader.Read();
return this.lastResult;
}
public bool NextResult()
{
this.wasPeeked = false;
return this.wrappedReader.NextResult();
}
// Add pass-through operations for all other IDataReader methods
// that simply call on 'this.wrappedReader'
}
```
Note that this does require quite a bit of pass-through code for all the unaffected properties, but the benefit is that it is a generic abstraction that can 'peek' at any position in the result set without moving forward on the subsequent 'read' operation.
To use:
```
using (IDataReader reader = new PeekDataReader(/* actual reader */))
{
if (reader.Peek())
{
// perform some operations on the first row if it exists...
}
while (reader.Read())
{
// re-use the first row, and then read the remainder...
}
}
```
Note though that every 'Peek()' call will actually move to the next record if the previous operation was not also a 'Peek()'. Keeping this symmetry with the 'Read()' operation provides a simpler implementation and a more elegant API. | You could create a state machine that tracks peek-mode vs regular-mode. Maybe something like this (could just toss them all into a single file called Peeker.cs or something like that):
```
public sealed class Peeker
{
internal readonly PeekMode PEEKING;
internal readonly NormalMode NORMAL;
private ReadState _state;
public Peeker()
{
PEEKING = new PeekMode(this);
NORMAL = new NormalMode(this);
// Start with a normal mode
_state = NORMAL;
}
public object[] OnRead(IDataReader dr, bool peek)
{
return _state.OnRead(dr, peek);
}
internal void SetState(ReadState state)
{
_state = state;
}
}
internal abstract class ReadState
{
protected Peeker _peeker;
protected ReadState(Peeker p)
{
_peeker = p;
}
public abstract object[] OnRead(IDataReader dr, bool peek);
}
internal class PeekMode : ReadState
{
public PeekMode(Peeker p)
: base(p)
{
}
public override object[] OnRead(IDataReader dr, bool peek)
{
object[] datarow = new object[dr.FieldCount];
if (peek)
{
dr.GetValues(datarow);
}
else
{
if (dr.Read())
{
dr.GetValues(datarow);
_peeker.SetState(_peeker.NORMAL);
}
}
return datarow;
}
}
internal class NormalMode : ReadState
{
public NormalMode(Peeker p)
: base(p)
{
}
public override object[] OnRead(IDataReader dr, bool peek)
{
object[] datarow = new object[dr.FieldCount];
if (peek)
{
if (dr.Read())
{
dr.GetValues(datarow);
_peeker.SetState(_peeker.PEEKING);
}
}
else
{
if (dr.Read())
{
dr.GetValues(datarow);
}
}
return datarow;
}
}
```
Kind of overkill, but oh well.
To use it you would just do the following:
```
Peeker p = new Peeker();
.
.
.
SomeDataReaderType dr = SomeCommandType.ExecuteReader();
.
.
.
// To peek
object[] myDataRow = p.OnRead(dr, true);
// or not to peek
object[] myDataRow = p.OnRead(dr, false);
```
Then do what you need to do with your row. There might be a better way than using an object array, but you get the point.
Good luck! | How do I implement a Peek() function on a DataReader? | [
"",
"c#",
".net",
"ado.net",
""
] |
I'm building a status page which should be refreshed periodically.
So, I've had a http-equiv refresh in the `<head>` section in order to refresh the page every minute :
```
<meta http-equiv="Refresh" id="refresh" content="60"/>
```
But, for browser supporting JavaScript, I would like to send an Ajax request checking if the page should be refreshed or not. And so, I would like to disable that http-equiv refresh in JavaScript (because it's Ajax which will do the work).
I tried to remove the tag using JavaScript/PrototypeJs but that doesn't work :
```
$('refresh').remove();
```
It seems that the browser keep trace of that timer and doesn't take care of that DOM update.
Any idea ? | Not exactly sure, but maybe:
```
<noscript>
<meta http-equiv="Refresh" id="refresh" content="60"/>
</noscript>
``` | This would be better handled on the server. There are a number of tools to let you reliably check to see if the browser supports JS (BrowserHawk is one that comes to mind) or you can check the SupportsECMAScript (in ASP.NET) property of the Browser object and write out different code if the browser supports JS. | How may I disable an http-equiv refresh in JavaScript? | [
"",
"javascript",
"html",
"browser",
""
] |
How to disable browser's BACK Button (across browsers)? | This question is very similar to this [one](https://stackoverflow.com/questions/533867/whats-the-best-method-for-forcing-cache-expiration-in-asp-net)...
You need to force the cache to expire for this to work. Place the following code on your page code behind.
```
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
``` | Do not disable expected browser behaviour.
Make your pages handle the possibility of users going back a page or two; don't try to cripple their software. | Disable browser's back button | [
"",
"asp.net",
"javascript",
""
] |
I have a div that has a large number of items in it. I select these items dynamically by clicking a button, overflow is auto in my case. What I want is that when an item that is not visible is selected to scroll the div so that can be visible. How can I do this? | You can use the [scrollTop](https://developer.mozilla.org/En/DOM/Element.scrollTop) property of HTMLElement to set the amount its content is scrolled by.
And you can get the amount you need to scroll by from [offsetTop](https://developer.mozilla.org/En/DOM/Element.offsetTop) of the element to which you want to scroll.
For example with this HTML:
```
<div id="container">
<p id="item-1">foo</p>
<p id="item-2">bar</p>
<p id="item-3">baz</p>
</div>
```
You could use this JavaScript to scroll the container div to third paragraph:
```
document.getElementById("container").scrollTop = document.getElementById("item-3").offsetTop;
``` | Yet another option is to use **[jQuery](http://www.jquery.com)** along with the plugin **[ScrollTo](http://plugins.jquery.com/project/ScrollTo)**. | DIV auto scroll | [
"",
"javascript",
"html",
"dom",
""
] |
I'm looking for a replacement for JCaptcha, which doesn't seem to be maintained any more, and isn't very good to begin with. The replacement has to integrate nicely with JavaEE webapps.
As I can see it, there are three options:
* JCaptcha - No longer maintained, crude API
* SimpleCaptcha - much nicer API, nicer captchas, but seems to be Java6 only
* ReCaptcha - easy to use, uses remote web-service to generate captchas, but not much control over look and feel
Has anyone used any others, that they'd recommend? | [ReCaptcha](http://recaptcha.net/) is the only captcha you should use, because it's the only captcha that makes the world better (improve OCR results to old text), with almost unlimited database.
All other captchas are usually limited by its database, or do nothing good to this world.
**EDIT :: I found steps how to implement captcha using recaptcha.**
## You can check both Online and Offline captcha using java [here](http://technoscripts.com/creating-captcha-application-using-java/) | I am the author of [SimpleCaptcha](http://simplecaptcha.sourceforge.net/). While I would recommend -- for humanity's sake -- using ReCaptcha where you can, I provided SimpleCaptcha because some organizations have policies which prohibit libraries like ReCaptcha. SimpleCaptcha is meant to be entirely stand-alone, with no external dependencies: as long as you are in a J2EE container, you should be good.
Also, SimpleCaptcha is now available for either Java 1.5 or Java 6. | Recommendations for java captcha libraries | [
"",
"java",
"jakarta-ee",
"captcha",
"recaptcha",
"simplecaptcha",
""
] |
I have a php script that reads one file through http(the file is on other domain). I would like to read this file only once or twice a day, instead of connecting to it every time the website is refreshed.
**Is there any other way than doing it with cron?**
I dont want to use cron cause I prefer to setup this behaviour in the script itself .. so it is flexible, so I can use it anywhere without setting up cron every time.
thanks | If you can't or don't want to use use cron and it's ok to update it only when the page is accessed. You could cache the result of the HTTP request and only update it on a page load it if the cache is older than a day or whatever interval you choose. | I've done this kind of thing in the past when I didn't have access to cron:
```
$lastRunLog = '/path/to/lastrun.log';
if (file_exists($lastRunLog)) {
$lastRun = file_get_contents($lastRunLog);
if (time() - $lastRun >= 86400) {
//its been more than a day so run our external file
$cron = file_get_contents('http://example.com/external/file.php');
//update lastrun.log with current time
file_put_contents($lastRunLog, time());
}
}
``` | How can I run PHP script in certain interval (e.g. once a day)? | [
"",
"php",
"autorun",
""
] |
I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files? | ```
find DIRECTORY -name "*.py" | xargs grep PATTERN
```
By the way, since writing this, I have discovered [ack](http://beyondgrep.com/), which is a much better solution.
(And since that edit, I have discovered ag). | ```
grep -r -n "PATTERN" --include="*.py" DIRECTORY
``` | How do you grep through code that lives in many different directories? | [
"",
"python",
"grep",
"plone",
"zope",
""
] |
When I have an object foo, I can get it's class object via
```
str(foo.__class__)
```
What I would need however is only the name of the class ("Foo" for example), the above would give me something along the lines of
```
"<class 'my.package.Foo'>"
```
I know I can get it quite easily with a regexp, but I would like to know if there's a more "clean" way. | Try
```
__class__.__name__
``` | foo.\_\_class\_\_.\_\_name\_\_ should give you result you need. | How can I get the name of a python class? | [
"",
"python",
"reflection",
"inspection",
""
] |
I want to write a function to retrieve the contents of a webpage so it works like:
```
$url = "example.com";
$pageContent = RetrievePageContent($url);
```
What would be the easiest way to do this?
Thanks in advance for your help! | ```
$pageContent = file_get_contents($url);
```
From: [`file_get_contents`](http://us.php.net/file_get_contents) | The easiest way is [file\_get\_contents](https://www.php.net/file_get_contents), which does exactly what you want:
```
$url = "http://example.com";
$pageContent = file_get_contents($url);
``` | What's the easiest way to retrieve the contents of a webpage via PHP? | [
"",
"php",
""
] |
I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.
I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.
Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl? | Well, you have better options. You can for example use [pickle](http://docs.python.org/library/pickle.html) or [json](http://docs.python.org/library/json.html) format.
Pickle serializing module is very easy to use.
```
import cPickle
cPickle.dump(obj, open('save.p', 'wb'))
obj = cPickle.load(open('save.p', 'rb'))
```
The format is not human readable and unpickling is not secure against erroneous or maliciously constructed data. You should not unpickle untrusted data.
If you are using python 2.6 there is a builtin module called [json](http://docs.python.org/library/json.html). It is as easy as pickle to use:
```
import json
encoded = json.dumps(obj)
obj = json.loads(encoded)
```
Json format is human readable and is very similar to the dictionary string representation in python. And doesn't have any security issues like pickle.
If you are using an earlier version of python you can [simplejson](http://code.google.com/p/simplejson/) instead. | For me, [PyYAML](http://pyyaml.org/wiki/PyYAML) works well for these kind of things. I used to use pickle or ConfigParser before. | Is something like ConfigParser appropriate for saving state (key, value) between runs? | [
"",
"python",
"xml",
"perl",
"configparser",
""
] |
When to use the assembly to debug a c/c++ program?
Does it help to learn some assembly to debug programs? | It can be very helpful in cases where you can not (yet) reliably reproduce a
bug, such as due to heap/stack corruption. You might get one or two core
dumps, quite possibly from a customer. Even assuming your debugger is
reliable, looking at assembly can tell you exactly which instruction is
crashing (and thus which piece of memory is corrupted).
Furthermore, in my experience (primarily in kernel debugging) the debuggers
have been relatively bad at dealing with optimized code. They get things like
parameters/etc wrong, and to *really* tell what's going on I need to look at
diassembly.
If I can reproduce a problem reliably/easily it doesn't tend to be as helpful
to deal with disassembly, because I'll get more information from just stepping
through the program. On the other hand, getting to the point where you can
reproduce a problem is usually more than halfway to fixing it. | I presume you are asking when to use a dis-assembly when you want to debug your C/C++ written code.
There will be cases when you suspect that the compiler has not generated the code as you would have wanted it to. Typically, when the optimized version of the executable does not operate correctly but the un-optimized form works well. You would want to check the dis-assembly then to see what optimization has changed the behavior.
Another case would be when you want to understand the executable behavior but you do not have the source code to start with -- this is called reverse engineering. You have no options but to work with the dis-assembly of the executable.
A Wiki reference of [dis-assembly and analysis tools](http://en.wikibooks.org/wiki/X86_Disassembly/Analysis_Tools "dis-assembly and analysis tools") for understanding the tools and start learning the one most suitable to your environment. | When to use assembly language to debug a c/c++ program? | [
"",
"c++",
"c",
"debugging",
"assembly",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.