Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
> **Possible Duplicate:**
> [Reading/Writing MS Word files in Python](https://stackoverflow.com/questions/188444/reading-writing-ms-word-files-in-python)
I know there are some libraries for editing excel files but is there anything for editing msword 97/2000/2003 .doc files in python? Ideally I'd like to make some minor changes to the formatting of the text based on the contents of the text. A really trivial example would be highlighting every word starting with a capital. | Why not look at using [python-uno](http://wiki.services.openoffice.org/wiki/Python) to load the document into OpenOffice and manipulate it using the UNO interface. There is some example code on the site I just linked to which can get you started. | If platform independence is important, then I'd recommend using the OpenOffice API either through BASIC or Python. OpenOffice can also run in headless mode, without a GUI, so you can automate it for batch jobs. These links might be helpful:
* [(BASIC) Text Documents in OpenOffice](http://wiki.services.openoffice.org/wiki/Documentation/BASIC_Guide/Structure_of_Text_Documents)
* [(Python) Examples](http://wiki.services.openoffice.org/wiki/PyUNO_samples)
It's definitely more involved than importing a module and doing a string replace, but OpenOffice is probably the best free .doc reader, that you can hook into. | Is there a python library for editing msword doc files? | [
"",
"python",
"ms-word",
""
] |
If i have the following directory structure:
Project1/bin/debug
Project2/xml/file.xml
I am trying to refer to file.xml from Project1/bin/debug directory
I am essentially trying to do the following:
```
string path = Environment.CurrentDirectory + @"..\..\Project2\xml\File.xml":
```
what is the correct syntax for this? | It's probably better to manipulate path components as path components, rather than strings:
```
string path = System.IO.Path.Combine(Environment.CurrentDirectory,
@"..\..\..\Project2\xml\File.xml");
``` | Use:
```
System.IO.Path.GetFullPath(@"..\..\Project2\xml\File.xml")
``` | Concatenating Environment.CurrentDirectory with back path | [
"",
"c#",
"path",
""
] |
I have an xml template document that I need to load into an XmlDocument. eg
```
myXMLDocument.Load(myXMLFile);
```
However this is very slow as it loads in the dtd. I have tried both `"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"` and a local copy of the dtd. Both take more or less the same time. If I turn of loading the dtd by setting the resolver to null (for example), I then get errors such as `"Reference to undeclared entity 'nbsp'"` if the document contains these.
I need to use an XmlDocument as I need to manipulate the DOM before outputting the document. How can I get round these problems? | You can avoid the DTD if you return an empty memory stream:
```
private class DummyResolver : XmlResolver
{
public override System.Net.ICredentials Credentials
{
set
{
// Do nothing.
}
}
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
return new System.IO.MemoryStream();
}
}
``` | ChrisW's answer sounds interesting, however I implemented a caching resolver from this link: <http://msdn.microsoft.com/en-us/library/bb669135.aspx>
That increased the speed from around 11.5s to 160ms, which is probably good enough for now. If its still not quick enough I will impliment ChrisW's solution. :) | XmlDocument and slow schema processing | [
"",
"c#",
".net",
"xml",
"dtd",
"xmldocument",
""
] |
I have using the following code for developing tabs.
```
$(document).ready(function() {
$('#container-1').tabs();
}
....
<div id="container-1">
<ul>
<li><a href="#fragment-1"><span>Home</span></a></li>
<li><a href="#fragment-2"><span>Contact</span></a></li>
</ul>
</div>
...
```
It works fine! I need the tab click event. If it is the *Home* tab click, I have to do `alert();`. How do I achieve this? | Personally, I'd handle it all in the tab configuration itself rather than adding click events to the elements which ultimately will be the clickable part of the tab. If you do it via the tab config, then all of your tab logic is centralized thus making things cleaner and you don't need to be familiar with the implementation details of the tabs:
```
$(document).ready(function() {
$('#container-1').tabs({
selected : function(e, ui) {
if (ui.index == 0) {
alert('Home clicked!');
}
}
});
});
....
<div id="container-1">
<ul>
<li><a href="#fragment-1"><span>Home</span></a></li>
<li><a href="#fragment-2"><span>Contact</span></a></li>
</ul>
</div>
``` | Set the id of the *Home* tab span element:
```
<li><a href="#fragment-1"><span id="home">Home</span></a></li>
```
And add the click handler to it somewhere:
```
$("#home").click(function()
{
alert("Home tab is selected!");
});
``` | How to find out the TabSelection | [
"",
"javascript",
"jquery",
""
] |
For a long time now C++ has been the dominate game development language. Many AAA quality 3D engines are available to fit any budget.
My question is, with the rise of XNA, has C# and the .NET framework been positioned well enough to take over as the new standard game development platform? Obviously the inherent cross-platform nature of the XNA framework (Windows, Xbox, Zune) has its benefits, but are those benefits good enough to entice large game dev studios to switch gears?
Personally, i am torn between using C#/XNA for a new project, and using Java via jMonkeyEngine. I have a great desire to have my game be portable to multiple platforms, and the only languages i know well enough to accomplish this are C# and Java. i would love to see an implementation of the XNA codebase that is powered by OpenGL and would run on Mono, but i think that is merely wishful thinking at this point.
I am curious to hear what others have experienced while building 3D games in something other than C++. | The large gaming studios will probably not adopt XNA any time soon. Some indies are using it, but definitely has the potential to eventually be very successful and leave C++ behind.
XNA provides many classes that you can use in game development, but many others often choose to use a fully fledged games engine. Although XNA is rather good for beginner's to cut their teeth on if you are new to programming games.
C# is a good language to use for games development. Games development produces applications that require sound, advanced graphics, AI, Physics, etc. All that requires a powerful and fairly quick language environment. While most of the top tier PC and console games are written in C++, C# has a road map that will likely leave C++ behind. The coming changes in C++0x will no doubt reinvigorate C++ for a little while but C# looks poised to overtake it.
If you really want to be a games developer I would urge you to at least learn C++ and write your own game engine. Using a pre-made game engine is easy and you can code something that is 'okay' but you will run into many limitations that you won't be able to code around. You will effectively be confined to the capabilities of the game engine (unless you have access to the source, which you could then modify to your liking).
Learn C++ and preferably OpenGL :)
Once you know OpenGL you can learn DirectX pretty easily.
C# is a piece of cake once you know C++. | I think C++ will go out of fashion in the next 10 years just the same way as assembly did. I'm a professional game programmer for more the 15 years. In early 90's lot of people said that C is not efficient enough for games. In the late 90's same people said that C is OK but C++ is just way too slow for performance critical applications such as games. Now C++ is the standard high performance language and people argue that other languages would be too slow. In the meantime today's games use script languages like Lua, Python or Unrealscript for game logic which are ten times slower than C# or Java.
C++ is much faster when you do math in your game. Doing linear algebra is painfully slow in C# or Java. However, this is only a part (10 - 25%) of the game. When it comes to the game logic bottleneck is memory access so using an other language does not reduce the performance significantly. The tool side of the game, which use to be the 50-80% of the code, really does not require any C++. It happily runs in C# which is fast enough for almost any tool.
One also should not forget that C++ is derived from C, which is made in the early 70's. So C++ is obsolete in many ways. The most annoying thing is probably the pre-processor which kills transparency and causes insanely long compile times. An average state of art C++ game engine compiles in 30-60 minutes. In such time you could compile every C# and Java project ever made by humans. Lack of self reflection and dynamic code creation is also a drawback. It often costs a lot of development time to overcome on these shortcomings.
Nevertheless C++ development costs a lot it would cost even more for a game studio to risk a failure by switching to a new technology which is not yet proven in game development. It is also an important factor that majority of experienced game programmers use only C/C++ and they do not have experience with other languages which would definitely increase the risk of switching. Because of these, you probably will not see game studios in the next couple of years switching to C#. However, it is likely that a Microsoft owned studio will make a big hit with a C# game in the next 5 years which will convince other studios that it is feasible to make AAA titles in C# and then you will see more and more studios switching to C#.
For now, my advice is:
If you want to make an AAA multi-platform title you have no other choice than C++ for the runtime part of the game. Consider using C# for the tool side. It's a little bit tricky to efficiently connect managed and unmanaged code but on long run it worth the effort you spend on it.
If you do a hobby project or a B title where performance is less important than development cost/time then forget C++ and just use C# for everything and spend some extra time to optimize the math. | Viability of C#/.NET as the new standard game dev platform? | [
"",
"c#",
"mono",
"xna",
""
] |
I've got a name of a method: "Garden.Plugins.Code.Beta.Business.CalculateRest"
How to run it? I think about this fancy reflection based solution like RunMethod(string MethodName) | * Split it into type name and method name by splitting on the last dot
* Get the type using [Type.GetType](http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx) or [Assembly.GetType](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettype.aspx). (Type.GetType will only look in the currently executing assembly and mscorlib, unless you specify the assembly name in the argument.)
* Get the method from the type using [Type.GetMethod](http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx). Assuming it's a public static method, specify `BindingFlags.Public | BindingFlags.Static`.
* Execute the method by calling [MethodInfo.Invoke](http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.invoke.aspx)(null, null). (The first null specifies "no target" - i.e. it's a static method; the second specifies no arguments.)
If you want to call an instance method or one which takes parameters, you'll need to work out how to get that information too. | It's not quite as simple as treating everything to the left of the last dot as the literal typename. If you've got a type of the form:
X.Y.Z.Type
then it's not necessarily the case that X, Y and Z are namespaces. They could also be types themselves and the subsequent parts could be inner classes:
```
class X
{
class Y
{
// etc
}
}
```
If this is the case then Type.GetType("X.YU") wont resolve to the Y class.Instead, the clr seperates inner classes with a + symbol, so you'd actually need to call Type.GetType("X+Y");
If the method that you're calling is a **params** method then you'll need to so some additional work. You're required to roll the variable parameters up into an array and pass this. You can check for variable parameters by grabbing the **ParameterInfo** data for a method and seeing if the last parameter has the **ParamArray** attribute attached. | How to run any method knowing only her fully qualified name | [
"",
"c#",
"reflection",
"methods",
""
] |
In my mock class, I'm mocking method foo(). For some test cases, I want the mock implementation of foo() to return a special value. For other test cases, I want to use the real implementation of foo(). I have a boolean defined in my mock class so that I can determine in the mock method whether I want to return the special value, or use the "real" method. The problem is, I can't seem to figure out how to call the real method from the mocked method.
I found that you can define a special member within the mock object named "it" (with type of the object being mocked). This allows you to reference the real class from the mock implementation. So, my plan was, if I needed to invoke the "real" implementation of foo(), the mock method would call it.foo(). However, this doesn't work, because calling it.foo() just calls the mock version again, not the real version, so I end up with infinite recursion.
Is there some way to make this work?
EDIT: it might be clearer with a code example, here's what my current mocked method implementation looks like:
```
private RealClass it;
...
public SomeClass foo() {
if(fakeIt) {
return new SomeClass("fakevalue");
} else {
// doesn't work, just keeps calling the mock foo
// in infinite recursion
return it.foo();
}
}
```
EDIT 2: Also, for most of my test cases I do *NOT* want the mock implementation. So my initial attempt at this was to only call Mockit.redefineMethods() within those test cases where I needed the mock object. But this didn't work - it seems you can only do this within setup/teardown ... my mock implementation never got called when I tried that.
NOTES ON SOLUTION:
At first I didn't think the answer given worked, but after playing with it some more, it seems the problem is that I was mixing JMockit "core" methods with the "annotation" driven methods. Apparently when using the annotation you need to use Mockit.setupMocks, not Mockit.redefineMethods(). This is what finally worked:
```
@Before
public void setUp() throws Exception
{
Mockit.setUpMocks(MyMockClass.class);
}
```
Then, for the mock class:
```
@MockClass(realClass = RealClass.class)
public static class MyMockClass {
private static boolean fakeIt = false;
private RealClass it;
@Mock(reentrant = true)
public SomeClass foo() {
if(fakeIt) {
return new SomeClass("fakevalue");
} else {
return it.foo();
}
}
}
``` | I think you can do this with the `@Mock` annotation. From the docs, `@Mock(reentrant=true)` on your mock class should do it.
See <http://jmockit.googlecode.com/svn/trunk/www/javadoc/mockit/Mock.html>
For an example look here <http://jmockit.googlecode.com/svn/trunk/www/tutorial/StateBasedTesting.html#reentrant>
I haven't tested this though.. | In more recent versions of JMockit, [`Invocation.proceed()`](http://jmockit.org/api1x/mockit/Invocation.html#proceed-java.lang.Object...-) can be called from within a [`MockUp`](http://jmockit.org/api1x/mockit/MockUp.html) implementation. See [Accessing the invocation context](https://jmockit.github.io/tutorial/Faking.html#invocation).
```
public class MyMockClass extends MockUp<RealClass> {
private static boolean fakeIt = false;
@Mock
public SomeClass foo(Invocation inv) {
if (fakeIt) {
return new SomeClass("fakevalue");
} else {
return inv.proceed();
}
}
}
``` | Is there a way in JMockit to call the original method from a mocked method? | [
"",
"java",
"mocking",
"jmockit",
""
] |
We're developing a Python web service and a client web site in parallel. When we make an HTTP request from the client to the service, one call consistently raises a socket.error in socket.py, in read:
```
(104, 'Connection reset by peer')
```
When I listen in with wireshark, the "good" and "bad" responses look very similar:
* Because of the size of the OAuth header, the request is split into two packets. The service responds to both with ACK
* The service sends the response, one packet per header (HTTP/1.0 200 OK, then the Date header, etc.). The client responds to each with ACK.
* (Good request) the server sends a FIN, ACK. The client responds with a FIN, ACK. The server responds ACK.
* (Bad request) the server sends a RST, ACK, the client doesn't send a TCP response, the socket.error is raised on the client side.
Both the web service and the client are running on a Gentoo Linux x86-64 box running glibc-2.6.1. We're using Python 2.5.2 inside the same virtual\_env.
The client is a Django 1.0.2 app that is calling httplib2 0.4.0 to make requests. We're signing requests with the OAuth signing algorithm, with the OAuth token always set to an empty string.
The service is running Werkzeug 0.3.1, which is using Python's wsgiref.simple\_server. I ran the WSGI app through wsgiref.validator with no issues.
It seems like this should be easy to debug, but when I trace through a good request on the service side, it looks just like the bad request, in the socket.\_socketobject.close() function, turning delegate methods into dummy methods. When the send or sendto (can't remember which) method is switched off, the FIN or RST is sent, and the client starts processing.
"Connection reset by peer" seems to place blame on the service, but I don't trust httplib2 either. Can the client be at fault?
\*\* Further debugging - Looks like server on Linux \*\*
I have a MacBook, so I tried running the service on one and the client website on the other. The Linux client calls the OS X server without the bug (FIN ACK). The OS X client calls the Linux service with the bug (RST ACK, and a (54, 'Connection reset by peer')). So, it looks like it's the service running on Linux. Is it x86\_64? A bad glibc? wsgiref? Still looking...
\*\* Further testing - wsgiref looks flaky \*\*
We've gone to production with Apache and mod\_wsgi, and the connection resets have gone away. See my answer below, but my advice is to log the connection reset and retry. This will let your server run OK in development mode, and solidly in production. | I've had this problem. See [The Python "Connection Reset By Peer" Problem](http://www.itmaybeahack.com/homepage/iblog/architecture/C551260341/E20081031204203/index.html).
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a `time.sleep(0.01)` placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just *before* you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads. | Don't use wsgiref for production. Use Apache and mod\_wsgi, or something else.
We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.
We've never seen a connection reset when running through Apache and mod\_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.
When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it. | 104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN? | [
"",
"python",
"sockets",
"wsgi",
"httplib2",
"werkzeug",
""
] |
I saw someone ask a question about detecting if a URL redirects from groovy and perl but couldn't find anything on PHP.
Anyone know of somewhere I could find that code that does this? | Actually, I found this works best:
```
function GetURL($URL)
{
$ch = curl_init($URL);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
return $code;
}
``` | ```
$ch = curl_init('http://www.yahoo.com/');
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (($code == 301) || ($code == 302)) {
//This was a redirect
}
``` | How can I determine if a URL redirects in PHP? | [
"",
"php",
"url",
"url-rewriting",
""
] |
I need a way to compute the nth root of a long integer in Python.
I tried `pow(m, 1.0/n)`, but it doesn't work:
> OverflowError: long int too large to convert to float
Any ideas?
By long integer I mean REALLY long integers like:
> 11968003966030964356885611480383408833172346450467339251
> 196093144141045683463085291115677488411620264826942334897996389
> 485046262847265769280883237649461122479734279424416861834396522
> 819159219215308460065265520143082728303864638821979329804885526
> 557893649662037092457130509980883789368448042961108430809620626
> 059287437887495827369474189818588006905358793385574832590121472
> 680866521970802708379837148646191567765584039175249171110593159
> 305029014037881475265618958103073425958633163441030267478942720
> 703134493880117805010891574606323700178176718412858948243785754
> 898788359757528163558061136758276299059029113119763557411729353
> 915848889261125855717014320045292143759177464380434854573300054
> 940683350937992500211758727939459249163046465047204851616590276
> 724564411037216844005877918224201569391107769029955591465502737
> 961776799311859881060956465198859727495735498887960494256488224
> 613682478900505821893815926193600121890632 | You can make it run slightly faster by avoiding the while loops in favor of setting low to 10 \*\* (len(str(x)) / n) and high to low \* 10. Probably better is to replace the len(str(x)) with the bitwise length and using a bit shift. Based on my tests, I estimate a 5% speedup from the first and a 25% speedup from the second. If the ints are big enough, this might matter (and the speedups may vary). Don't trust my code without testing it carefully. I did some basic testing but may have missed an edge case. Also, these speedups vary with the number chosen.
If the actual data you're using is much bigger than what you posted here, this change may be worthwhile.
```
from timeit import Timer
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n < x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
def find_invpowAlt(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
low = 10 ** (len(str(x)) / n)
high = low * 10
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
x = 237734537465873465
n = 5
tests = 10000
print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)
print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)
```
Norm 0.626754999161
Alt 0.566340923309 | If it's a REALLY big number. You could use a binary search.
```
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n <= x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
```
For example:
```
>>> x = 237734537465873465
>>> n = 5
>>> y = find_invpow(x,n)
>>> y
2986
>>> y**n <= x <= (y+1)**n
True
>>>
>>> x = 119680039660309643568856114803834088331723464504673392511960931441>
>>> n = 45
>>> y = find_invpow(x,n)
>>> y
227661383982863143360L
>>> y**n <= x < (y+1)**n
True
>>> find_invpow(y**n,n) == y
True
>>>
``` | How to compute the nth root of a very big integer | [
"",
"python",
"math",
"nth-root",
""
] |
I noticed some people declare a private variable and then a public variable with the get and set statements:
```
private string myvariable = string.Empty;
public string MyVariable
{
get { return myvariable; }
set { myvariable = value ?? string.Empty; }
}
```
and then some people just do the following:
```
public string MyVariable
{
get { return value; }
set { MyVariable = value; }
}
```
Being a bear of little intelligence (yes, I have kids... why do you ask?) I can't figure out why you would choose one over the other. Isn't it just as effective in using a public variable that you can set any time using the set method of the variable?
Can anyone shed some light on this for me?
UPDATE: I corrected the second example after several people pointed out it wouldn't compile. Sorry about that, but the question still remains... | [This](https://blog.codinghorror.com/properties-vs-public-variables/) is a very interesting read on this topic. However, I am pretty sure I have read somewhere on MSDN that objects with public variables are lighter than having properties (can't find the link). | Your second example won't compile, as the getter's value variable doesn't exist. Also, the setter would result in the eponymous StackOverflow exception!
In C# 3.0, you can use the following syntax to have the compiler create the private backing variable:
```
public string MyVariable { get; set; }
```
This wouldn't give you the extra null checking your first example has, though. You'd probably have to stick with your first example's method if you need custom logic in the setter. | Proper Variable Declaration in C# | [
"",
"c#",
"asp.net",
""
] |
I can find lots of information on how Long Polling works (For example, [this](http://jfarcand.wordpress.com/2007/05/15/new-adventures-in-comet-polling-long-polling-or-http-streaming-with-ajax-which-one-to-choose/), and [this](http://en.wikipedia.org/wiki/Comet_(programming)#Ajax_with_long_polling)), but no *simple* examples of how to implement this in code.
All I can find is [cometd](http://code.google.com/p/cometd/), which relies on the Dojo JS framework, and a fairly complex server system..
Basically, how would I use Apache to serve the requests, and how would I write a simple script (say, in PHP) which would "long-poll" the server for new messages?
The example doesn't have to be scaleable, secure or complete, it just needs to work! | It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).
Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)
`msgsrv.php`
```
<?php
if(rand(1,3) == 1){
/* Fake an error */
header("HTTP/1.0 404 Not Found");
die();
}
/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>
```
Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's [twisted](http://twistedmatrix.com/trac/), which does not rely on one thread per request. [cometD](http://cometdproject.dojotoolkit.org/) is an popular one (which is available in several languages), and [Tornado](http://www.tornadoweb.org/) is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)
Then, in Javascript, you request the above file (`msg_srv.php`), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)
What follows is an example of such a page.. When the page is loaded, it sends the initial request for the `msgsrv.php` file.. If it succeeds, we append the message to the `#messages` div, then after 1 second we call the waitForMsg function again, which triggers the wait.
The 1 second `setTimeout()` is a really basic rate-limiter, it works fine without this, but if `msgsrv.php` *always* returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.
If the page errors, it appends the error to the `#messages` div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)
The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required
Anyway, the `long_poller.htm` code, using the jQuery framework:
```
<html>
<head>
<title>BargePoller</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
body{ background:#000;color:#fff;font-size:.9em; }
.msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
.old{ background-color:#246499;}
.new{ background-color:#3B9957;}
.error{ background-color:#992E36;}
</style>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
/* Simple helper to add a div.
type is the name of a CSS class (old/new/error).
msg is the contents of the div */
$("#messages").append(
"<div class='msg "+ type +"'>"+ msg +"</div>"
);
}
function waitForMsg(){
/* This requests the url "msgsrv.php"
When it complete (or errors)*/
$.ajax({
type: "GET",
url: "msgsrv.php",
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
setTimeout(
waitForMsg, /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg, /* Try again after.. */
15000); /* milliseconds (15seconds) */
}
});
};
$(document).ready(function(){
waitForMsg(); /* Start the inital request */
});
</script>
</head>
<body>
<div id="messages">
<div class="msg old">
BargePoll message requester!
</div>
</div>
</body>
</html>
``` | I've got a really simple chat example as part of [slosh](http://github.com/dustin/slosh).
**Edit**: (since everyone's pasting their code in here)
This is the complete JSON-based multi-user chat using long-polling and [slosh](http://github.com/dustin/slosh). This is a **demo** of how to do the calls, so please ignore the XSS problems. Nobody should deploy this without sanitizing it first.
Notice that the client *always* has a connection to the server, and as soon as anyone sends a message, everyone should see it roughly instantly.
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Copyright (c) 2008 Dustin Sallings <dustin+html@spy.net> -->
<html lang="en">
<head>
<title>slosh chat</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<link title="Default" rel="stylesheet" media="screen" href="style.css" />
</head>
<body>
<h1>Welcome to Slosh Chat</h1>
<div id="messages">
<div>
<span class="from">First!:</span>
<span class="msg">Welcome to chat. Please don't hurt each other.</span>
</div>
</div>
<form method="post" action="#">
<div>Nick: <input id='from' type="text" name="from"/></div>
<div>Message:</div>
<div><textarea id='msg' name="msg"></textarea></div>
<div><input type="submit" value="Say it" id="submit"/></div>
</form>
<script type="text/javascript">
function gotData(json, st) {
var msgs=$('#messages');
$.each(json.res, function(idx, p) {
var from = p.from[0]
var msg = p.msg[0]
msgs.append("<div><span class='from'>" + from + ":</span>" +
" <span class='msg'>" + msg + "</span></div>");
});
// The jQuery wrapped msgs above does not work here.
var msgs=document.getElementById("messages");
msgs.scrollTop = msgs.scrollHeight;
}
function getNewComments() {
$.getJSON('/topics/chat.json', gotData);
}
$(document).ready(function() {
$(document).ajaxStop(getNewComments);
$("form").submit(function() {
$.post('/topics/chat', $('form').serialize());
return false;
});
getNewComments();
});
</script>
</body>
</html>
``` | How do I implement basic "Long Polling"? | [
"",
"php",
"http",
"comet",
""
] |
I tried the following code to get an alert upon closing a browser window:
```
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
```
It works, but if the page contains one hyperlink, clicking on that hyperlink raises the same alert. I need to show the alert only when I close the browser window and not upon clicking hyperlinks. | Keep your code as is and use jQuery to handle links:
```
$(function () {
$("a").click(function {
window.onbeforeunload = null;
});
});
``` | Another implementation is the following you can find it in this webpage:
<http://ujap.de/index.php/view/JavascriptCloseHook>
```
<html>
<head>
<script type="text/javascript">
var hook = true;
window.onbeforeunload = function() {
if (hook) {
return "Did you save your stuff?"
}
}
function unhook() {
hook=false;
}
</script>
</head>
<body>
<!-- this will ask for confirmation: -->
<a href="http://google.com">external link</a>
<!-- this will go without asking: -->
<a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
</body>
</html>
```
What it does is you use a variable as a flag. | How to prevent closing browser window? | [
"",
"javascript",
"browser",
"window",
"onbeforeunload",
""
] |
How to get Hibernate session inside a Hibernate Interceptor?
I'm trying to use Hibernate to enforce data access by organization id transparently.
I have set a global Filter to filter all queries by organization id.
Now, I need to use an Entity interceptor to set Organizational Id on all Entities before Save/Update.
The organization id comes from HttpSession
I've set Organizational Id as a Filter property in Hibernate session which i want to retrieve inside my interceptor and use for all Inserts and Updates as well.
The problem is i dont seem to have access to Session inside the Interceptor. Any workarounds for this? | You can, but I would use a simple POJO just to keep things cleanly separated. Keep in mind that the value stored in the singleton will only be accessible by the same thread that handled the servlet request, so if you're doing any asynch, you will need to account for that. Here's a super basic impl:
```
public class OrgId {
public static ThreadLocal<Integer> orgId = new ThreadLocal<Integer>();
}
```
Since the Organizational Id is resident in the session, you could set the value of the ThreadLocal in an early servlet filter like this (not much error checking):
```
public class OrgIdFilter implements Filter {
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws java.io.IOException, javax.servlet.ServletException {
int orgId = 0;
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpSession session = req.getSession();
orgId = Integer.parseInt(session.getAttribute("OrganizationalIdAttr"));
try {
OrgId.orgId.set(orgId);
filterChain.doFilter(servletRequest, servletresponse);
} finally {
OrgId.orgId.set(null); // Important to clear after request !!
}
}
}
```
This assumes that the orgId is in the session when the filter is called, but if not, you get the idea....
Then in your interceptor (or pretty much anywhere) you can get the thread's current orgId with:
```
OrgId.orgId.get(); // Might be null.....
```
A potential snafu here is that all these components (filter, OrgId and interceptor) need to be loaded by the same class loader to ensure that the OrgId class is effectively a singleton, otherwise, with multiple instances of the ThreadLocal hanging around it won't work consistently, or at all. Needless to say, all this needs to be happening in the same VM.
I am not sure if this is the cleanest way to solve this problem, but it does get you your orgId where you need it. | When you create your Interceptor, if you can provide it with a reference to the SessionFactory, you can use [SessionFactory#getCurrentSession](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html#getCurrentSession()) | How to get Hibernate session inside a Hibernate Interceptor? | [
"",
"java",
"hibernate",
"orm",
""
] |
I have a class that extends Zend\_Form like this (simplified):
```
class Core_Form extends Zend_Form
{
protected static $_elementDecorators = array(
'ViewHelper',
'Errors',
array('Label'),
array('HtmlTag', array('tag' => 'li')),
);
public function loadDefaultDecorators()
{
$this->setElementDecorators(self::$_elementDecorators);
}
}
```
I then use that class to create all of my forms:
```
class ExampleForm extends Core_Form
{
public function init()
{
// Example Field
$example = new Zend_Form_Element_Hidden('example');
$this->addElement($example);
}
}
```
In one of my views, I have a need to display *only* this one field (without anything else generated by Zend\_Form). So in my view I have this:
```
<?php echo $this->exampleForm->example; ?>
```
This works fine, except for it generates the field like this:
```
<li><input type="hidden" name="example" value=""></li>
```
This is obviously because I set the element decorators to include HtmlTag: tag => 'li'.
**My question is: How can I disable all decorators for this element. I don't need decorators for hidden input elements.** | the best place to set it is public function loadDefaultDecorators()
for example like this:
```
class ExampleForm extends Core_Form
{
public function init()
{
//Example Field
$example = new Zend_Form_Element_Hidden('example');
$this->addElement($example);
}
public function loadDefaultDecorators()
{
$this->example->setDecorators(array('ViewHelper'));
}
}
``` | Reset the decorators for the form element to only use 'ViewHelper'. For example:
```
<?php echo $this->exampleForm->example->setDecorators(array('ViewHelper')) ; ?>
```
Obviously, the view is not the ideal place to do this, but you get the idea. Note that calling setDecorator\*\*\*s\*\*\*() resets all the decorators instead of adding a new one. | Zend Framework - Zend_Form Decorator Issue | [
"",
"php",
"zend-framework",
"zend-form",
""
] |
I would like to add attributes to Linq 2 Sql classes properties. Such as this Column is browsable in the UI or ReadOnly in the UI and so far.
I've thought about using templates, anybody knows how to use it? or something different?
Generally speaking, would do you do to address this issue with classes being code-generated? | As requested, here's an approach using a `CustomTypeDescriptor` to edit the attributes at run-time; the example here is win-forms, but it should be pretty simple to swap it into WPF to see if it works...
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
// example POCO
class Foo {
static Foo()
{ // initializes the custom provider (the attribute-based approach doesn't allow
// access to the original provider)
TypeDescriptionProvider basic = TypeDescriptor.GetProvider(typeof(Foo));
FooTypeDescriptionProvider custom = new FooTypeDescriptionProvider(basic);
TypeDescriptor.AddProvider(custom, typeof(Foo));
}
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
// example form
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run( new Form {
Controls = {
new DataGridView {
Dock = DockStyle.Fill,
DataSource = new BindingList<Foo> {
new Foo { Name = "Fred", DateOfBirth = DateTime.Today.AddYears(-20) }
}
}
}
});
}
}
class FooTypeDescriptionProvider : TypeDescriptionProvider
{
ICustomTypeDescriptor descriptor;
public FooTypeDescriptionProvider(TypeDescriptionProvider parent) : base(parent) { }
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{ // swap regular descriptor for bespoke (Foo) descriptor
if (descriptor == null)
{
ICustomTypeDescriptor desc = base.GetTypeDescriptor(typeof(Foo), null);
descriptor = new FooTypeDescriptor(desc);
}
return descriptor;
}
}
class FooTypeDescriptor : CustomTypeDescriptor
{
internal FooTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) { }
public override PropertyDescriptorCollection GetProperties()
{ // wrap the properties
return Wrap(base.GetProperties());
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ // wrap the properties
return Wrap(base.GetProperties(attributes));
}
static PropertyDescriptorCollection Wrap(PropertyDescriptorCollection properties)
{
// here's where we have an opportunity to swap/add/remove properties
// at runtime; we'll swap them for pass-thru properties with
// edited atttibutes
List<PropertyDescriptor> list = new List<PropertyDescriptor>(properties.Count);
foreach (PropertyDescriptor prop in properties)
{
// add custom attributes here...
string displayName = prop.DisplayName;
if (string.IsNullOrEmpty(displayName)) displayName = prop.Name;
list.Add(new ChainedPropertyDescriptor(prop, new DisplayNameAttribute("Foo:" + displayName)));
}
return new PropertyDescriptorCollection(list.ToArray(), true);
}
}
class ChainedPropertyDescriptor : PropertyDescriptor
{
// this passes all requests through to the underlying (parent)
// descriptor, but has custom attributes etc;
// we could also override properties here...
private readonly PropertyDescriptor parent;
public ChainedPropertyDescriptor(PropertyDescriptor parent, params Attribute[] attributes)
: base(parent, attributes)
{
this.parent = parent;
}
public override bool ShouldSerializeValue(object component) { return parent.ShouldSerializeValue(component); }
public override void SetValue(object component, object value) { parent.SetValue(component, value); }
public override object GetValue(object component) { return parent.GetValue(component); }
public override void ResetValue(object component) { parent.ResetValue(component); }
public override Type PropertyType {get { return parent.PropertyType; } }
public override bool IsReadOnly { get { return parent.IsReadOnly; } }
public override bool CanResetValue(object component) {return parent.CanResetValue(component);}
public override Type ComponentType { get { return parent.ComponentType; } }
public override void AddValueChanged(object component, EventHandler handler) {parent.AddValueChanged(component, handler); }
public override void RemoveValueChanged(object component, EventHandler handler) { parent.RemoveValueChanged(component, handler); }
public override bool SupportsChangeEvents { get { return parent.SupportsChangeEvents; } }
}
``` | You can take advantage of the new Metadata functionality in the System.ComponentModel.DataAnnotations which will allow us to separate the MetaData from the existing domain model.
For example:
```
[MetadataType (typeof (BookingMetadata))]
public partial class Booking
{
// This is your custom partial class
}
public class BookingMetadata
{
[Required] [StringLength(15)]
public object ClientName { get; set; }
[Range(1, 20)]
public object NumberOfGuests { get; set; }
[Required] [DataType(DataType.Date)]
public object ArrivalDate { get; set; }
}
``` | How can I add my attributes to Code-Generated Linq2Sql classes properties? | [
"",
"c#",
"linq-to-sql",
"attributes",
"code-generation",
""
] |
When creating a new C++ header/source file, what information do you add to the top? For example, do you add the date, your name, a description of the file, etc.? Do you use a structured format for this information?
e.g.
```
// Foo.cpp - Implementation of the Foo class
// Date: 2008-25-11
// Created by: John Smith
```
One team I know embeds CVS commit messages to the foot of each file, but I'm not sure I want to go this far... | Information about who created a file and when and who edited it and when is all in source control. If your team has good practices around check-in comments, then you'll know the reasons for each change too. No need for comments for that stuff.
I think it's 100% legit - wise, even - to put a comment block, as long as is necessary, explaining the purpose of the class/module. When the next person goes to change it, they'll have a better idea of the overall vision and whether this file is the appropriate place for their change.
Some shops put copyright notices and other legal folderol in source file comments. This strikes me as just silly - if your (non-OSS) source code has made it onto someone else's servers without your knowledge or permission, a copyright notice is probably not going to deter them from doing anything with it. IANAL, YMMV. | I used to like putting version control keywords in the header of file. But recovered from that affliction. :) For two reasons:
1. Nobody put comments in that are of any use. You always wind up looking at the diffs reported by the version control system.
2. It creates a nightmare in trying to diff large filesets because the keywords create differences that are the only difference in the file. | Do you add information to the top of each .hpp/.cpp file? | [
"",
"c++",
"coding-style",
""
] |
Normally to attach a debuger to a running jvm you would need start the jvm with arguments such as the following:
```
> java -Xdebug -Xrunjdwp:transport=dt_socket,address=1000,server=y,suspend=n
```
Now if I want to debug a process that wasn't started in debug mode, what can I do?
This situation arrises when a production system (i.e. started without debug args) exhibits a 'random' (I use the term loosely) bug. So I can't restart the jvm with the appropriate arguments, because nobody knows how to reproduce the bug again. Is it impossible to attach to the JVM in this situation?
Just to clarify it is not possible to use tools like jdb to attach to already running JVMs unless they were started in debug mode
from the JVM man page
> **Another way to use jdb is by attaching it to a Java VM that is
> already running. A VM that is to be
> debugged with jdb must be started with
> the following options:** | You may be able to use [jsadebugd](http://docs.oracle.com/javase/7/docs/technotes/tools/share/jsadebugd.html) ([JDK](http://docs.oracle.com/javase/7/docs/technotes/tools/)) to attach a debug server to the process (available on Windows with the [Debugging Tools for Windows](http://msdn.microsoft.com/en-US/windows/hardware/gg463009)). It is marked as experimental, so you may want to try it out on a test machine first.
Usage:
```
jsadebugd <pid>
jdb -connect sun.jvm.hotspot.jdi.SADebugServerAttachingConnector:debugServerName=localhost
```
The connector name withe arg can be found using `jdb -listconnectors`. | > Just to clarify it is not possible to use tools like jdb to attach to already running JVMs > > unless they were started in debug mode
in soviet russia source reads you
```
jdb -connect sun.jvm.hotspot.jdi.SAPIDAttachingConnector:pid=9426
``` | Debug a java application without starting the JVM with debug arguments | [
"",
"java",
"debugging",
"jvm",
"jvm-arguments",
""
] |
Does any one know of a way to control how Visual Studio handles curly braces in Html view?
Type...
```
<% if (true) { %>
```
Then
```
<% { %>
```
And visual studio will auto format it as such.
```
<% if (true)
{ %>
<% } %>
```
Not a major issue but nest a few of these using foreach and it gets messy. | Well its not really a sollution, but what i do is that i hit Ctrl+x to undo, and it will undo the formatting - there is not another way that i know off, other that changed it in all C# documents. | Take a look at tools -> options -> texteditor -> JScript -> Formatting! | Visual Studio HTML editor curly bracket annoyance | [
"",
"c#",
"asp.net",
"html",
"visual-studio-2008",
""
] |
Which one is better when performance is taken into consideration an
**if else if** or **switch case**
Duplicate: [Is there any significant difference between using if/else and switch-case in C#?](https://stackoverflow.com/questions/395618/ifelse-vs-switch) | For both readability and sense use a switch statement instead of loads of IF statements.
The switch statement is slightly faster though:
<http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx> (first hit on Google)
The compiler can optimise the switch statement so use that if you have more than, I would say, 3 or 4 different cases | What are you switching on? If you're switching on a string, the C# compiler *either* converts it into a dictionary *or* into a series of if/else checks. Which will be faster depends on the strings in question (including the candidate string).
If you're switching on an integral value, I believe the C# compiler always uses an IL switch statement - but that may or may not be faster than an if/else sequence depending on the values involved. (If they're in a large contiguous block, the CLR can just jump to the right place in the table - if they're very disparate, I suspect it doesn't help.)
Is this just an idle query, or are you really micro-optimising at this level? Any performance difference is going to be insignificant in the vast majority of cases - write for readability. | If else if or Switch case | [
"",
"c#",
".net",
"performance",
""
] |
say I have this
```
$result = mysql_query('SELECT views FROM post ORDER BY views ASC');
```
and I want to use the value at index 30 I assumed I would use
```
mysql_data_seek($result, 30);
$useableResult = mysql_fetch_row($result);
echo $useableResult . '<br/>';
```
But that is returning my whole table
What have I got wrong?
Edit: Woops, I actually have
```
mysql_data_seek($result, 30);
while($row = mysql_fetch_row($result)){
echo $row['views'] . '<br/>';
}
``` | Simply use an SQL WHERE clause.
```
$result = mysql_query('SELECT views FROM post WHERE ID=30')
```
If you don't want to go by ID but instead want the 30th item that would be returned you can use a LIMIT min, max:
```
$result = mysql_query('SELECT views FROM post LIMIT 30, 1')
```
In both cases your ORDER BY commands become unnecessary.
Here is a [good usage example of the LIMIT command](http://www.php-mysql-tutorial.com/wikis/php-tutorial/paging-using-php.aspx) for doing paging on large record sets. | Your first example would actually do what you want, but be very expensive. The second is selecting the entire table, moving to the 30th row of the result, and then looping through all the results from then onwards.
You should instead do the following, which will only return one row and be a lot faster:
```
$result = mysql_query('SELECT views FROM post ORDER BY views ASC LIMIT 30,1');
```
Note that Soviut's explanation of LIMIT is not quite correct - it's (offset, number of rows) rather than (min, max). | Use Single Row Query with MySQL and PHP | [
"",
"php",
"mysql",
""
] |
I'm trying to export a program in Eclipse to a jar file.
In my project I have added some pictures and PDF:s. When I'm exporting to jar file, it seems that only the `main` has been compiled and exported.
My will is to export everything to a jar file if it's possible, because then I want to convert it to an extraditable file, like .exe-file.
But how? | No need for external plugins. In the **Export JAR** dialog, make sure you select *all* the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.
[](https://i.stack.imgur.com/IsQZv.jpg) | Go to file->export->JAR file, there you may select "Export generated class files and sources" and make sure that your project is selected, and all folder under there are also! Good luck! | Java: export to an .jar file in eclipse | [
"",
"java",
"eclipse",
"executable",
"extract",
"exe",
""
] |
I have a string like this that I need to parse into a 2D array:
```
str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'"
```
the array equiv would be:
```
arr[0][0] = 813702104
arr[0][1] = 813702106
arr[1][0] = 813702141
arr[1][1] = 813702143
#... etc ...
```
I'm trying to do this by REGEX. The string above is buried in an HTML page but I can be certain it's the only string in that pattern on the page. I'm not sure if this is the best way, but it's all I've got right now.
```
imgRegex = re.compile(r"(?:'(?P<main>\d+)\[(?P<thumb>\d+)\]',?)+")
```
If I run `imgRegex.match(str).groups()` I only get one result (the first couplet). How do I either get multiple matches back or a 2d match object (if such a thing exists!)?
*Note: Contrary to how it might look, this is **not** homework*
# Note *part deux*: The real string is embedded in a *large* HTML file and therefore splitting does not appear to be an option.
I'm still getting answers for this, so I thought I better edit it to show why I'm not changing the accepted answer. Splitting, though more efficient on this test string, isn't going to extract the parts from a whole HTML file. I *could* combine a regex and splitting but that seems silly.
If you do have a better way to find the parts from a load of HTML (the pattern `\d+\[\d+\]` is unique to this string in the source), I'll happily change accepted answers. Anything else is academic. | I would try `findall` or `finditer` instead of `match`.
Edit by Oli: Yeah `findall` work brilliantly but I had to simplify the regex to:
```
r"'(?P<main>\d+)\[(?P<thumb>\d+)\]',?"
``` | I think I will not go for regex for this task. Python list comprehension is quite powerful for this
```
In [27]: s = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'"
In [28]: d=[[int(each1.strip(']\'')) for each1 in each.split('[')] for each in s.split(',')]
In [29]: d[0][1]
Out[29]: 813702106
In [30]: d[1][0]
Out[30]: 813702141
In [31]: d
Out[31]: [[813702104, 813702106], [813702141, 813702143], [813702172, 813702174]]
``` | Python regex to parse into a 2D array | [
"",
"python",
"regex",
""
] |
I have data that needs to be executed on a certain background thread. I have code coming from all other threads that need to call into this. does anyone have a good tutorial or best practice on having a queue for synchronization to support this threading requirement | You could either:
* implement a [producer/consumer model](http://msdn.microsoft.com/en-us/library/yy12yx1f.aspx) (which use not thread-safe [generic queue](http://msdn.microsoft.com/en-us/library/7977ey2c.aspx))
* or use in your background thread a [synchronized queue](http://msdn.microsoft.com/en-us/library/system.collections.queue.synchronized.aspx), which does comment on the process of Enumerating through a collection. | Check out [Threading in C#](http://www.albahari.com/threading/), by Joseph Albahari, very complete reference about multithreading. In particular, he covers [producer/consumer queues](http://www.albahari.com/threading/part2.aspx#_ProducerConsumerQWaitHandle). | Best threading queue example / best practice | [
"",
"c#",
"multithreading",
""
] |
Imagine a Java client/server ERP application serving up to 100 concurrent users, both web and swing clients. For persistence we can use Persistence API and Hibernate.
But when it comes to client/server communication, do we really have an alternative to using an AS with EJBs to keep down the programming costs of remote communication?
It seems a very heavyweight solution to throw in EJBs and an application server, just for remoting stuff. There is also the standard way using RMI, but who wants nowadays to code everything on his own...
I know that you'll get a lot of features for free with an AS in addition to the remoting part. And, maybe it's the way to go. But, are there really any other (low programming cost) alternatives to an AS for doing client/server communication for an enterprise application? | Personally I consider Seam to be the ultimate solution to the problem I don't have but that aside, there are lots of options and Spring is used for most of them:
* [RMI](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-rmi);
* [Hessian](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-caucho-protocols) (binary HTTP based protocol);
* [HTTP Invokers](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-caucho-protocols) (Java serialization over HTTP);
* [Web Services](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-web-services); or
* Even [JMS](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-jms).
The advantage of the HTTP based remoting methods is that they easily plug into Spring's security models. Plus then you get access to things like interceptors. | You can use light weight remoting frameworks. Spring is having a number of options in this section.
If you ask me one word for both, I will suggest two. Seam or Spring. I myself like Seam, but for lightweight remoting [Spring](http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html) has more viable solutions and support. Again if your AS is JBoss, give a thought to [Seam](http://docs.jboss.com/seam/2.0.1.GA/reference/en/html/remoting.html). | Are application servers (with EJBs) the only way for Java EE client/server communication? | [
"",
"java",
"remoting",
"client-server",
"enterprise",
""
] |
Am I allowed to add whatever attributes I want to HTML tags such that I can retrieve their value later on using javascript? For example:
```
<a href="something.html" hastooltip="yes" tipcolour="yellow">...</a>
```
If that's not going to work, how would you store arbitrary pieces of information like this?
**Edit:** Since it appears that making up HTML attributes isn't technically valid, I've rephrased the second part of this question into its own question here: [How to store arbitrary data for some HTML tags](https://stackoverflow.com/questions/432174/) | In HTML5, yes. You just have to prefix them with `data-`. See [the spec](https://www.w3schools.com/tags/att_global_data.asp).
Of course, this implies you should be using the HTML5 doctype (`<!doctype html>`), even though browsers don't care. | Well, you can always create your own DTD to get new valid attributes for your tags. Browser won't hiccup, you should test your JavaScript if you can access these custom attributes. Or you can use the existing facilities provided by HTML and CSS. You can use multiple classes like
```
<a href="..." class="class-one class-two has-tooltip">
```
For the colour selection I strongly discourage you to use hard-coded colour names in your HTML, you have CSS for declaring styles. Use the class attribute as a hook for the CSS declaration, and choose *semantic* class names, for example
HTML:
```
<a href="..." class="has-tooltip common-tooltip">
<a href="..." class="has-tooltip long-tooltip">
```
CSS:
```
a.has-tooltip {
colour: red;
}
a.common-tooltip {
background: #ddd;
}
a.long-tooltip {
background: #ebf;
}
```
And in your JavaScript code you can generate elements with classes like "long-tooltip" and "common-tooltip" instead of "yellow-tooltip", so you won't contradict yourself in case of redesigning the page to have green tooltips. | Can I just make up attributes on my HTML tags? | [
"",
"javascript",
"html",
""
] |
Seem to be having an issue with std::auto\_ptr and assignment, such that the object referenced seems to get trashed for some reason.
```
std::auto_ptr<AClass> someVar = new AClass(); // should work, but mangles content
std::auto_ptr<AClass> someVar( new AClass() ); // works fine.
std::auto_ptr<AClass> someVar = std::auto_ptr<AClass>(new AClass()); // works fine.
std::auto_ptr<AClass> someVar;
someVar.reset( new AClass() ); // works fine.
```
I've traced it through, and it appears (via watching the values in the debugger) that the problem occurs in the transfer of the pointer from the temporary std::auto\_ptr\_byref() that is created to wrap the rhs pointer. That is the value contained in \_Right on entering the auto\_ptr(auto\_ptr\_ref<\_Ty> \_Right) function is correct, but the value in \_Myptr on leaving is junk.
```
template<class _Ty>
struct auto_ptr_ref
{ // proxy reference for auto_ptr copying
auto_ptr_ref(void *_Right)
: _Ref(_Right)
{ // construct from generic pointer to auto_ptr ptr
}
void *_Ref; // generic pointer to auto_ptr ptr
};
template<class _Ty>
class auto_ptr
{ // wrap an object pointer to ensure destruction
public:
typedef _Ty element_type;
explicit auto_ptr(_Ty *_Ptr = 0) _THROW0()
: _Myptr(_Ptr)
{ // construct from object pointer
}
auto_ptr(auto_ptr<_Ty>& _Right) _THROW0()
: _Myptr(_Right.release())
{ // construct by assuming pointer from _Right auto_ptr
}
auto_ptr(auto_ptr_ref<_Ty> _Right) _THROW0()
{ // construct by assuming pointer from _Right auto_ptr_ref
_Ty **_Pptr = (_Ty **)_Right._Ref;
_Ty *_Ptr = *_Pptr;
*_Pptr = 0; // release old
_Myptr = _Ptr; // reset this
}
auto_ptr<_Ty>& operator=(auto_ptr_ref<_Ty> _Right) _THROW0()
{ // assign compatible _Right._Ref (assume pointer)
_Ty **_Pptr = (_Ty **)_Right._Ref;
_Ty *_Ptr = *_Pptr;
*_Pptr = 0; // release old
reset(_Ptr); // set new
return (*this);
}
```
At first I thought it was messing up the inheritance and slicing off interfaces, however this happens even if the class only has one parent class.
We can avoid doing = new if we remember, either by using brackets or changing to have a explicit std::auto\_ptr temp on the rhs, this is of course error prone.
Is it just this version of the library being broken, or some underlying thing I'm just not getting?
We also noticed a similar issue with assigning a std::auto\_ptr to a boot::shared\_ptr though we removed that entirely now and I don't recall which syntax caused the issue. | The first line:
```
std::auto_ptr<AClass> someVar = new AClass(); // should work, but mangles content
```
should result in a compiler error. Because there is no implicit conversion from the raw `AClass` pointer to an `auto_ptr` (the constructor for an `auto_ptr` that takes a raw pointer is marked `explicit`), initialization using the 'copy initializer' form is not permitted.
VC9 gives the following error:
```
C:\temp\test.cpp(23) : error C2440: 'initializing' : cannot convert from 'AClass *' to 'std::auto_ptr<_Ty>'
```
Other compilers I've tried (GCC 3.4.5, Comeau C/C++ 4.3.10.1, Digital Mars) give a similar error.
EDIT:
It looks like this is in fact a bug in VS2005's implementation of `auto_ptr<>` (not sure if it was introduced in SP1 or was in VS2005 from the start) that got fixed in VS2008. Here's the MS Connect bug record for the problem:
<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101842&wa=wsignin1.0> | Known bug in VC++ between VC6 and VC9: <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101842> | Why does std::auto_ptr operator = trash objects? | [
"",
"c++",
"memory",
"std",
""
] |
I have some code that uses the Oracle function add\_months to increment a Date by X number of months.
I now need to re-implement the same logic in a C / C++ function. For reasons I don't want/need to go into I can't simply issue a query to oracle to get the new date.
Does anyone know of a simple and reliable way of adding X number of months to a time\_t?
Some examples of the types of calculations are shown below.
30/01/2009 + 1 month = 28/02/2009
31/01/2009 + 1 month = 28/02/2009
27/02/2009 + 1 month = 27/03/2009
28/02/2009 + 1 month = 31/03/2009
31/01/2009 + 50 months = 31/03/2013 | Method **AddMonths\_OracleStyle** does what you need.
Perhaps you would want to replace IsLeapYear and GetDaysInMonth to some librarian methods.
```
#include <ctime>
#include <assert.h>
bool IsLeapYear(int year)
{
if (year % 4 != 0) return false;
if (year % 400 == 0) return true;
if (year % 100 == 0) return false;
return true;
}
int daysInMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int GetDaysInMonth(int year, int month)
{
assert(month >= 0);
assert(month < 12);
int days = daysInMonths[month];
if (month == 1 && IsLeapYear(year)) // February of a leap year
days += 1;
return days;
}
tm AddMonths_OracleStyle(const tm &d, int months)
{
bool isLastDayInMonth = d.tm_mday == GetDaysInMonth(d.tm_year, d.tm_mon);
int year = d.tm_year + months / 12;
int month = d.tm_mon + months % 12;
if (month > 11)
{
year += 1;
month -= 12;
}
int day;
if (isLastDayInMonth)
day = GetDaysInMonth(year, month); // Last day of month maps to last day of result month
else
day = std::min(d.tm_mday, GetDaysInMonth(year, month));
tm result = tm();
result.tm_year = year;
result.tm_mon = month;
result.tm_mday = day;
result.tm_hour = d.tm_hour;
result.tm_min = d.tm_min;
result.tm_sec = d.tm_sec;
return result;
}
time_t AddMonths_OracleStyle(const time_t &date, int months)
{
tm d = tm();
localtime_s(&d, &date);
tm result = AddMonths_OracleStyle(d, months);
return mktime(&result);
}
``` | Convert `time_t` to `struct tm`, add X to month, add months > 12 to years, convert back. tm.tm\_mon is an int, adding 32000+ months shouldn't be a problem.
[edit] You might find that matching Oracle is tricky once you get to the harder cases, like adding 12 months to 29/02/2008. Both 01/03/2009 and 28/02/2008 are reasonable. | easy way to add 1 month to a time_t in C/C++ | [
"",
"c++",
"c",
"date",
"time-t",
"date-math",
""
] |
I have a table named *visiting* that looks like this:
```
id | visitor_id | visit_time
-------------------------------------
1 | 1 | 2009-01-06 08:45:02
2 | 1 | 2009-01-06 08:58:11
3 | 1 | 2009-01-06 09:08:23
4 | 1 | 2009-01-06 21:55:23
5 | 1 | 2009-01-06 22:03:35
```
I want to work out a sql that can get how many times a user visits within *one session*(successive visit's interval less than 1 hour).
So, for the example data, I want to get following result:
```
visitor_id | count
-------------------
1 | 3
1 | 2
```
BTW, I use postgresql 8.3.
Thanks!
**UPDATE**: updated the timestamps in the example data table. sorry for the confusion.
**UPDATE**: I don't care much if the solution is a single sql query, using store procedure, subquery etc. I only care how to get it done :) | The question is slightly ambiguous because you're making the assumption or requiring that the hours are going to start at a set point, i.e. a natural query would also indicate that there's a result record of (1,2) for all the visits between the hour of 08:58 and 09:58. You would have to "tell" your query that the start times are for some determinable reason visits 1 and 4, or you'd get the natural result set:
```
visitor_id | count
--------------------
1 | 3
1 | 2 <- extra result starting at visit 2
1 | 1 <- extra result starting at visit 3
1 | 2
1 | 1 <- extra result starting at visit 5
```
That extra logic is going to be expensive and too complicated for my fragile mind this morning, somebody better than me at postgres can probably solve this.
I would normally want to solve this by having a sessionkey column in the table I could cheaply group by for perforamnce reasons, but there's also a logical problem I think. Deriving session info from timings seems dangerous to me because I don't believe that the user will be definitely logged out after an hours *activity*. Most session systems work by expiring the session after a period of *inactivity*, i.e. it's very likely that a visit after 9:45 is going to be in the same session because your hourly period is going to be reset at 9:08. | The problem seems a little fuzzy.
It gets more complicated as id 3 is within an hour of id 1 and 2, but if the user had visited at 9:50 then that would have been within an hour of 2 but not 1.
You seem to be after a smoothed total - for a given visit, how many visits are within the following hour?
Perhaps you should be asking for how many visits have a succeeding visit less than an hour distant? If a visit is less than an hour from the preceeding one then should it 'count'?
So what you probably want is how many chains do you have where the links are less than an arbitrary amount (so the hypothetical 9:50 visit would be included in the chain that starts with id 1). | a question about sql group by | [
"",
"sql",
"database",
"postgresql",
""
] |
I'm starting to love Lambda expressions but I'm struggling to pass this wall:
```
public class CompanyWithEmployees {
public CompanyWithEmployees() { }
public Company CompanyInfo { get; set; }
public List<Person> Employees { get; set; }
}
```
My search:
```
List<CompanyWithEmployees> companiesWithEmployees = ws.GetCompaniesWithEmployees();
CompanyWithEmployees ces = companiesWithEmployees
.Find(x => x.Employees
.Find(y => y.PersonID == person.PersonID));
```
So, I want to get the Object "CompanyWithEmployees" that have that Person (Employee) that I'm looking for, but I'm getting "*Cannot implicit convert 'Person' To 'bool')*" which is correct, but if I'm not passing the Person object, how can the first Find executes? | Because you want to check for existance, perhaps try:
```
ces = companiesWithEmployees
.Find(x => x.Employees
.Find(y => y.ParID == person.ParID) != null);
```
This will check for any `Person` with the same `ParID`; if you mean the same `Person` instance (reference), then `Contains` should suffice:
```
ces = companiesWithEmployees
.Find(x => x.Employees.Contains(person));
``` | `Find()` returns the found object. Use `Any()` to just check whether the expression is true for any element.
```
var ces = companiesWithEmployees
.Find(x => x.Employees
.Any(y => y.PersonID == person.PersonID));
``` | Lambda expressions, how to search inside an object? | [
"",
"c#",
"lambda",
""
] |
Both:
* CLSID
* IID
Having specified the above, and using:
* CoCreateInstance()
To returning a single uninitialised object of the class specified by the CLSID above.
How can I then access an Interface's method from C++?
Without:
* ATL
* MFC
* Just plain C++
Afterwards, I use CreateInstance()
I'm having trouble, using CreateInstance() - with the last parameter - ppv
Using oleview, I can see methods of the specified IIDabove IID above, such as:
```
interface IS8Simulation : IDispatch {
HRESULT Open([in] BSTR FileName);
};
```
How can I then access the above? Examples/guidance - please
Regards | By doing a CoCreateInstance you get an interface pointer. Through QueryInterface(...) method you can get the interface pointer of some other interface easily.
e.g.,
```
IUnknown* pUnk = NULL;
HRESULT hr = ::CoCreateInstance(clsid,NULL,CLSCTX_ALL,__uuidof(IUnknown),(void**)&pUnk);
```
IS8Simulation\* pSim = NULL;
hr = pUnk->QueryInterface(\_\_uuidof(IS8Simulation), (void\*\*)&pSim);
After doing this, you will get the pointer to IS8Simulation in pSim and through that you can call methods of that interface. Remember you need to provide a valid clsid in the CoCreateInstance call. | It's a little vague what the actual problem is. Some code would be helpful. But to take a guess, do you need to QueryInterface? | Access a COM Interface method C++ | [
"",
"c++",
"com",
"oleview",
""
] |
if my host does not allow me to upload a file directly to my mysql folder
and i can only do so throught phpmyadmin? are there any alternatives aside from its native import feature so that my connection would not time out while uploading a query that's around 8mb? | you can gzip or bzip the file and phpMyAdmin will decompress and run the script.
otherwise what I've had to do in the past is split my SQL into a number of files and load each one individually. You can do this simply by opening the SQL file in a text editor, scroll to about half way down, find the start of a statement and move everything after that into another file. | Don't use phpmyadmin for anything critical. Definitely don't use it to create backups or do restoration. It's a bag of rubbish.
Log on to your shell and use the mysql command line client to restore the database in the standard way. If you can't do that, get a better provider.
Shell access is necessary to work with mysql databases.
Don't expect anything done with phpmyadmin NOT to destroy all your data. | how to import a very large query over phpmyadmin? | [
"",
"php",
"mysql",
"timeout",
"phpmyadmin",
""
] |
Certain methods in Java will block until they can do something, like ServerSocket.accept() and InputStream.read(), but how it does this is not easy for me to find. The closest thing I can think of is a while() loop with a Thread.sleep() each time through, but the longer the sleep period, the less responsive the blocking, and the shorter the sleep, the more spinning that occurs.
I have two questions:
1. How do various standard functions, like the ones above, block? Native code? while() loops? Something else?
2. How should I implement methods that block? | The essential answer to (1) is "don't worry about it -- the OS handles it". Calls to things like reading from input streams are essentially wrappers around operating system calls. Under the hood inside the OS, what I think is usually happening when a call "blocks" in these cases is that the OS "knows" that it is waiting for a hardware interrupt from, say, the disk controller to say that such-and-such requested data is now available, and it knows that Thread X was the one that requested that data. So it doesn't schedule in Thread X again until it receives that interrupt (or an interrupt saying "there was an error" etc). (And part of the thread scheduling algorithm is then doing things like giving the waiting thread a temporary "boost" of some kind when that waited-for data becomes available. Again, usually you don't need to worry too much about this.) Or put another way: whatever the exact details of this mechanism, it's not available to the general Java programmer.
In (2), I would suggest thinking more about "how do I do Thing X, which might happen to block". I think the answer is hardly ever that Thing You Want To Do is deliberately just "block", and whatever Thing X is, there's probably a library method/class that will do it for you. For example (links include some material I've written on these subjects):
* if you want to take the next message/job when it becomes available from some queue/provider, look at [blocking queues](http://www.javamex.com/tutorials/synchronization_producer_consumer_2.shtml)
* if you need to control access to a shared resource with a "lock" on an object, waiting for the lock to become available if necessary, consider plain old synchronized, or an [explicit lock](http://www.javamex.com/tutorials/synchronization_concurrency_9_locks.shtml);
* if you want to wait for one of many *pooled resources* to become available, look at [semaphores](http://www.javamex.com/tutorials/synchronization_concurrency_semaphore.shtml)
I'd say that the raw wait/notify mechanism is largely deprecated with the Java 5 concurrency API. And whatever you're doing, spinlocking is usually the very very last resort. | The operations you've listed block because of the underlying platform (ie. native code).
You can implement a block using Java's `Object.wait()` and `Object.notify()` methods; `wait()` will block the calling thread until another thread calls `notify()` on the same lock. | Block without spinning in Java? | [
"",
"java",
"multithreading",
""
] |
I have an aspx page with a gridview. In my page load event, I load a datatable with all the data like so:
```
HistoricalPricing historicalPricing = new HistoricalPricing();
DataTable dtHistoricalPricing = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dtHistoricalPricing = historicalPricing.GetAuctionData();
}
}
```
The above loades the data into the datatable fine. I also have a listbox which contains a list of auctions. When I click on an auction, I use the RowFilter on a DataView to display a Gridview with the data that was selected, but the DataTable seems to loose its value and I can't figure out why. Here is the code below:
```
protected void lstAuctions_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dvPricing = new DataView(dtHistoricalPricing); // Loses Value
dvPricing.RowFilter = "Auction = 1"; //Hard-Coded for Test
gvPricing.DataSource = dvPricing.ToTable();
gvPricing.DataBind();
}
``` | Every time you do a postback you're dealing with a new instance of your page class. That means a new datatable object as well.
If you *really* want to persist it between postbacks (and make sure you consider the memory implications for that when you may have 1000 people hitting this web server at the same time) then you can put the datatable in the Session, ViewState, or other location that persists state. | I think I figured it out, is it because when I click on the ListBox, it does a postback and I am only loading the data on the first load of the Page? If this is correct, I think I answered my own question.
I put the datatable in Session after loading it on the first Page Load and this seemed to solve my problem. Not sure if this is the best way though. | Why doesn't globally declared DataTable retains its value? | [
"",
"c#",
"asp.net",
"gridview",
"datatable",
""
] |
I am trying to write a C# http server for a personal project, i am wondering how i can change the returned server header from Microsoft-HTTPAPI/2.0, to something else?
```
public class HttpWebServer
{
private HttpListener Listener;
public void Start()
{
Listener = new HttpListener();
Listener.Prefixes.Add("http://*:5555/");
Listener.Start();
Listener.BeginGetContext(ProcessRequest, Listener);
Console.WriteLine("Connection Started");
}
public void Stop()
{
Listener.Stop();
}
private void ProcessRequest(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
string responseString = "<html>Hello World</html>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
context.Response.ContentLength64 = buffer.Length;
System.IO.Stream output = context.Response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
Listener.BeginGetContext(ProcessRequest, Listener);
}
}
``` | The HttpListener class encapsulates the native API, [HttpSendHttpResponse Function](http://msdn.microsoft.com/en-us/library/aa364499(VS.85).aspx), which as stated in the link will always append the preposterous text to the server header information.
There's no way how to fix that, unless you want to code your HttpListener from scratch. | I know I'm a little late but I was just recently trying to do the same thing and I accidentally came across a solution that works but I'm unsure if it has any repercussions.
```
Response.Headers.Add("Server", "\r\n\r\n");
``` | HttpListener Server Header c# | [
"",
"c#",
"http",
"httplistener",
""
] |
I have a multi-threaded Windows C++ app written in Visual Studio 6.
Within the app 2 threads are running each trying to read UDP packets on different ports. If I protect the reading from the socket with a critical section then all the date read is fine. Without that protection data is lost from both sockets.
Is reading from a socket not thread safe? I've written many socket apps in the past and don't remember having to use this sort of thread protection. | ***Within the app 2 threads are running each trying to read UDP packets on different ports.***
How much UDP data are you sending/reading? How fast are you sending it? How much of your data is lost?
This could be a race condition... **Not between the two threads, but between the thread and the socket!**
I've seen problems in the past porting code from Linux to Windows. Windows uses (used) a default UDP buffersize of 8k. Naturally, we were sending 12k bursts, and there's just no way to read it fast enough even with a dedicated read thread!
You can change the UDP buffersize (under Windows) with something like:
```
int newBufferSize = 128 * 1024; // 128k
setsockopt( readSocketFd, SOL_SOCKET, SO_RCVBUF, (char *) & newBufferSize );
``` | Winsock is not guaranteed to be thread-safe. It's up to the implementer. Have a look [here](http://tangentsoft.net/wskfaq/intermediate.html#threadsafety). | Reading from 2 sockets in 2 threads causes data loss | [
"",
"c++",
"sockets",
""
] |
I come from a Java background and with any servlets-based technology, it's trivial to map a range of URLs (eg /reports/*, /secure/*.do) to a specified servlet. Now I'm less familiar with PHP but I haven't yet seen anything that does quite the same thing with PHP (or mod\_php). It's entirely possible that I'm missing something simple.
How do you do this in PHP?
One of the reasons I want to do this is "one use" URLs. Now this can sorta be done with GET parameters (like an MD5 hash token) but I'm interested in URL mapping as a general solution to many problems.
Another big reason to use something like this is to have RESTful URLs. | With Apache, you are able to setup URL Rewriting for your php pages with mod\_rewrite, check this resources:
* [mod\_rewrite: A Beginner's Guide to URL Rewriting](http://www.sitepoint.com/article/guide-url-rewriting/)
* [Module mod\_rewrite](http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html)
* [URL Rewriting Guide](http://httpd.apache.org/docs/2.0/misc/rewriteguide.html) | Other than using mod\_rewrite, as already reported you can do a little of magic with a simple trick.
Put into the .htaccess a directive like this one
```
<FilesMatch "^servlet$">
ForceType application/x-httpd-php
</FilesMatch>
```
substitute ^servlet$ with a regular expression of your choice (it will be the name of your dispatcher)
The file servlet should be similar to this
```
<?php
$data = explode('/',$HTTP_SERVER_VARS['PATH_INFO']); // $data[0] always empty
$fileToInclude = $data[1].'.php';
if (file_exists($data[1]) {
$params=array_slice($data,2); // you can do here something more sophisticated
// for example sanitize parameters or assemble
// an hash
include ($fileToInclude); //Think to this file as a servlet
} else {
// issue a 404 error, maybe one of the 500 series
}
?>
```
The url can have the form: <http://yoursite/servlet/reports/sales/2009>
you can also reach the form <http://yoursite/reports/sales/2009>
plaiyng a little with the .htacces and the dispatcher.
This method has the advantage that mod\_rewrite is not required as FilesMatch (1.3+) and ForceType (2.0+) are in the apache core
See for reference
<http://httpd.apache.org/docs/2.2/mod/core.html#forcetype>
<http://httpd.apache.org/docs/2.2/mod/core.html#filesmatch>
<http://www.devarticles.com/c/a/Apache/Using-ForceType-For-Nicer-Page-URLs/1/> | URL mapping in PHP? | [
"",
"php",
"apache",
"rest",
""
] |
I have a console application. A class (let's say Worker) does some work in a separate thread and throws an event when it finishes. But this never happens because the execution ends instantly. How can I wait for the thread to finish and handle the event after it throws?
```
static void Main(string[] args)
{
Worker worker = new Worker();
worker.WorkCompleted += PostProcess;
worker.DoWork();
}
static void PostProcess(object sender, EventArgs e) { // Cannot see this happening }
```
**Edit:** Corrected the order of the statements but that was not the problem. | You've got a race condition, in that the work could finish before you register for the event. To avoid the race condition, change the order of the code so you register for the event before starting the work, then it will always be raised, no matter how fast it finishes:
```
static void Main(string[] args)
{
Worker worker = new Worker();
worker.WorkCompleted += PostProcess;
worker.DoWork();
}
```
---
**Edit:**
OK the question has been modified, so it looks like what you're really asking is how to wait for `PostProcess` to finish executing. There are a couple of ways to do this, but you'll have to add some more code.
The easiest way is, because events always execute on the same thread as they are raised, is to call `Thread.Join` on the thread the `Worker` class creates, e.g. assuming the thread is exposed as a property:
```
worker.Thread.Join();
```
(Although to be honest I'd probably keep the `Thread` private and expose a method called something like `WaitForCompletion` on the `Worker` class that calls it).
Alternative methods are:
1. Have a `WaitHandle`, probably a `ManualResetEvent`, in the `Worker` class which is `Set` when it completes all its work, and call `WaitOne` on it.
2. Have a `volatile bool complete` field in the `Worker` class and loop while waiting for it to be set to `true`, using `Thread.Sleep` in the loop body (this probably isn't a good solution, but it is feasible).
There are probably other options too, but that's the common ones. | Have you tried switching the order of the statements ?
```
static void Main(string[] args)
{
Worker worker = new Worker();
worker.WorkCompleted += PostProcess;
worker.DoWork();
}
```
WorkCompleted is an event handler and has to be set up-front. This does not get invoked by the assignment worker.WorkCompleted += PostProcess; | How to wait for a thread to finish its work | [
"",
"c#",
"multithreading",
""
] |
What does the following expression return in Java?
```
Math.max(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
```
I saw this question in a website and the answer is `Double.POSITIVE_INFINITY`. I'm not sure about this answer as how can we compare 2 infinities? Can someone clarify this? Thanks. | Float.POSITIVE\_INFINITY returns float and Double.POSITIVE\_INFINITY returns double.
There is no method called Math.max(float, double).
only Math.max(float, float) and Math.max(double, double)
Therefore when the method is called Math.max(float, double), it converts the float argument to double and so the Math.max(double, double) is called so Double.POSITIVE\_INFINITY is returned.
Java does not convert from double to float since it may lead to precision problem. | Certainly you can compare infinities. Unless you get into transfinite numbering systems where there are varying degrees of infinity, infinity means just what it says, a number without limit.
The maximum/sum/product/average of two numbers without limit is one number without limit. | Comparing Infinities in Java | [
"",
"java",
""
] |
How can I get C# to distinguish between ambiguous class types without having to specify the full `HtmlAgilityPack.HtmlDocument` name every time (it is ambiguous compared to `System.Windows.Forms.HtmlDocument`)?
Is there a way to make C# know that I am ALWAYS talking about one class or the other, and thus not have to specify it each time I use it? | Use aliases:
```
using HapHtmlDocument = HtmlAgilityPack.HtmlDocument;
using WfHtmlDocument = System.Windows.Forms.HtmlDocument;
``` | You can define an alias for one namespace, e.g:
```
using hap = HtmlAgilityPack;
```
and then use the alias instead of the full namespace:
```
hap.HtmlDocument doc = new hap.HtmlDocument;
``` | How Can I Get C# To Distinguish Between Ambiguous Class Names? | [
"",
"c#",
".net",
""
] |
Every tutorial or explanation of REST just goes too complicated too quickly - the learning curve rises so fast after the initial explanation of CRUD and the supposed simplicity over SOAP. Why can't people write decent tutorials anymore!
I'm looking at Restlet - and its not the best, there are things missing in the tutorial and the language/grammar is a bit confusing and unclear. It has took me hours to untangle their First Steps tutorial (with the help of another Java programmer!)
**RESTlet Tutorial Comments**
Overall I'm not sure exactly who the tutorial was aimed at - because there is a fair degree of assumed knowledge all round, so coming into REST and Restlet framework cold leaves you with a lot of 'catchup work' to do, and re-reading paragraphs over and over again.
1. We had difficulty working out that the jars had to be in copied into the correct lib folder.
2. Problems with web.xml creating a HTTP Status 500 error -
> The server encountered an internal
> error () that prevented it from
> fulfilling this request
, the tutorial says:
> "Create a new Servlet Web application
> as usual, add a
> "com.firstStepsServlet" package and
> put the resource and application
> classes in."
This means that your fully qualified name for your class **FirstStepsApplication** is **com.firstStepsServlet.FirstStepsApplication**, so we had to alter web.xml to refer to the correct class e.g:
original:
```
<param-value>
firstStepsServlet.FirstStepsApplication
</param-value>
```
should be:
```
<param-value>
com.firstStepsServlet.FirstStepsApplication
</param-value>
```
---
**Conclusion**
I was under the impression that the concepts of REST were supposed to be much simpler than SOAP - but it seems just as bad if not more complicated - don't get it at all! grrrr
Any good links - much appreciated. | It sounds like you could use a solid understanding of the fundamentals of REST, and for that I *highly* recommend [RESTful Web Services](https://rads.stackoverflow.com/amzn/click/com/0596529260) by Leonard Richardson and Sam Ruby. I provides a great introduction to REST: what it is and how to implement a (practical) RESTful web service.
Most of the example code in the book is actually Ruby, but it's easy enough to understand even if you're not a Ruby expert. But one thing that should help you specifically is that one of the later chapters of the book contains overviews of several RESTful frameworks, including Restlet. It doesn't really get into any code (it's a 50,000-foot flyover) but I think it'll give you just what you need at this stage. | Could you describe precisely what caused you troubles in our Restlet tutorials? We are interested in fixing/improving what needs to.
Did you check the screencasts?
<http://www.restlet.org/documentation/1.1/screencast/>
Otherwise, there is a Restlet tutorial in the O'Reilly book that we wrote in their Chapter 12.
If you still have troubles, please contact our mailing list:
<http://www.restlet.org/community/lists>
Best regards,
Jérôme Louvel
Restlet ~ Founder and Lead developer ~ <http://www.restlet.org>
Noelios Technologies ~ Co-founder ~ <http://www.noelios.com> | Any easy REST tutorials for Java? | [
"",
"java",
"rest",
""
] |
Is it possible to close parent window in Firefox 2.0 using JavaScript. I have a parent page which opens another window, i need to close the parent window after say 10 seconds.
I have tried Firefox tweaks "dom.allow\_scripts\_to\_close\_windows", tried delay but nothing seems to work.
Any help will be really appreciated.
Thanks | Scissored from [quirksmode](http://www.quirksmode.org/js/croswin.html) (EDIT: added a bit of context, as suggested by Diodeus):
Theoretically
```
opener.close()
```
should be the code from the popup: close the window that has opened this popup.
However, in some browsers it is not allowed to automatically close windows that have not been opened by JavaScript. The line above works fine in Explorer on Mac, Mozilla, Opera and OmniWeb, but not in Explorer on Windows, Netscape 4 and lower and iCab. In these browsers the user is asked to confirm the closing of the window. As to Safari, it does absolutely nothing.
Rather to my surprise it's very easy to get around this confirm box in Explorer 5.5 and 6 on Windows. Explorer merely looks if the page has an opener. If it doesn't the window has been opened by the user and may not be closed without a confirm. So what we need to do is trick Explorer into thinking the opening page has an opener:
```
opener.opener = top; // or whatever, as long as opener.opener has a value;
opener.close()
```
This trick doesn't work in Netscape 4 and lower and iCab, these browsers have more sophisticated ways to determine whether a window has been opened by JavaScript. | Using only the opener object may not always close the parent window, for security reasons.
What you can do is:
On parent, have a function named closeWindowFromChild():
```
function closeWindowFromChild()
{
this.window.close();
}
```
On child, when you want to close the window:
```
function closeParentWindow()
{
opener.closeWindowFromChild();
}
```
And this should work fine. :-D | Close Parent window in fireFox | [
"",
"javascript",
"firefox",
""
] |
If I have two objects on the heap referring to each other but they are not linking to any reference variable then are those objects eligible for garbage collection? | Yes, they are. Basically the GC walks from "known roots" (static variables, local variables from all stack frames in alll threads) to find objects which can't be garbage collected. If there's no way of getting to an object from a root, it's eligible for collection.
EDIT: Tom pointed this out, which I thought was worth lifting into the answer itself:
> Technically, static variables are not
> roots - they are referenced by classes
> which are referenced by class loaders
> which are referenced by classes which
> are referenced by object which are
> referenced by root references.
The difference is likely to be irrelevant *most* of the time, but it's good to know :) | Check this out: [How does Java Garbage Collector Handle Self References](https://stackoverflow.com/questions/407855/how-does-java-garbage-collector-handle-self-reference).
You may want to check [`java.lang.ref.WeakReference`](http://java.sun.com/javase/6/docs/api/java/lang/ref/WeakReference.html) | Garbage collection behavior with isolated cyclic references? | [
"",
"java",
"garbage-collection",
""
] |
Hi all I've just started a new project using Visual Web Developer 2008 Express and all my code behinds are not in any namespace. How can I set the default namespace for the project?
In VisualStudioPro it used to be in project properties, the website properties in Visual Web Developer 2008 Express seem very ... express.
Thanks,
David. | Visual Web Developer (prior to 2008 SP1) does not support Web Application projects. Default namespace is only available in Web Application projects.
If you really want to add your classes to a namespace, you should do it manually (the namespace surround with code snippet can prove pretty useful) by enclosing them in a namespace statement:
```
namespace MyDefaultNamespace {
// original code
}
``` | If you are using the Website Project Template, then namespaces aren't used. If this is the case, consider using the Web Application Project Template. | Setting Default Namespace in Visual Web Developer 2008 Express | [
"",
"c#",
"asp.net",
"visual-studio-2008",
"visual-web-developer",
""
] |
I have a simple 2D array of strings and I would like to stuff it into an SPFieldMultiLineText in MOSS. This maps to an ntext database field.
I know I can serialize to XML and store to the file system, but I would like to serialize without touching the filesystem.
```
public override void ItemAdding(SPItemEventProperties properties)
{
// build the array
List<List<string>> matrix = new List<List<string>>();
/*
* populating the array is snipped, works fine
*/
// now stick this matrix into the field in my list item
properties.AfterProperties["myNoteField"] = matrix; // throws an error
}
```
Looks like I should be able to do something like this:
```
XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
properties.AfterProperties["myNoteField"] = s.Serialize.ToString();
```
but that doesn't work. All the examples I've found demonstrate writing to a text file. | ```
StringWriter outStream = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
s.Serialize(outStream, myObj);
properties.AfterProperties["myNoteField"] = outStream.ToString();
``` | Here's a Generic serializer (C#):
```
public string SerializeObject<T>(T objectToSerialize)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream memStr = new MemoryStream();
try
{
bf.Serialize(memStr, objectToSerialize);
memStr.Position = 0;
return Convert.ToBase64String(memStr.ToArray());
}
finally
{
memStr.Close();
}
}
```
In your case you could call with:
```
SerializeObject<List<string>>(matrix);
``` | Serialization in C# without using file system | [
"",
"c#",
"sharepoint",
"serialization",
"moss",
"wss",
""
] |
My page deals with many "Store" objects, each of them has a field called 'data'. However, this data is fetched via AJAX requests which may be parallely going on.
```
function Store(id){
this.id = id;
this.queryparam = 'blah';
this.items = null;
}
Store.prototype.fetch = function(){
$.get("/get_items",{q:this.quaryparam},function(data,status){
// how to store the received data in this particular store object? Being
// a callback function, I don't have a reference to this object as 'this'
// this.data = data; //will not work
});
}
```
In the callback function I tried defining a default parameter to the calling objects as following:
```
$.get("/get_items",{q:this.quaryparam},function(data,status, ref = this) ...
```
But turns out that javascript does not support default argument values like this. **Can I somehow get jquery to pass a reference to 'this' store in the callback function?**
I thought of a couple of other approaches but none of them work:
I could set the store data using synchronous requests but then thats not the point of AJAX, is it?
Another way for me could be, to send the store id also in the requests which will come back in the response. For eg:
```
// in Store.fetch()
$.get("/get_items",{q:this.quaryparam,id:this.id},function(responsetext,status){
var response = eval(responsetext);
stores[response.id].data = response.data;
});
```
I do not like this approach because this pollutes the response just because the client-side code was unable to keep track of which request was sent by which object.
Moreover, since store.id is client-specific, it will also mess up caching at the server. A different request URL will be used for two different stores even though they have the same query parameters.
Is there any other way to achieve what I want? | You should be able to use closure:
```
var tmp = this;
$.get("/get_items",{q:this.quaryparam},function(data,status){
tmp.data = data;
});
```
Is that what you mean? | function Store(id){
this.id = id;
this.queryparam = 'blah';
this.items = null;
}
```
Store.prototype.fetch = function(){
var that = this;
$.get("/get_items",{q:this.quaryparam},function(response){
that.callback(response)
});
}
Store.prototype.callback = function(response){
// and here you can use
this.items = response // just example
}
``` | How to get jQuery to pass custom arguments to asynchronous AJAX callback functions? | [
"",
"javascript",
"jquery",
"ajax",
""
] |
I'm a newbie to python and the app engine.
I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using [GAEUnit](http://code.google.com/p/gaeunit/)), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?
```
class EmailHandler(webapp.RequestHandler):
def bad_input(self):
self.response.set_status(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>bad input </body></html>")
def get(self):
to_addr = self.request.get("to")
subj = self.request.get("subject")
msg = self.request.get("body")
if not mail.is_email_valid(to_addr):
# Return an error message...
# self.bad_input()
pass
# authenticate here
message = mail.EmailMessage()
message.sender = "my.company@gmail.com"
message.to = to_addr
message.subject = subj
message.body = msg
message.send()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>success!</body></html>")
```
And the unit tests,
```
import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler
class SendingEmails(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)
def test_success(self):
app = TestApp(self.application)
response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject')
self.assertEqual('200 OK', response.status)
self.assertTrue('success' in response)
# somehow, assert email was sent
``` | A very short introduction provides [PyPI: MiniMock 1.0](http://pypi.python.org/pypi/MiniMock/1.0). It's a very small library to establish mocks.
1. Inject your mock into the module, that should be mocked
2. Define, what your mock will return
3. Call the method
4. Your mock will say, which method were called.
Good luck! | You could also override the `_GenerateLog` method in the `mail_stub` inside AppEngine.
Here is a parent TestCase class that I use as a mixin when testing that e-mails are sent:
```
from google.appengine.api import apiproxy_stub_map, mail_stub
__all__ = ['MailTestCase']
class MailTestCase(object):
def setUp(self):
super(MailTestCase, self).setUp()
self.set_mail_stub()
self.clear_sent_messages()
def set_mail_stub(self):
test_case = self
class MailStub(mail_stub.MailServiceStub):
def _GenerateLog(self, method, message, log, *args, **kwargs):
test_case._sent_messages.append(message)
return super(MailStub, self)._GenerateLog(method, message, log, *args, **kwargs)
if 'mail' in apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map:
del apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map['mail']
apiproxy_stub_map.apiproxy.RegisterStub('mail', MailStub())
def clear_sent_messages(self):
self._sent_messages = []
def get_sent_messages(self):
return self._sent_messages
def assertEmailSent(self, to=None, sender=None, subject=None, body=None):
for message in self.get_sent_messages():
if to and to not in message.to_list(): continue
if sender and sender != message.sender(): continue
if subject and subject != message.subject(): continue
if body and body not in message.textbody(): continue
return
failure_message = "Expected e-mail message sent."
args = []
if to: args.append('To: %s' % to)
if sender: args.append('From: %s' % sender)
if subject: args.append('Subject: %s' % subject)
if body: args.append('Body (contains): %s' % body)
if args:
failure_message += ' Arguments expected: ' + ', '.join(args)
self.fail(failure_message)
```
After that, a sample test case might look like:
```
import unittest, MailTestCase
class MyTestCase(unittest.TestCase, MailTestCase):
def test_email_sent(self):
send_email_to('test@example.org') # Some method that would send an e-mail.
self.assertEmailSent(to='test@example.org')
self.assertEqual(len(self.get_sent_messages()), 1)
``` | Unit testing and mocking email sender in Python with Google AppEngine | [
"",
"python",
"unit-testing",
"google-app-engine",
"mocking",
""
] |
There is one thing that I do not understand...
Imagine you have a **text** = "hello world" and you want to split it.
In some places I see people that want to split the **text** doing:
```
string.split(text)
```
In other places I see people just doing:
```
text.split()
```
What’s the difference? Why you do in one way or in the other way? Can you give me a theory explanation about that? | Interestingly, the docstrings for the two are not completely the same in Python 2.5.1:
```
>>> import string
>>> help(string.split)
Help on function split in module string:
split(s, sep=None, maxsplit=-1)
split(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator.
(split and splitfields are synonymous)
>>> help("".split)
Help on built-in function split:
split(...)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator.
```
Digging deeper, you'll see that the two forms are completely equivalent, as [string.split(s)](http://svn.python.org/view/python/tags/r251/Lib/string.py?rev=54864&view=markup) actually calls [s.split()](http://svn.python.org/view/python/tags/r251/Objects/unicodeobject.c?rev=54864&view=markup) (search for the *split*-functions). | The `string.split(stringobj)` is a feature of the `string` module, which must be imported separately. Once upon a time, that was the only way to split a string. That's some old code you're looking at.
The `stringobj.split()` is a feature of a string object, `stringobj`, which is more recent than the `string` module. But pretty old, nonetheless. That's the current practice. | string.split(text) or text.split() : what's the difference? | [
"",
"python",
"string",
"split",
""
] |
I have a script that needs to run after tomcat has finished starting up and is ready to start deploying applications. I'm using `$TOMCAT_HOME/bin/startup.sh` which returns immediately. How can I wait until tomcat has finished starting up? | There are probably several ways to do this. The trick we use is:
```
#!/bin/bash
until [ "`curl --silent --show-error --connect-timeout 1 -I http://localhost:8080 | grep 'Coyote'`" != "" ];
do
echo --- sleeping for 10 seconds
sleep 10
done
echo Tomcat is ready!
```
Hope this helps! | It's not hard to implement programaticaly. You can implement org.apache.catalina.LifecycleListener and then you'll have
```
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if(lifecycleEvent.getType().equals(Lifecycle.START_EVENT))
//do what you want
}
}
```
in web.xml :
```
<Context path="/examples" ...>
...
<Listener className="com.mycompany.mypackage.MyListener" ... >
...
</Context>
```
Please notice that some things could differ between 6-9 Tomcats. | Wait until tomcat finishes starting up | [
"",
"java",
"linux",
"tomcat",
""
] |
I am having an Event Management System in which i want,
If an event is registered for 5 days (21 jan 2009 to 26 Jan 2009) Then if another person wants to register an event between 22 jan 2009 to 24 jan 2009 then it will not allow to register. I want to check this using SQL query, so please tell me how can i do this. | SELECT \*
FROM events e
WHERE (@startDate BETWEEN e.startDate and e.endDate)
OR (@endDate BETWEEN e.startDate and e.endDate)
OR (@startDate < e.startDate AND @endDate > e.endDate) | Just a to complete other answers, you have a good article on **[How to Search for Date and Time Values Using SQL Server 2000](http://www.devarticles.com/c/a/SQL-Server/Date-and-Time-Values-Using-SQL-Server-2000/)**
It reminds you about how date/time values are stored (two date/time data types: datetime and smalldatetime)
It also points out Datetime and smalldatetime are like the floating-point data types, float and real, in that they’re approximate numerics. That means the value retrieved from SQL Server may be different from the value that was originally stored.
Plus, it warns about Database designers who don’t always use date/time columns appropriately. At the time the database is designed, each date/time column should be identified as to whether it will store both dates and times, dates only, or times only.
It closes with [practical queries on data/time](http://www.devarticles.com/c/a/SQL-Server/Date-and-Time-Values-Using-SQL-Server-2000/6/).
You also have a good description of [DATEADD and DATEDIFF here](http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1333669,00.html#). | How to Search date in SQL? | [
"",
"sql",
"sql-server",
"date",
"sql-server-2000",
""
] |
Is there any tricky way to use Java reserved words as variable, method, class, interface, package, or enum constant names? | No, there is no way. That's why they're labeled "reserved". | This is a valid question. Such a thing *is* possible in other languages. In C#, prefix the identifier with `@` ([as asked before](https://stackoverflow.com/questions/421257/how-i-use-a-c-keyword-as-a-property-on-an-anonymous-object#421263)); in Delphi, prefix with `&`. But Java offers no such feature (partly because it doesn't really need to interact with identifiers defined by other languages the way the .Net world does). | Reserved words as names or identifiers | [
"",
"java",
"naming",
"reserved-words",
""
] |
I basically need to know how to import SQL code into Access. I've tried one way but that requires me to do one table and one value at a time which takes a lot of time.
Can anyone help? | Well, some days ago I needed to shift data from an Access database to SQL (reverse of what you're doing). I found it simpler to write a simple script that would read data from my access database and insert it into SQL.
I don't think doing what you need to do is any different.
I don't know if it will help, but I posting my code (It's a simple C# function). You can just change the connections and it will work. Of course I only had 3 fields so I hard-coded them. You can do the same for your db schema.
```
protected void btnProcess_Click(object sender, EventArgs e)
{
//Open the connections to the access and SQL databases
string sqlDBCnn = @"Data Source=.\SQLEXPRESS;Integrated Security=True;AttachDBFileName=|DataDirectory|\mydb.mdf;user instance=true";
string accessDBCnn = @"Provider=Microsoft.Jet.OleDB.4.0;Data Source=C:\mydb.mdb";
OleDbConnection cnnAcc = new OleDbConnection(accessDBCnn);
cnnAcc.Open();
SqlConnection cnnSql = new SqlConnection(sqlDBCnn);
cnnSql.Open();
SqlCommand cmSql = new SqlCommand("DELETE tablename", cnnSql);
cmSql.ExecuteNonQuery();
//Retrieve the data from the Access Database
OleDbCommand cmdAcc = new OleDbCommand("SELECT * FROM tablename", cnnAcc);
OleDbDataReader drAcc = cmdAcc.ExecuteReader();
using (drAcc)
{
if (drAcc.HasRows)
{
//Loop through the access database records and add them to the database
while (drAcc.Read())
{
SqlCommand cmdSql = new SqlCommand("INSERT INTO tablename(Category, Head, Val) VALUES(@cat,@head,@val)",cnnSql);
SqlParameter parCat = new SqlParameter("cat",System.Data.SqlDbType.VarChar,150);
SqlParameter parHead = new SqlParameter("head",System.Data.SqlDbType.VarChar,150);
SqlParameter parVal = new SqlParameter("val",System.Data.SqlDbType.VarChar);
parCat.Value = drAcc["Category"].ToString();
parHead.Value = drAcc["Head"].ToString();
parVal.Value = drAcc["Val"].ToString();
cmdSql.Parameters.Add(parCat);
cmdSql.Parameters.Add(parHead);
cmdSql.Parameters.Add(parVal);
cmdSql.ExecuteNonQuery();
}
}
}
lblMsg.Text = "<p /> All Done Kapitone!";
}
``` | If you are trying to import data, rather than SQL code (see Duffymo's response), there are two ways.
One is to go where the data is and dump a .CSV file and import that, as Duffymo responded.
The other is to create a table link from the Access database to a table in the source database. If the two databases will talk to each other this way, you can use the data in the remote table as if it were in the Access database. | SQL code import into Access 2007 | [
"",
"sql",
"sql-server",
"ms-access-2007",
""
] |
I have a number of native C++ libraries (Win32, without MFC) compiling under Visual Studio 2005, and used in a number of solutions.
I'd like to be able to choose to compile and link them as either static libraries or DLLs, depending on the needs of the particular solution in which I'm using them.
What's the best way to do this? I've considered these approaches:
## 1. Multiple project files
* Example: "foo\_static.vcproj" vs "foo\_dll.vcproj"
* Pro: easy to generate for new libraries, not too much manual vcproj munging.
* Con: settings, file lists, etc. in two places get out of sync too easily.
## 2. Single project file, multiple configurations
* Example: "Debug | Win32" vs "Debug DLL | Win32", etc.
* Pro: file lists are easier to keep in sync; compilation options are somewhat easier to keep in sync
* Con: I build for both Win32 and Smart Device targets, so I already have multiple configurations; I don't want to make my combinatorial explosion worse ("Static library for FooPhone | WinMobile 6", "Dynamic library for FooPhone | WinMobile 6", "Static library for BarPda | WinMobile 6", etc.
* Worse Con: VS 2005 has a bad habit of assuming that if you have a configuration defined for platform "Foo", then you really need it for all other platforms in your solution, and haphazardly inserts all permutations of configuration/platform configurations all over the affected vcproj files, whether valid or not. (Bug filed with MS; closed as WONTFIX.)
## 3. Single project file, selecting static or dynamic via vsprops files
* Example: store the appropriate vcproj fragments in property sheet files, then apply the "FooApp Static Library" property sheet to config/platform combinations when you want static libs, and apply the "FooApp DLL" property sheet when you want DLLs.
* Pros: **This is what I really want to do!**
* Cons: **It doesn't seem possible.** It seems that the .vcproj attribute that switches between static and dynamic libraries (the ConfigurationType attribute of the Configuration element) isn't overrideable by the .vsprops file. Microsoft's published schema for these files lists only <Tool> and <UserMacro> elements.
**EDIT**: In case someone suggests it, I've also tried a more "clever" version of #3, in which I define a .vsprops containing a UserMacro called "ModuleConfigurationType" with a value of either "2" (DLL) or "4" (static library), and changed the configuration in the .vcproj to have `ConfigurationType="$(ModuleConfigurationType)"`. Visual Studio silently and without warning removes the attribute and replaces it with `ConfigurationType="1"`. So helpful!
Am I missing a better solution? | I may have missed something, but why can't you define the DLL project with no files, and just have it link the lib created by the other project?
And, with respect to settings, you can factor them out in vsprop files... | **There is an easy way to create both static and dll lib versions in one project.**
Create your dll project. Then do the following to it:
Simply create an nmake makefile or .bat file that runs the lib tool.
Basically, this is just this:
```
lib /NOLOGO /OUT:<your_lib_pathname> @<<
<list_all_of_your_obj_paths_here>
<<
```
Then, in your project, add a Post Build Event where the command just runs the .bat file (or nmake or perl). Then, you will always get both a dll and a static lib.
I'll refrain from denigrating visual studio for not allowing the tool for this to exist in a project just before Linker (in the tool flow). | Building both DLL and static libs from the same project | [
"",
"c++",
"winapi",
"visual-studio-2005",
"projects-and-solutions",
"vsprops",
""
] |
Does anyone have any guidance or recommendations for writing a MIDI-based application in C# Winforms? I have recently bought a new effects pedal that has a full MIDI implementation (or so I'm led to believe) but the manufacturers have seen fit to not release a librarian / patch editing application.
I have virtually no experience of MIDI beyond plugging a keyboard into another MIDI device, but it can't be that hard, right? ;-)
Thanks in advance. | check out this links, this is maybe what you are looking for
* <http://www.codeproject.com/KB/audio-video/MIDIToolkit.aspx>
* <http://www.codeproject.com/KB/audio-video/midiports.aspx> | Also check out [NAudio](http://www.codeplex.com/naudio) | Midi implementation within .Net | [
"",
"c#",
"midi",
"sysex",
""
] |
I was trying to access swf from javascript, so this example in livedocs is what I'm trying to modify. <http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html#includeExamplesSummary>
However,it is not working correctly for some reason. The problem I'm encountering
is that it does not work in Safari and in Firefox, it only works if I put an alert
in the function before javascript pass the value to swf. (seems like it needs some time)
I also tried to set a timer in as3, but timer doesn't work, only alert in js helps.
All I wanted to do is use js to tell the swf file to play ep1.swf.
Here's my js code:
```
document.observe('dom:loaded', function() {
$('episode1').observe('click', function() {
var params = {wmode : "transparent", allowScriptAccess:"always", movie:"header"};
swfobject.embedSWF("swf/float.swf", "header", "100%", "100%", "9.0.0","expressInstall.swf", "", params, "");
sendToActionScript("ep1.swf");
});
})
function thisMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
return window[movieName];
} else {
//alert("aaa")
return document[movieName];
}
}
function sendToActionScript(value) {
thisMovie('header').sendToActionScript(value);
}
```
Here's my as3 code:
```
private function receivedFromJavaScript(value:String):void {
loader.load(new URLRequest(value));
}
```
I've been trying for a really long time, does anyone know how to fix this? Thanks. | The problem is that the SWF file isn't fully loaded by the time you try to call it. The flash player is probably loaded but it takes a while to load and initialise the swf file.
What you need to do is make a call from the SWF file to a javascript function when it's loaded and put your javascript there rather than in the page loaded handler that you seem to be doing now. That way you know that your flash application is properly initialized by then. The ExternalInterface class you are using has methods to let you call back into the javascript. | Use this code to get swf Object.
I tested this code on:
* IE 9,8,7
* Firefox 6.0.1
* Netscape Navigator 9.0.0.6
* Opera 11.5
* Google chrome 13.0.782.215
* Safari 3.2 (All In Windows OS)
and it worked fine.
```
function GetSWF(strName) {
if (window.document[strName] != null) {
if (window.document[strName].length == null)
return window.document[strName];
else
return window.document[strName][1];
} else {
if (document[strName].length == null)
return document[strName];
else
return document[strName][1];
}
}
``` | as3 ExternalInterface.addCallback is not working right | [
"",
"javascript",
"actionscript-3",
"externalinterface",
"addcallback",
""
] |
I'd use a singleton like this:
```
Singleton* single = Singleton::instance();
single->do_it();
```
I'd use an unnamed class like this:
```
single.do_it();
```
I feel as if the Singleton pattern has no advantage over the unnamed class other than having readable error messages. Using singletons is clumsier than using an unnamed class object: First, clients must first get a handle of the instance; second, the implementer of `Singleton::instance()` might need to consider concurrency.
So why and how would you choose a singleton over an unnamed class?
As an addendum, although the obvious definition of an unnamed class might be
```
class {
// ...
}single;
```
I could as well define it like so:
```
#ifndef NDEBUG
class Singleton__ { // readable error messages,
#else
class { // unnamed, clients can't instantiate
#endif
// ...
}single;
```
with the latter approach having the advantage of readable compiler error messages but not being a singleton in debug mode. | I think the most important reason is that you cannot put an unnamed class in namespace scope. So, the following is not valid (gcc accepts, but warns. comeau doesn't accept in strict mode):
```
class { } single;
int main() { }
```
The type of `single` has *no* linkage because there is no way to declare its name in another scope referring to it (precisely because it has no name). But using it to declare `single`, which *has* linkage (external here) is not valid (3.5/8). `single` has to be defined locally in main where it will have no linkage. You also cannot pass single to function templates and it can't have static data members (because there is no way to define them). All those restrictions make it more or less not applicable as a substitution for a singleton. | Surely the main reason for using singleton objects in C++ is to give you some control over the initialization order, by using 'lazy construction' within your instance method?
As an example, much of my code uses a logger singleton where log messages are written to. This started many moons ago as a good old 'global', but after being bitten by attempting to use it before construction, it's now a singleton:
before...
```
logger.write("Something bad happened..."); // crash if logger not constructed
```
...after
```
Logger &getLogger()
{
static Logger logger_;
return logger_;
}
getLogger().write("Something bad happened...");
```
I've read the regular "singletons are bad" posts, but havn't seen anyone suggest a better alternative for C++. | How do you choose between a singleton and an unnamed class? | [
"",
"c++",
"singleton",
""
] |
So I'm learning java, and I have a question. It seems that the types `int`, `boolean` and `string` will be good for just about everything I'll ever need in terms of variables, except perhaps `float` could be used when decimal numbers are needed in a number.
My question is, are the other types such as `long`, `double`, `byte`, `char` etc ever used in normal, everyday programming? What are some practical things these could be used for? What do they exist for? | With the possible exception of "short", which arguably is a bit of a waste of space-- sometimes literally, they're all horses for courses:
* Use an **int** when you don't need fractional numbers and you've no reason to use anything else; on most processors/OS configurations, this is the size of number that the machine can deal with most efficiently;
* Use a **double** when you need fractional numbers and you've no reason to use anything else;
* Use a **char** when you want to represent a character (or possibly rare cases where you need two-byte unsigned arithmetic);
* Use a **byte** if either you specifically need to manipulate a *signed* byte (rare!), or when you need to move around a *block* of bytes;
* Use a **boolean** when you need a simple "yes/no" flag;
* Use a **long** for those occasions where you need a whole number, but where the magnitude could exceed 2 billion (file sizes, time measurements in milliseconds/nanoseconds, in advanced uses for compacting several pieces of data into a single number);
* Use a **float** for those rare cases where you either (a) are storing a *huge number* of them and the memory saving is worthwhile, or (b) are performing a *massive number of calculations*, and can afford the loss in accuracy. For most applications, "float" offers very poor precision, but operations can be twice as fast -- it's worth testing this on your processor, though, to find that it's actually the case! [\*]
* Use a **short** if you really need 2-byte signed arithmetic. There aren't so many cases...
[\*] For example, in Hotspot on Pentium architectures, f[loat and double operations generally take exactly the same time](http://www.javamex.com/tutorials/math/basic_operations.shtml), except for division.
Don't get too bogged down in the memory usage of these types unless you *really* understand it. For example:
* **every object size is rounded to 16 bytes** in Hotspot, so an object with a single byte field will take up precisely the same space as a single object with a long or double field;
* when passing parameters to a method, **every type takes up 4 or 8 bytes on the stack**: you won't save anything by changing a method parameter from, say, an int to a short! (I've seen people do this...)
Obviously, there are certain API calls (e.g. various calls for non-CPU intensive tasks that for some reason take floats) where you just have to pass it the type that it asks for...!
Note that String isn't a primitive type, so it doesn't really belong in this list. | A java int is 32 bits, while a long is 64 bits, so when you need to represent integers larger than 2^31, long is your friend. For a typical example of the use of long, see System.currentTimeMillis()
A byte is 8 bits, and the smallest addressable entity on most modern hardware, so it is needed when reading binary data from a file.
A double has twice the size of a float, so you would usually use a double rather than a float, unless you have some restrictions on size or speed and a float has sufficient capacity.
A short is two bytes, 16 bits. In my opinion, this is the least necessary datatype, and I haven't really seen that in actual code, but again, it might be useful for reading binary file formats or doing low level network protocols. For example ip port numbers are 16 bit.
Char represents a single character, which is 16 bits. This is the same size as a short, but a short is signed (-32768 to 32767) while a char is unsigned (0 to 65535). (This means that an ip port number probably is more correctly represented as a char than a short, but this seems to be outside the intended scope for chars...)
For the really authorative source on these details, se the [java language specification](http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2). | What is the purpose of long, double, byte, char in Java? | [
"",
"java",
"variables",
"types",
"language-features",
""
] |
can someone give a scons config file which allows the following structure
```
toplevel/
/src - .cc files
/include .h files
```
at top level I want the o and final exe. | ```
env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:include',
CPPDEFINES=[],
LIBS=['glib-2.0'])
if ARGUMENTS.get('debug', 0):
env.Append(CCFLAGS = ' -g')
env.Program('template', Glob('src/*.cc'))
```
Worked a treat. Thanks. | Here is one example of Sconscript file
```
env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:inc',
CPPDEFINES=[],
LIBS=['glib-2.0'])
env.Program('runme', Glob('src/*.c'))
```
(The environment line is not really necessary for the example, but I have it to include the non standard glib header path and left it there so you can get the idea how to add extra includes and defines)
The source files are in src directory and header files in inc directory. You run scons from the base directory and the output file is also generated in the same directory. | scons : src and include dirs | [
"",
"python",
"scons",
""
] |
I'm putting some page content (which has been run through Tidy, but doesn't need to be if this is a source of problems) into `DOMDocument` using `DOMDocument::loadHTML`.
It's coming up with various errors:
> ID x already defined in Entity, line X
Is there any way to make either `DOMDocument` (or Tidy) ignore or strip out duplicate element IDs, so it will actually create the `DOMDocument`?
Thanks. :) | A quick search on the subject reveals this (incorrect) bug report:
<http://bugs.php.net/bug.php?id=46136>
The last reply states the following:
> You're using HTML 4 rules to load an
> XHTML document. Either use the load()
> method to parse as XML or the
> libxml\_use\_internal\_errors() function
> to ignore the warnings.
I can't be sure if you are encountering this problem for the same reasons, since you did not include a reference to the HTML page being loaded. In any case, using [`libxml_use_internal_errors()`](https://www.php.net/manual/en/function.libxml-use-internal-errors.php) should at least *suppress* the error.
ID's in HTML documents are [generally unique](http://www.w3.org/TR/html401/struct/global.html#adef-id), so the **best solution** would still be validating your document, if at all possible. | By definition, IDs are unique. If they are not, you should use classes instead (nor names, where it applies).
I doubt you can force XML tools to ignore duplicate IDs, that will make them handle an invalid XML document. | DOMDocument: Ignore Duplicate Element IDs | [
"",
"php",
"domdocument",
"tidy",
""
] |
Let say there is a table:
```
TableA:Field1, Field2, Field3
```
and associated JPA entity class
```
@Entity
@Table(name="TableA")
public class TableA{
@Id
@Column(name="Field1")
private Long id;
@Column(name="Field2")
private Long field2;
@Column(name="Field3")
private Long field3;
//... more associated getter and setter...
}
```
Is there any way to construct a JPQL statement that loosely translated to this SQL, ie how to translated the case expression to JPQL?
```
select field1,
case
when field2 = 1 then 'One'
when field2 = 2 then 'Two'
else 'Other number'
end,
field3
from tableA;
``` | It has been added in JPA 2.0
**Usage:**
```
SELECT e.name, CASE WHEN (e.salary >= 100000) THEN 1 WHEN (e.salary < 100000) THEN 2 ELSE 0 END FROM Employee e
```
**Ref:** <http://en.wikibooks.org/wiki/Java_Persistence/JPQL_BNF#New_in_JPA_2.0> | There is certainly such thing in Hibernate so when you use Hibernate as your JPA provider then you can write your query as in this example:
```
Query query = entityManager.createQuery("UPDATE MNPOperationPrintDocuments o SET o.fileDownloadCount = CASE WHEN o.fileDownloadCount IS NULL THEN 1 ELSE (o.fileDownloadCount + 1) END " +
" WHERE o IN (:operations)");
query.setParameter("operations", mnpOperationPrintDocumentsList);
int result = query.executeUpdate();
``` | Is there such thing CASE expression in JPQL? | [
"",
"java",
"oracle",
"orm",
"jpa",
""
] |
Hi I have following data in the table:
ID-----startDate----endDate
5549 2008-05-01 4712-12-31
**5567 2008-04-17 2008-04-30 1
5567 2008-05-01 2008-07-31 1
5567 2008-09-01 4712-12-31 2**
5569 2008-05-01 2008-08-31
5569 2008-09-01 4712-12-31
5589 2008-04-18 2008-04-30
5589 2008-05-01 4712-12-31
5667 2008-05-01 4712-12-31
5828 2008-06-03 4712-12-31
5867 2008-06-03 4712-12-31
6167 2008-11-01 4712-12-31
6207 2008-07-01 4712-12-31
6228 2008-07-01 4712-12-31
6267 2008-07-14 4712-12-31
I am looking for I way to group the continuous time intervals for each id to return:
ID,
min(startDate),
max(endDate),
to have something like this in result for the bolded ID 5567
5567 2008-04-17 2008-07-31
5567 2008-09-01 4712-12-31
PL/SQL is also an option here :)
Thanks, | I think this will do what you need:
(note that it will probably get confused by overlapping ranges; don't know if they're possible in your data set)
```
select id, min(start_date) period_start, max(end_date) period_end
from
(
select
id, start_date, end_date,
max(contig) over (partition by id order by end_date) contiguous_group
from
(
select
id, start_date, end_date,
case
when lag(end_date) over (partition by id order by end_date) != start_date-1 or row_number() over (partition by id order by end_date)=1
then row_number() over (partition by id order by end_date) else null end contig
from t2
)
)
group by id, contiguous_group
order by id, period_start
/
```
Here's the test data that I used - based on yours with a couple extra entries:
```
create table t2 (id number, start_date date, end_date date);
insert into t2(id, start_date, end_date)values(5549, to_date('2008-05-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5567, to_date('2008-04-17', 'yyyy-mm-dd'), to_date('2008-04-30', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5567, to_date('2008-05-01', 'yyyy-mm-dd'), to_date('2008-07-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5567, to_date('2008-08-01', 'yyyy-mm-dd'), to_date('2008-08-14', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5567, to_date('2009-09-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5567, to_date('2008-11-17', 'yyyy-mm-dd'), to_date('2008-12-13', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5567, to_date('2008-12-14', 'yyyy-mm-dd'), to_date('2008-12-24', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5569, to_date('2008-05-01', 'yyyy-mm-dd'), to_date('2008-08-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5569, to_date('2008-09-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5589, to_date('2008-04-18', 'yyyy-mm-dd'), to_date('2008-04-30', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5589, to_date('2008-05-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5667, to_date('2008-05-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5828, to_date('2008-06-03', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(5867, to_date('2008-06-03', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(6167, to_date('2008-11-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(6207, to_date('2008-07-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(6228, to_date('2008-07-01', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
insert into t2(id, start_date, end_date)values(6267, to_date('2008-07-14', 'yyyy-mm-dd'), to_date('4712-12-31', 'yyyy-mm-dd'));
commit;
``` | You could do this with analytic functions like this:
```
with d as
( select id, start_date, end_date
, case when start_date = prev_end+1
then 'cont' else 'new' end start_status
, case when end_date = next_start-1
then 'cont' else 'new' end end_stat
from
(
select id, start_date, end_date
, lag(end_date) over (partition by id order by start_date) prev_end
, lead(start_date) over (partition by id order by start_date) next_start
from t1
order by id, start_date
)
)
select starts.id, starts.start_date, ends.end_date
from
( select id, start_date, row_number() over (order by id, start_date) rn
from d
where start_status='new'
) starts,
( select id, end_date, row_number() over (order by id, start_date) rn
from d
where end_status='new'
) ends
where starts.rn = ends.rn
```
I get this result with your data:
```
ID START_DATE END_DATE
---------- ---------- ----------
5549 2008-05-01 4712-12-31
5567 2008-04-17 2008-07-31
5567 2008-09-01 4712-12-31
5569 2008-05-01 4712-12-31
5589 2008-04-18 4712-12-31
5667 2008-05-01 4712-12-31
5828 2008-06-03 4712-12-31
5867 2008-06-03 4712-12-31
6167 2008-11-01 4712-12-31
6207 2008-07-01 4712-12-31
6228 2008-07-01 4712-12-31
6267 2008-07-14 4712-12-31
12 rows selected.
```
How it works:
1. The WITH clause generates a view D of the data where each row is assigned a "start status" and an "end status", each of which is 'new' or 'cont' to indicate whether it is continuous with the previous/next row or not.
2. In-line views "starts" and "ends" pull out only the rows that have a "new" start status / end status respectively, with a row number to marry them up.
3. The "main query" then selects from these 2 views and joins on the row number column. | Grouping SQL results by continuous time intervals (oracle sql) | [
"",
"sql",
"oracle",
"date",
"continuous",
"intervals",
""
] |
I have the following RegEx
```
id=(.*?) | id="(.*?)"
```
The reason for this is I am trying to replace Ids from the browsers DOM using JavaScript. IE, however strips quotes from element atributes as it appears not to require them in the DOM
The problem I have is that the backrefererences from each alternate statement are in separate groups ($1 and $2) as the match is only one OR the other can I return both the backreference as a single backreference?
EDIT:
```
<div id="test1" /><div id=test2 />
```
will match as follows
```
match | $1 | $2
--------------------------------
id="test1" | test1 |
id=test2 | | test2
```
I just want both backreferences to be added to $1 | ```
id="?([\w-]*)"?
``` | what about:
```
id="?(.*?)"?
```
*(possibly that . should be [^"] - I didn't test it)* | Grouping Regular expression BackReferences | [
"",
"javascript",
"html",
"regex",
""
] |
I'm in the process of implementing a binary tree in C++. Traditionally, I'd have a pointer to left and a pointer to right, but manual memory management typically ends in tears. Which leads me to my question...
Are data structures an appropriate place to use shared\_ptr? | I think it depends on where you'd be using them. I'm assuming that what you're thinking of doing is something like this:
```
template <class T>
class BinaryTreeNode
{
//public interface ignored for this example
private:
shared_ptr<BinaryTreeNode<T> > left;
shared_ptr<BinaryTreeNode<T> > right;
T data;
}
```
This would make perfect sense *if* you're expecting your data structure to handle dynamically created nodes. However, since that's not the normal design, I think it's inappropriate.
My answer would be that no, it's not an appropriate place to use shared\_ptr, as the use of shared\_ptr implies that the object is actually shared - however, a node in a binary tree is *not* ever shared. However, as Martin York pointed out, why reinvent the wheel - there's already a smart pointer type that does what we're trying to do - auto\_ptr. So go with something like this:
```
template <class T>
class BinaryTreeNode
{
//public interface ignored for this example
private:
auto_ptr<BinaryTreeNode<T> > left;
auto_ptr<BinaryTreeNode<T> > right;
T data;
}
```
If anyone asks why data isn't a shared\_ptr, the answer is simple - if copies of the data are good for the *client* of the library, they pass in the data item, and the tree node makes a copy. If the *client* decides that copies are a bad idea, then the *client* code can pass in a shared\_ptr, which the tree node can safely copy. | Because left and right are not shared boost::shared\_ptr<> is probably not the correct smart pointer.
This would be a good place to try std::auto\_ptr<> | Are data structures an appropriate place for shared_ptr? | [
"",
"c++",
"data-structures",
"shared-ptr",
"tr1",
""
] |
I have a table with a binary column which stores files of a number of different possible filetypes (PDF, BMP, JPEG, WAV, MP3, DOC, MPEG, AVI etc.), but no columns that store either the name or the type of the original file. Is there any easy way for me to process these rows and determine the type of each file stored in the binary column? Preferably it would be a utility that only reads the file headers, so that I don't have to fully extract each file to determine its type.
**Clarification**: I know that the approach here involves reading just the beginning of each file. I'm looking for a good resource (aka links) that can do this for me without too much fuss. Thanks.
Also, **just C#/.NET on Windows, please**. I'm not using Linux and can't use Cygwin (doesn't work on Windows CE, among other reasons). | you can use these tools to find the file format.
File Analyser
<http://www.softpedia.com/get/Programming/Other-Programming-Files/File-Analyzer.shtml>
What Format
<http://www.jozy.nl/whatfmt.html>
PE file format analyser
<http://peid.has.it/>
This website may be helpful for you.
<http://mark0.net/onlinetrid.aspx>
Note:
i have included the download links to make sure that you are getting the right tool name and information.
please verify the source before you download them.
i have used a tool in the past i think it is File Analyser, which will tell you the closest match.
happy tooling. | This is not a complete answer, but a place to start would be a "magic numbers" library. This examines the first few bytes of a file to determine a "magic number", which is compared against a known list of them. This is (at least part) of how the `file` command on Linux systems works. | Is there an easy way to determine the type of a file without knowing the file's extension? | [
"",
"c#",
".net",
"windows",
"file-extension",
"file-type",
""
] |
The same as [this](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about) question but for java
**Update**
Based on the comments and responses of a few people, Its clear that Java has very little undefined behaviour.
So I'd like to ask as well what behaviour is not *obvious.* Please when answering make the distinction between the two :) | Anything to do with threads... :)
Also:
* Overriding methods and expecting them to be used in the same way between versions
* Assumptions about underlying platform (file separator, for instance)
* Details of garbage collection/finalisation
* Some details about class initialisation
* Whether Integer.valueOf (and the like) return the same objects
* Performance, latency and memory usage | There is very, very little undefined behavior in Java, when compared to C/C++, it is a much more well-defined platform. The reason for this is that C/C++ compilers are meant to produce code for very different platforms and therefore were granted rather wide freedoms in order to prevent too stringent requirements that would force a compiler to produce suboptimal code for a given platform.
Java sacrificed some of that by defining almost every behavior in a very exact way and allowing only small degrees of freedom. This of course makes the platform somewhat easier to handle.
The main area where undefined behavior happens is the exact timing and scheduling of multiple threads (as Tom Hawtin already mentioned)..
There are several places where the behavior is not obvious, 'though, so it might look undefined, but isn't (the String comparison examples given by Oscar Reyes are a great example).
And a few places where the behavior is defined to be undefined (for example the order of elements in a HashMap is defined to be implementation dependent and needs not be constant). | What are the common undefined behaviours that Java Programmers should know about | [
"",
"java",
"undefined",
""
] |
I have a simple piece of code:
```
public string GenerateRandomString()
{
string randomString = string.Empty;
Random r = new Random();
for (int i = 0; i < length; i++)
randomString += chars[r.Next(chars.Length)];
return randomString;
}
```
If i call this function to generate two strings, one after another, they are identical... but if i debug through the two lines where the strings are generated - the results are different.
does anyone know why is it happening? | This is happening, because the calls happen very close to each other (during the same milli-second), then the Random constructor will seed the Random object with the same value (it uses date & time by default).
So, there are two solutions, actually.
**1. Provide your own seed value**, that would be unique each time you construct the Random object.
**2. Always use the same Random object** - only construct it once.
Personally, I would use the second approach. It can be done by making the Random object static, or making it a member of the class. | The above answers are correct. I would suggest the following changes to your code though:
1) I would suggest using a StringBuilder instead of appending to the string all the time. Strings are immutable, so this is creating a new string each time you add to it. If you have never used StringBuilder, look it up. It is very useful for this sort of work.
2) You can make your method easier to reuse if you pass the length into the method itself. You could probably pass the chars array in as well, but I've left that out.
3) Use the same random object each time, as suggested above.
```
public string GenerateRandomString(int length)
{
StringBuilder randomString = new StringBuilder(length);
for (int i = 0; i < length; i++)
randomString.Append(chars[(int)(_RandomObj.Next(chars.Length))].ToString());
return randomString.ToString();
}
``` | random string generation - two generated one after another give same results | [
"",
"c#",
"string",
"random",
""
] |
Is there any method to generate MD5 hash of a string in Java? | You need [`java.security.MessageDigest`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html).
Call [`MessageDigest.getInstance("MD5")`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#getInstance(java.lang.String)) to get a MD5 instance of `MessageDigest` you can use.
The compute the hash by doing one of:
* Feed the entire input as a `byte[]` and calculate the hash in one operation with [`md.digest(bytes)`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#digest(byte%5B%5D)).
* Feed the `MessageDigest` one `byte[]` chunk at a time by calling [`md.update(bytes)`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#update(byte%5B%5D)). When you're done adding input bytes, calculate the hash with
[`md.digest()`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/MessageDigest.html#digest()).
The `byte[]` returned by `md.digest()` is the MD5 hash. | The `MessageDigest` class can provide you with an instance of the MD5 digest.
When working with strings and the crypto classes be sure to **always** specify the encoding you want the byte representation in. If you just use `string.getBytes()` it will use the platform default. (Not all platforms use the same defaults)
```
import java.security.*;
..
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] theMD5digest = md.digest(bytesOfMessage);
```
If you have a lot of data take a look at the `.update(xxx)` methods which can be called repeatedly. Then call `.digest()` to obtain the resulting hash. | How can I generate an MD5 hash in Java? | [
"",
"java",
"hash",
"md5",
"hashcode",
""
] |
I am inputting a 200mb file in my application and due to a very strange reason the memory usage of my application is more than 600mb. I have tried vector and deque, as well as std::string and char \* with no avail. I need the memory usage of my application to be almost the same as the file I am reading, any suggestions would be extremely helpful.
Is there a bug that causes so much memory consumption? Could you pinpoint the problem or should I rewrite the whole thing?
Windows Vista SP1 x64, Microsoft Visual Studio 2008 SP1, 32Bit Release Version, Intel CPU
The whole application until now:
```
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <time.h>
static unsigned int getFileSize (const char *filename)
{
std::ifstream fs;
fs.open (filename, std::ios::binary);
fs.seekg(0, std::ios::beg);
const std::ios::pos_type start_pos = fs.tellg();
fs.seekg(0, std::ios::end);
const std::ios::pos_type end_pos = fs.tellg();
const unsigned int ret_filesize (static_cast<unsigned int>(end_pos - start_pos));
fs.close();
return ret_filesize;
}
void str2Vec (std::string &str, std::vector<std::string> &vec)
{
int newlineLastIndex(0);
for (int loopVar01 = str.size(); loopVar01 > 0; loopVar01--)
{
if (str[loopVar01]=='\n')
{
newlineLastIndex = loopVar01;
break;
}
}
int remainder(str.size()-newlineLastIndex);
std::vector<int> indexVec;
indexVec.push_back(0);
for (unsigned int lpVar02 = 0; lpVar02 < (str.size()-remainder); lpVar02++)
{
if (str[lpVar02] == '\n')
{
indexVec.push_back(lpVar02);
}
}
int memSize(0);
for (int lpVar03 = 0; lpVar03 < (indexVec.size()-1); lpVar03++)
{
memSize = indexVec[(lpVar03+1)] - indexVec[lpVar03];
std::string tempStr (memSize,'0');
memcpy(&tempStr[0],&str[indexVec[lpVar03]],memSize);
vec.push_back(tempStr);
}
}
void readFile(const std::string &fileName, std::vector<std::string> &vec)
{
static unsigned int fileSize = getFileSize(fileName.c_str());
static std::ifstream fileStream;
fileStream.open (fileName.c_str(),std::ios::binary);
fileStream.clear();
fileStream.seekg (0, std::ios::beg);
const int chunks(1000);
int singleChunk(fileSize/chunks);
int remainder = fileSize - (singleChunk * chunks);
std::string fileStr (singleChunk, '0');
int fileIndex(0);
for (int lpVar01 = 0; lpVar01 < chunks; lpVar01++)
{
fileStream.read(&fileStr[0], singleChunk);
str2Vec(fileStr, vec);
}
std::string remainderStr(remainder, '0');
fileStream.read(&remainderStr[0], remainder);
str2Vec(fileStr, vec);
}
int main (int argc, char *argv[])
{
std::vector<std::string> vec;
std::string inFile(argv[1]);
readFile(inFile, vec);
}
``` | Your memory is being fragmented.
Try something like this :
```
HANDLE heaps[1025];
DWORD nheaps = GetProcessHeaps((sizeof(heaps) / sizeof(HANDLE)) - 1, heaps);
for (DWORD i = 0; i < nheaps; ++i)
{
ULONG HeapFragValue = 2;
HeapSetInformation(heaps[i],
HeapCompatibilityInformation,
&HeapFragValue,
sizeof(HeapFragValue));
}
``` | If I'm reading this right, the biggest issue is that this algorithm automatically doubles doubles the required memory.
In ReadFile(), you read the whole file into a set of 'singleChunk' sized strings (chunks), and then in the last loop in str2Vec() you allocate a tempstring for every newline separated segment of the chunk. So you're doubling the memory right there.
You've also got speed issues - str2vec does 2 passes over the chunk to find all the newlines. There's no reason you can't do that in one. | I think STL is causing my application triple its memory usage | [
"",
"c++",
"memory",
"memory-leaks",
"stl",
""
] |
I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.
For instance:
```
>>> c = "help, me"
>>> print c.split()
['help,', 'me']
```
What I really want the list to look like is:
```
['help', ',', 'me']
```
So, I want the string split at whitespace with the punctuation split from the words.
I've tried to parse the string first and then run the split:
```
>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
```
This produces the result I want, but is painfully slow on large files.
Is there a way to do this more efficiently? | This is more or less the way to do it:
```
>>> import re
>>> re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!")
['Hello', ',', "I'm", 'a', 'string', '!']
```
The trick is, not to think about where to split the string, but what to include in the tokens.
Caveats:
* The underscore (\_) is considered an inner-word character. Replace \w, if you don't want that.
* This will not work with (single) quotes in the string.
* Put any additional punctuation marks you want to use in the right half of the regular expression.
* Anything not explicitely mentioned in the re is silently dropped. | Here is a Unicode-aware version:
```
re.findall(r"\w+|[^\w\s]", text, re.UNICODE)
```
The first alternative catches sequences of word characters (as defined by unicode, so "résumé" won't turn into `['r', 'sum']`); the second catches individual non-word characters, ignoring whitespace.
Note that, unlike the top answer, this treats the single quote as separate punctuation (e.g. "I'm" -> `['I', "'", 'm']`). This appears to be standard in NLP, so I consider it a feature. | Splitting a string into words and punctuation | [
"",
"python",
"string",
"split",
""
] |
General tutorial or good resource on how to use threads in Python?
When to use threads, how they are effective, and some general background on threads [specific to Python]? | Threads should be used when you want two things to run at once, or want something to run in the background without slowing down the main process.
My recommendation is to only use threads if you have to. They generally add complexity to a program.
The main documentation for threading is here: <http://docs.python.org/library/threading.html>
Some examples are here:
<http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/>
<http://linuxgazette.net/107/pai.html>
<http://www.wellho.net/solutions/python-python-threads-a-first-example.html> | One thing to remember before spending time and effort in writing a multi-threaded Python application is that there is a [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock) (GIL), so you won't actually be running more than one thread at a time.
This makes threading unsuitable for trying to take advantage of multiple cores or CPUs. You may get some speedup from multiplexing other resources (network, disk, ...), but it's never been particularly noticeable in my experience.
In general, I only use threads when there are several logically separate tasks happening at once, and yet I want them all in the same VM. A thread pulling data from the web and putting it on a Queue, while another thread pops from the Queue and writes to a database, something like that.
With Python 2.6, there is the new `multiprocessing` module which is pretty cool - it's got a very similar interface to the `threading` module, but actually spawns new OS processes, sidestepping the GIL. | Threads in Python | [
"",
"python",
"multithreading",
""
] |
We've been having intermittent problems causing users to be forcibly logged out of out application.
Our set-up is ASP.Net/C# web application on Windows Server 2003 Standard Edition with SQL Server 2000 on the back end. We've recently performed a major product upgrade on our client's VMWare server (we have a guest instance dedicated to us) and whereas we had none of these issues with the previous release the added complexity that the new upgrade brings to the product has caused a lot of issues. We are also running SQL Server 2000 (build 8.00.2039, or SP4) and the IIS/ASP.NET (.Net v2.0.50727) application on the same box and connecting to each other via a TCP/IP connection.
---
Primarily, the exceptions being thrown are:
> System.IndexOutOfRangeException: Cannot find table 0.
>
> System.ArgumentException: Column 'password' does not belong to table Table.
[This exception occurs in the log in script, even though there is clearly a password column available]
> System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
[This one is occurring very regularly]
> System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable.
>
> System.ApplicationException: ExecuteReader requires an open and available Connection. The connection's current state is connecting.
>
> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
And just today, for the first time:
> System.Web.UI.ViewStateException: Invalid viewstate.
---
We have load tested the app using the same number of concurrent users as the production server and cannot reproduce these errors. They are very intermittent and occur even when there are only 8/9/10 user connections. My gut is telling me its ASP.NET - SQL Server 2000 connection issues..
We've pretty much ruled out code-level Data Access Layer errors at this stage (we've a development team of 15 experienced developers working on this) so we think its a specific production server environment issue. | Lads, just as an update, it turned out that the problem was VMWare related under heavy usage - what a fun week! We're changing the code around to suit the VMWare environment and we've seen some improvement already.
Thanks for the suggestions, I appreciate it. | The Invalid Viewstate error is pretty common in a high traffic web site. Though, if you recently moved to multiple web servers, make sure you're sharing the same machine key so Viewstate is signed with the same key on all servers. <http://www.codinghorror.com/blog/archives/000132.html>
Based on the other errors I'd guess that you are using shared connections across multiple threads. Are your connections stored in static variables, Application state, Session state, or other object that's used across multiple requests? Maybe there's a hashtable somewhere containing connections, commands, or transactions. None of the ADO.Net objects are thread safe. So, make sure you only use them in a single threaded fashion.
Another possibility is you're passing around the ADO.NET objects and not consistently disposing of them and managing their scope. Maybe they're cached in the request context or some such? | SQL Server 2000 intermittent connection exceptions on production server - specific environment problem? | [
"",
"c#",
"asp.net",
"sql-server-2000",
"windows-server-2003",
""
] |
Would you mix MFC with STL? Why? | Sure. Why not?
I use MFC as the presentation layer, even though the structures and classes in the back-end use STL. | Use STL whenever you can, use MFC when no alternative | Mixing MFC and STL | [
"",
"c++",
"mfc",
"stl",
""
] |
I often make a collection field unmodifiable before returning it from a getter method:
```
private List<X> _xs;
....
List<X> getXs(){
return Collections.unmodifiableList(_xs);
}
```
But I can't think of a convenient way of doing that if the X above is itself a List:
```
private List<List<Y>> _yLists;
.....
List<List<Y>> getYLists() {
return Collections.unmodifiableList(_yLists);
}
```
The problem in the above is of course that though the client cannot modify the List of lists, it can add/delete Y objects from the embedded lists.
Any thoughts? | The best I could come up with uses [ForwardingList from Google Collections](http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html). Comments are welcome.
```
private static <T> List<List<T>> unmodifiableList2(final List<List<T>> input) {
return Collections.unmodifiableList(new ForwardingList<List<T>>() {
@Override protected List<List<T>> delegate() {
return Collections.unmodifiableList(input);
}
@Override public List<T> get(int index) {
return Collections.unmodifiableList(delegate().get(index));
}
});
}
``` | unfortunately, there is no easy way to get deep const-ness in java. you would have to hack around it by always making sure that the list inside the list is also unmodifiable.
i'd be interested too to know any elegant solution. | How to create a deep unmodifiable collection? | [
"",
"java",
"unmodifiable",
""
] |
I'm trying to "force" Safari or IE7 to open a new page *using a new tab*.
Programmatically I mean something like:
```
window.open('page.html','newtaborsomething');
``` | You can't directly control this, because it's an option controlled by Internet Explorer users.
Opening pages using Window.open with a different window name will open in a new browser window like a popup, *OR* open in a new tab, if the user configured the browser to do so. | You can, in Firefox it works, add the attribute target="\_newtab" to the anchor to force the opening of a new tab.
```
<a href="some url" target="_newtab">content of the anchor</a>
```
In javascript you can use
```
window.open('page.html','_newtab');
```
Said that, I partially agree with Sam. You shouldn't force user to open new pages or new tab without showing them a hint on what is going to happen **before** they click on the link.
Let me know if it works on other browser too (I don't have a chance to try it on other browser than Firefox at the moment).
Edit: added reference for ie7
Maybe this link can be useful
<http://social.msdn.microsoft.com/forums/en-US/ieextensiondevelopment/thread/951b04e4-db0d-4789-ac51-82599dc60405/> | Programmatically open new pages on Tabs | [
"",
"javascript",
"internet-explorer-7",
"safari",
"tabs",
""
] |
Is there some smart way to retreive the installation path when working within a dll (C#) which will be called from an application in a different folder?
I'm developing an add-in for an application. My add-in is written in C#. The application that will use is written in C and needs to compile some stuff during evaluation, so I have a middlestep with a C++ dll that handles the interop business with C# and only shows a clean interface outward that C can work with.
What I deploy will be a set of .dll's and a .lib and .h for the C++ part (sometimes static binding will be necessary).
When trying out the setup and printing out the current directory info from the C# dll with:
```
Console.WriteLine(Directory.GetCurrentDirectory());
```
or:
```
Console.WriteLine(System.Environment.CurrentDirectory);
```
I get the executables path.
So ... once again, how do I get the installation path of my dll?
Edit: They both worked! Thanks for the quick reply guys! | I think what you want is `Assembly.GetExecutingAssembly().Location`. | One of these two ways:
```
using System.IO;
using System.Windows.Forms;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
```
Or:
```
using System.IO;
using System.Reflection;
string path = Path.GetDirectoryName(
Assembly.GetAssembly(typeof(MyClass)).CodeBase);
``` | How to get the installation directory in C# after deploying dll's | [
"",
"c#",
"deployment",
"interop",
""
] |
I was wondering how to check whether a variable is a class (not an instance!) or not.
I've tried to use the function `isinstance(object, class_or_type_or_tuple)` to do this, but I don't know what type a class would have.
For example, in the following code
```
class Foo:
pass
isinstance(Foo, **???**) # i want to make this return True.
```
I tried to substitute "`class`" with **???**, but I realized that `class` is a keyword in python. | Even better: use the [`inspect.isclass`](https://docs.python.org/library/inspect.html#inspect.isclass) function.
```
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> inspect.isclass(x)
False
``` | ```
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
``` | How to check whether a variable is a class or not? | [
"",
"python",
"oop",
""
] |
When I'm naming array-type variables, I often am confronted with a dilemma:
Do I name my array using plural or singular?
For example, let's say I have an array of names: In PHP I would say: `$names=array("Alice","Bobby","Charles");`
However, then lets say I want to reference a name in this array. For Bobby, I'd say: `$names[1]`. However, this seams counter-intuitive. I'd rather call Bobby `$name[1]`, because Bobby is only one name.
So, you can see a slight discrepancy. Are there conventions for naming arrays? | I use the plural form. Then I can do something like:
```
$name = $names[1];
``` | Name should always convey as much information as possible in case a reader is not familiar with the type declaration. An array or collection should therefore be named in the plural.
I personally find $name[1] to be misleading, since it means "the 1st element of name" which doesn't make English sense. | Do you name your arrays using plural or singular in PHP? | [
"",
"php",
"arrays",
"naming-conventions",
""
] |
I'm having some problems with a datagridview element I'm using in VS2008.
This DataGridView is actually a tab in a TabControl element.
I gave it 5 colums which need to be filled up with elements from a costum Object i made.
It's basically a small library application which contains a main class and several classed derived from it. They all have a ToString() method which represents the data as a string of keywords containing the values needed for me to fill up the datagridview.
I only need the first 5 though, some objects will have up to 12 keywords.
Currently, Whenever I add an object, the datagrid doesn't fill itself, instead it adds an amount of columns equall to the amount of keywords the specific object has.
What i'm currently doing is this:
```
public void libDataGrid_Click(object sender, EventArgs e)
{
if(this.manager.Lib.LibList[0] != null)
{
libDataGrid.DataSource = this.manager.Lib.LibList;
libDataGrid.Refresh();
}
}
```
`this.manager.Lib.LibList` returns and ArrayList, in which all objects are stored. The ArrayList can contain elements of all derived classes, but since they are all connected, the string representation will always contain the elements I need to fill up the grid.
I don't see how I can filter only the first five and them have them put in the correct colums.
And another thing. Currently I can only refresh the DataGridView by clicking it. It should change on when I switch to it switch to its specific tab on the Tabcontrol I mean.
I tried adding an argument for SelectedIndexChanged, but that does nothing really...
Or at least, it doesn't appear to do anything.
What I mean is I commented out the code above and added this instead:
```
public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
libDataGrid.DataSource = this.manager.Lib.LibList;
libDataGrid.Refresh();
}
```
This refreshes it everytime the tab is changed, no matter to which one.
I had to remove the if-statement, since it gave me an Exception. Probably because the length of the ArrayList isn't set on initialisation. | I'm a little confused by the question, but here are some thoughts:
1. `DataGridView` has an [`AutoGenerateColumn`s](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns.aspx) property; if you don't want it to create its own columns, set this to false
2. To bind to existing columns, the [`DataPropertyName`](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspx) must be set on each
3. `DataGridView` (in cmomon with any list control using `TypeDescriptor`) will hugely prefer `List<T>` (for some `T` != `object`) to `ArrayList`, since it can get meta-data even for an empty list. In general, in 2.0 using `ArrayList` is a mistake. | I can only give a partial answer but I think the reason that
```
public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
libDataGrid.DataSource = this.manager.Lib.LibList;
libDataGrid.Refresh();
}
```
isn't working, is because you need to add this line where tabControl1 is being initialized. I've had this problem where VS won't do this itself.
```
tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);
``` | Controlling C# DataGridView with an Arraylist in VS2008 | [
"",
"c#",
"winforms",
"visual-studio-2008",
"datagridview",
"tabcontrol",
""
] |
In JavaScript nested functions are very useful: closures, private methods and what have you..
What are nested PHP functions for? Does anyone use them and what for?
Here's a small investigation I did
```
<?php
function outer( $msg ) {
function inner( $msg ) {
echo 'inner: '.$msg.' ';
}
echo 'outer: '.$msg.' ';
inner( $msg );
}
inner( 'test1' ); // Fatal error: Call to undefined function inner()
outer( 'test2' ); // outer: test2 inner: test2
inner( 'test3' ); // inner: test3
outer( 'test4' ); // Fatal error: Cannot redeclare inner()
``` | There is none basically. I've always treated this as a side effect of the parser.
Eran Galperin is mistaken in thinking that these functions are somehow private. They are simply undeclared until `outer()` is run. They are also not privately scoped; they do pollute the global scope, albeit delayed. And as a callback, the outer callback could still only be called once. I still don't see how it's helpful to apply it on an array, which very likely calls the alias more than once.
The only 'real world' example I could dig up is [this](http://www.java2s.com/Code/Php/Functions/Nestedfunction.htm), which can only run once, and could be rewritten cleaner, IMO.
The only use I can think of, is for modules to call a `[name]_include` method, which sets several nested methods in the global space, combined with
```
if (!function_exists ('somefunc')) {
function somefunc() { }
}
```
checks.
PHP's OOP would obviously be a better choice :) | If you are using PHP 5.3 you can get more JavaScript-like behaviour with an anonymous function:
```
<?php
function outer() {
$inner=function() {
echo "test\n";
};
$inner();
}
outer();
outer();
inner(); //PHP Fatal error: Call to undefined function inner()
$inner(); //PHP Fatal error: Function name must be a string
?>
```
Output:
```
test
test
``` | What are PHP nested functions for? | [
"",
"php",
"nested-function",
""
] |
How do I call the correct overloaded function given a reference to an object based on the actual type of the object. For example...
```
class Test
{
object o1 = new object();
object o2 = new string("ABCD");
MyToString(o1);
MyToString(o2);//I want this to call the second overloaded function
void MyToString(object o)
{
Console.WriteLine("MyToString(object) called.");
}
void MyToString(string str)
{
Console.WriteLine("MyToString(string) called.");
}
}
```
what I mean is there a better option than the following?
```
if(typeof(o) == typeof(string))
{
MyToString((string)o);
}
else
{
MyToString(o);
}
```
May be this can be done using reflection? | Ok as soon as I hit post I remembered this can indeed be done using reflection...
```
var methInfo = typeof(Test).GetMethod("MyToString", new Type[] {o.GetType()});
methInfo.Invoke(this, new object[] {o});
``` | You could just use ternary operators to code this using a single clean line of code:
```
MyToString(o is string ? (string)o : o);
``` | How to call the correct overloaded function at runtime? | [
"",
"c#",
"reflection",
""
] |
Let's say I'm generating markup through server-side code. I'm generating a bunch of HTML tags but I want to add custom client-side behavior.
With JavaScript (if I had a reference to the DOM node) I could have written:
```
var myDOMNode = ...
myDOMNode.myCustomAttribute = "Hi!";
```
Now the issue here is that I don't want to qualify every element with an unique id just to initialize data. And it's really strange to me, that there's not an easier and unobtrusive way to attach client-side behavior.
If I'm remembing this correctly, this is valid IE stuff.
```
<div onload="this.myCustomAttribute='Hi!'"></div>
```
If I was able to do this, I should be able to access it's "data context" though the identifier 'myCustomAttribute', which is really what I want. | I do appricate the input but I've finally figured this out and it's the way I go about *initialization* that has been the thorn in my side.
What you never wan't do is to pollute your global namespace with a bunch of short lived identifiers. Any time you put `id=""` on an element you're doing exactly that (same thing for any top level function). By relying on jQuery, HTML5 data and CSS there's a solution to my problem which I think is quite elegant.
What I do is that I reserve a CSS class for a specific behavior and then use HTML5 data to parameterize the behavior. When the document is ready, I query the document (using Query) for the CSS class that represents the behavior and initialize the client-side behavior.
I've been doing a lot of ASP.NET and within this context both the `id=""` and `name=""` belongs to ASP.NET and is pretty useless for anything else than internal ASP.NET stuff. What you typically find yourself doing is to get at a server-side property called `ClientID` you can refer to this from client-side JavaScript, it's a lot of hassle. They made it easier in 4.0 but fundamentally I think it's pretty much broken.
Using this hybrid of CSS, HTML5 data and jQuery solves this problem altogether. Here's an example of an attached behavior that uses regular expressions to validate the input of a textbox.
```
<input type="text" class="-input-regex" data-regex="^[a-z]+$" />
```
And here's the script:
```
$(function () {
function checkRegex(inp) {
if (inp.data("regex").test(inp.val()))
inp.data("good-value", inp.val());
else
inp.val(inp.data("good-value"));
}
$(".-input-regex")
.each(function () {
// starting with jQuery 1.5
// you can get at HTML5 data like this
var inp = $(this);
var pattern = inp.data("regex");
inp.data("regex", new RegExp(pattern));
checkRegex(inp);
})
.keyup(function (e) {
checkRegex($(this));
})
.change(function (e) {
checkRegex($(this));
})
.bind("paste", undefined, function (e) {
checkRegex($(this));
})
;
});
```
Totally clean, no funky `id=""` or obtrusive dependency. | The following will work but not validate:
```
<div myattribute="myvalue"></div>
```
But if you are injecting it into the HTML with Javascript, then perhaps that's not concern for you. Otherwise, you can use something like jQuery to process the elements before adding them to the DOM:
```
$(elements).each(function(){
$(this).attr('myattribute','myvalue');
});
``` | Setting properties on anonymous DOM elements through JavaScript? | [
"",
"javascript",
"dom",
""
] |
The following is okay:
```
try
{
Console.WriteLine("Before");
yield return 1;
Console.WriteLine("After");
}
finally
{
Console.WriteLine("Done");
}
```
The `finally` block runs when the whole thing has finished executing (`IEnumerator<T>` supports `IDisposable` to provide a way to ensure this even when the enumeration is abandoned before it finishes).
But this is not okay:
```
try
{
Console.WriteLine("Before");
yield return 1; // error CS1626: Cannot yield a value in the body of a try block with a catch clause
Console.WriteLine("After");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
```
Suppose (for the sake of argument) that an exception is thrown by one or other of the `WriteLine` calls inside the try block. What's the problem with continuing the execution in `catch` block?
Of course, the yield return part is (currently) unable to throw anything, but why should that stop us from having an enclosing `try`/`catch` to deal with exceptions thrown before or after a `yield return`?
**Update:** There's an [interesting comment from Eric Lippert here](https://web.archive.org/web/20080818052536/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx) - seems that they already have enough problems implementing the try/finally behaviour correctly!
EDIT: The MSDN page on this error is: <http://msdn.microsoft.com/en-us/library/cs1x15az.aspx>. It doesn't explain why, though. | I suspect this is a matter of practicality rather than feasibility. I suspect there are very, very few times where this restriction is *actually* an issue that can't be worked around - but the added complexity in the compiler would be very significant.
There are a few things like this that I've already encountered:
* Attributes not being able to be generic
* Inability for X to derive from X.Y (a nested class in X)
* Iterator blocks using public fields in the generated classes
In each of these cases it would be possible to gain a little bit more freedom, at the cost of extra complexity in the compiler. The team made the pragmatic choice, for which I applaud them - I'd rather have a slightly more restrictive language with a 99.9% accurate compiler (yes, there are bugs; I ran into one on SO just the other day) than a more flexible language which couldn't compile correctly.
EDIT: Here's a pseudo-proof of how it why it's feasible.
Consider that:
* You can make sure that the yield return part itself doesn't throw an exception (precalculate the value, and then you're just setting a field and returning "true")
* You're allowed try/catch which doesn't use yield return in an iterator block.
* All local variables in the iterator block are instance variables in the generated type, so you can freely move code to new methods
Now transform:
```
try
{
Console.WriteLine("a");
yield return 10;
Console.WriteLine("b");
}
catch (Something e)
{
Console.WriteLine("Catch block");
}
Console.WriteLine("Post");
```
into (sort of pseudo-code):
```
case just_before_try_state:
try
{
Console.WriteLine("a");
}
catch (Something e)
{
CatchBlock();
goto case post;
}
__current = 10;
return true;
case just_after_yield_return:
try
{
Console.WriteLine("b");
}
catch (Something e)
{
CatchBlock();
}
goto case post;
case post;
Console.WriteLine("Post");
void CatchBlock()
{
Console.WriteLine("Catch block");
}
```
The only duplication is in setting up try/catch blocks - but that's something the compiler can certainly do.
I may well have missed something here - if so, please let me know! | All the `yield` statements in an iterator definition are converted to a state in a state machine which effectively uses a `switch` statement to advance states. If it *did* generate code for `yield` statements in a try/catch it would have to duplicate *everything* in the `try` block for *each* `yield` statement while excluding every other `yield` statement for that block. This isn't always possible, particularly if one `yield` statement is dependant on an earlier one. | Why can't yield return appear inside a try block with a catch? | [
"",
"c#",
"exception",
"yield",
""
] |
I have a dataview defined as:
```
DataView dvPricing = historicalPricing.GetAuctionData().DefaultView;
```
This is what I have tried, but it returns the name, not the value in the column:
```
dvPricing.ToTable().Columns["GrossPerPop"].ToString();
``` | You need to specify the row for which you want to get the value. I would probably be more along the lines of table.Rows[index]["GrossPerPop"].ToString() | You need to use a `DataRow` to get a value; values exist in the data, not the column headers. In LINQ, there is an extension method that might help:
```
string val = table.Rows[rowIndex].Field<string>("GrossPerPop");
```
or without LINQ:
```
string val = (string)table.Rows[rowIndex]["GrossPerPop"];
```
(assuming the data **is** a string... if not, use `ToString()`)
If you have a `DataView` rather than a `DataTable`, then the same works with a `DataRowView`:
```
string val = (string)view[rowIndex]["GrossPerPop"];
``` | How to get a value from a column in a DataView? | [
"",
"c#",
"asp.net",
"dataview",
""
] |
We're currently developing a new piece of hand-held software. I cant discuss the nature of the application, so I'll use an example instead.
We're designing hand-held software for managing a school. We want to modularise each aspect of the system so that different schools can use different features.
Our system will start with a main menu and a login screen. I'd like this to be the base of the system and be where the modules will be added to. I.e. I'll have a project called SchoolPda.
I then want to have different modules. I.e., I want a registration module that will handle student registrations. I want a classroom module for managing classroom cleanliness, etc.
The way I'd possibly see this working is including/not including different dlls and having the base system's main menu expose buttons to access those modules if the dlls exist. That's just the kind of thing we're after.
Does anyone have any experience doing something like this? What would be the best way of doing it? We don't need to worry about the database as the database will always be the full database, but aspects wont get populated if the associated modules do not exist. | I have been in projects that have done it two ways:
* In one project we did not deploy certain DLLs if the customers weren't licensed. That's what you are suggesting. It worked fine. Of course, there was no way to enable those modules without an additional install, but it made perfect sense for that app.
* In another project we deployed everything and only exposed to the end-users the menus, buttons, etc. for which the customer was licensed. We did that because then the user could easily add-on an extra module by adding a license for it. When the license was added, the stuff magically showed up on next login.
So in my experience, I would say look at your licensing model as one big piece of your decision. Think about whether you would ever want to add those extra modules on the fly. | I am currently also developing a application that runs on both Compact and Full framework and is built modular.
The way I implemented it is that it scans a location for dll's and enummerates over each type and looks if they have a "ScreenInfoAttribute" or "WidgetInfoAttribute" defined which contains usefull information about the class.
here's a snippet, it contains 3.5 code, but that's because we recently made the switch from 2.0, but the principle works in 2.0
```
public void Analyze(FileInfo file) {
Assembly asm = Assembly.LoadFrom(file.FullName);
List<Data.AnyPlugin> types = GetPluginTypes(asm.GetTypes());
if (types.Count > 0) {
types.ForEach(x => x.AssemblyPath = file.FullName);
if (_plugins.ContainsKey(file.FullName)) {
_plugins[file.FullName].Plugins.AddRange(types);
} else {
AssemblyPlugin asp = new AssemblyPlugin();
asp.Ass = asm;
asp.Plugins = types;
_plugins.Add(file.FullName, asp);
}
}
}
private List<Data.AnyPlugin> GetPluginTypes(Type[] types) {
List<Data.AnyPlugin> returnTypes = new List<AnyPlugin>();
foreach (Type t in types) {
Data.AnyPlugin st = GetPluginType(t);
if (st != null) returnTypes.Add(st);
}
return returnTypes;
}
private Data.AnyPlugin GetPluginType(Type type) {
if (type.IsSubclassOf(typeof(Screens.bScreen<T>))) {
Screens.ScreenInfoAttribute s = GetScreenAttrib(type);
if (s != null) {
return new Data.ScreenPlugin("", type, s);
}
} else if (type.IsSubclassOf(typeof(Widgets.bWidget<T>))) {
Widgets.WidgetInfoAttribute w = GetWidgetAttrib(type);
if (w != null) return new Data.WidgetPlugin("", type, w);
}
return null;
}
private Screens.ScreenInfoAttribute GetScreenAttrib(Type t) {
Attribute a = Attribute.GetCustomAttribute(t, typeof(Screens.ScreenInfoAttribute));
return (Screens.ScreenInfoAttribute)a;
}
``` | Modularising a C# Compact Framework 2.0 Application | [
"",
"c#",
".net",
"module",
"compact-framework",
"modularization",
""
] |
I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):
```
import os
sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"'
server = 'myLocalServer'
database = 'myLocalDatabase'
connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true']
connection_string = ';'.join(connection_values)
dbms_version = '2000'
sqlscript_filename = 'CreateSchema.sql'
args = [
sqlpubwiz,
'script',
'-C ' + connection_string,
sqlscript_filename,
'-schemaonly',
'-targetserver ' + dbms_version,
'-f',
]
cmd = ' '.join(args)
os.system(cmd)
```
This code runs properly but I have would like to get into the habit of using [subprocess](http://docs.python.org/library/subprocess) since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly.
How would the above code look like if it was converted to use subprocess in place of os.system? | ```
import subprocess
p=subprocess.Popen(args, stdout=subprocess.PIPE)
print p.communicate()[0]
```
It would look pretty much the same. But the path should not be r'"whatever the path is"'. Because that gives me an error. You want "the path with escaped backslashes" or r'the path without escaping'.
Also args should be of the form ['-arg', 'args'] instead of ['arg argsval']. | Remove quotes from the name of the executable. On the first line of your example, instead of
```
sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"'
```
use:
```
sqlpubwiz = r'C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe'
```
That's because you don't have to escape anything since a shell won't be involved.
Then just use `subprocess.call(args)` (don't `join` the args, pass them as a list)
If you want to capture the output (`os.system` can't do it) just follow [subprocess](http://docs.python.org/library/subprocess.html) documentation:
```
result = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
print result
``` | In Python, how I do use subprocess instead of os.system? | [
"",
"python",
"syntax",
"scripting",
"process",
""
] |
I am creating a GUI frontend for the Eve Online API in Python.
I have successfully pulled the XML data from their server.
I am trying to grab the value from a node called "name":
```
from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
```
This seems to find the node, but the output is below:
```
[<DOM Element: name at 0x11e6d28>]
```
How could I get it to print the value of the node? | It should just be
```
name[0].firstChild.nodeValue
``` | Probably something like this if it's the text part you want...
```
from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)
```
The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.
```
<name>
blabla
<somestuff>asdf</somestuff>
znylpx
</name>
```
You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing. | Get Element value with minidom with Python | [
"",
"python",
"dom",
"minidom",
""
] |
I have this simple Jsp page:
```
<%@ page language="java" import="java.awt.Color"%> <%
Color background = Color.white;
%>
```
Which fails with following error:
```
java.lang.NoClassDefFoundError
at _text__jsp._jspService(/text.jsp:3)
at com.caucho.jsp.JavaPage.service(JavaPage.java:75)
at com.caucho.jsp.Page.subservice(Page.java:506)
at com.caucho.server.http.FilterChainPage.doFilter(FilterChainPage.java:182)
at com.caucho.server.http.Invocation.service(Invocation.java:315)
at com.caucho.server.http.CacheInvocation.service(CacheInvocation.java:135)
at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:346)
at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:274)
at com.caucho.server.TcpConnection.run(TcpConnection.java:139)
at java.lang.Thread.run(Thread.java:534)
```
I'm running it on Resin 2.1.13.
Any idea what's causing this? | Not sure about the issue. I can run your code successfully in my Tomcat. May be this problem is particular to Resin. Or, as said by Dave, may be a headless issue.
Your best bet is to convert the image in some POJO and then spit that to the browser, or may be save it somewhere on the disk and then link it in your JSP. If problem persists, try running in headless mode, as Dave pointed out.
Moreover, its important to understand that JSP is a view technology for the web, and must not do that kind of graphics manipulation. | In the past I've used AWT classes inside servlet containers. The issue that needs to be dealt with is that, on a server system, there is probably no graphics display running that AWT can connect to, which by default causes it to fail.
The solution is to pass a system property that tells AWT it is running on a "headless" system. In general this is done by passing "-Djava.awt.headless=true" to the java command line.
Here's a reference regarding accomplishing this for Resin: <http://www.caucho.com/support/resin-interest/0209/0062.html>. The OP in that thread also reported a NoClassDefFound error. | java.awt.Color error | [
"",
"java",
"jsp",
"resin",
""
] |
How can I put a link in a C# `TextBox`? I have tried to put HTML tags in the box but instead of showing a link it shows the entire HTML tag. Can this be done with a `TextBox`? | I would think about this a little bit. If you allow executable code in an editable control, the user, the user can execute **ANY** code. This is generally a bad idea.
The behavior of the C# control is intentional to prevent the exact behavior that you are trying to create. A little creativity (such as parsing out links from the text box and creating a list of links next or below the text box) will provide a much safer application. | Use the [RichTextBox](http://msdn.microsoft.com/en-us/library/f591a55w.aspx), no need to build your own, it cames with VS | How do I add HTML links in C# TextBox? | [
"",
"c#",
"html",
"textbox",
"hyperlink",
""
] |
I've posted this [here](https://stackoverflow.com/questions/155739/detecting-unsaved-changes-using-javascript#317246), but thought it might deserve a question on its own.
What I'm trying to do is show a dialog box that asks the user if he/she wants to leave the page if there are unsaved changes. That all works fine. But the problem is described below:
Has anyone come across the problem where Internet Explorer fires the onbeforeunload event twice? While Googling around, I found it has something to do with the fact that for (among others) an ASP.NET linkbutton the HTML code is `<a href="javascript: __doPostBack...`.
Apparently, when IE encouters a link that doesn't have a `href="#"`, it fires the onbeforeunload event. Then, when you confirm the javascript dialog box we're showing, the page will do the 'real' unload to navigate to the other page, and raise the onbeforeunload event a second time.
A solution offered on the internet is to set a boolean variable and check on it before showing the dialog. So the second time, it wouldn't be shown. That's all well, but when the user cancels, the variable will still be set. So the next time the user wants to leave the page, the dialog won't be shown anymore.
Hope this is a little clear, and I hope someone has found a way around this? | In reaction to annakata: Yes, but you want the result of the dialog box to be used by the browser. So you might think using 'return bFlag' would do the trick (or event.returnValue = bFlag), but that gives you a second dialog box.
I've found a way around, thanks to [this page](http://www.codeproject.com/KB/aspnet/EWSWebPt2.aspx). It's quite simple actually:
```
var onBeforeUnloadFired = false;
```
Use this global variable here:
```
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You'll lose changes!";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 1000);
```
And then implement that function:
```
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
```
So, in effect, use the flag, but reset it if the user clicks cancel. Not entirely what I would like, but haven't found anything better. | I haven't encountered this, but surely you could set the flag variable to be equal to the result of the dialog? If the user cancels the flag will therefore remain false.
```
var bFlag = window.confirm('Do you want to leave this page?');
``` | ASP.NET linkbutton raising onBeforeUnload event twice | [
"",
"asp.net",
"javascript",
""
] |
How can you make the ASP.net Session Data available to a JavaScript method? I found [this](http://blogs.msdn.com/mattgi/archive/2006/11/15/accessing-session-data-from-javascript.aspx) link when I googled. Anyone has a better trick that does not use the ScriptManager? | If ditching the ScriptManager is your aim, exposing the page method is still a good option, just use javascript that doesn't rely on the ScriptManager js libraries.
I like the solution proposed in the linked page, but it might be a too wide open though. Maybe you want to create a strongly typed and controlled PageMethod for any/all Session items that you want to allow access to. That way you can't access some secret Session value accidentally.
Also, I think you need to tag the PageMethod with
VB
```
WebMethod(EnableSession:=True)
```
C#
```
WebMethod(true)
```
as I don't think EnableSession is on by default. | The purpose of session is to hide details from the client. Sounds to me like you should convert it over to using cookies which is obviously trivial to retrieve via javascript. | What is the best way to access ASP.net Session Data using JavaScript? | [
"",
"asp.net",
"javascript",
"session",
""
] |
I have two process and a shared memory zone, my workflow is like this. The process A write some data in the shared memory, after that it should wait and send a signal to other process B to start running. The process B should read some data from the shared memory do some stuff write the result, and send a signal to the process A to keep running, after this process B should wait.
Can anyone plese provide an example or a place where I can find how can I stop a process and how can I start running again the process?. I am working in Linux and C++.
I already have semaphores, but the thing that I do not like, it is that one process is stop a bunch of seconds reading all the time from the shared memory, until it detects that it can run. That's why I was thinkin only in send a signal in the right moment
**Update with the solution**
I selected the answer of stefan.ciobaca as favourite because is a complete solution that it works and it has a very good explanation. But in all of the other answers there are other interesting options. | Here is a proof-of-concept of how it can be done:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <assert.h>
typedef void (*sighandler_t)(int);
#define SHM_SIZE 8 /* size of shared memory: enough for two 32 bit integers */
volatile int cancontinue = 0;
void halt(char *err) { perror(err); exit(1); }
void handler(int signum) { assert(signum == SIGUSR1); cancontinue = 1; }
int main(void)
{
key_t key;
int id;
int *data;
pid_t otherpid;
printf("Hi, I am the %s process and my pid is %d\n",
#ifdef PRODUCER_MODE
"writer"
#else
"reader"
#endif
, getpid());
printf("Please give me the pid of the other process: ");
scanf("%d", &otherpid);
// get a pointer to the shared memory
if ((key = ftok("test_concur.c", 'R')) == -1) halt("ftok");
if ((id = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) halt("shmget");
if ((data = shmat(id, (void *)0, 0)) == (int *)(-1)) halt("shmat");
sighandler_t oldhandler = signal(SIGUSR1, handler);
while (1) {
#ifdef PRODUCER_MODE
printf("Enter two integers: ");
scanf("%d %d", data, data + 1);
printf("Sending signal to consumer process\n");
kill(otherpid, SIGUSR1);
printf("Waiting for consumer to allow me to continue\n");
while (!cancontinue);
cancontinue = 0;
if (*data + *(data + 1) == 0) { printf("Sum was 0, exiting...\n"); break; }
#else
printf("Waiting for producer to signal me to do my work\n");
while (!cancontinue);
cancontinue = 0;
printf("Received signal\n");
printf("Pretending to do a long calculation\n");
sleep(1);
int sum = *data + *(data + 1);
printf("The sum of the ints in the shared memory is %d\n", sum);
printf("Signaling producer I'm done\n");
kill(otherpid, SIGUSR1);
if (sum == 0) break;
#endif
}
signal(SIGUSR1, oldhandler);
/* detach from the segment: */
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
// don't forget to remove the shared segment from the command line with
// #sudo ipcs
// ... and look for the key of the shared memory segment
// #ipcrm -m <key>
return 0;
}
```
The above program is actually two programs, a consumer and a producer,
depending on how you compile it.
You compile the producer by making sure that the PRODUCER\_MODE macro
is defined:
```
# gcc -Wall -DPRODUCER_MODE -o producer test_concur.c
```
The consumer is compiled without defining the PRODUCER\_MODE macro:
```
# gcc -Wall -o consumer test_concur.c
```
The consumer and producer share some global memory (8 bytes pointed to by data); the producer's role is to read two 32-bit integers from stdin and write them to the shared
memory. The consumer reads integers from the shared memory and
computes their sum.
After writing the data to shared memory, the producer signals to the
consumer (via SIGUSR1) that it may begin the computation. After the
computation is done, the consumer signals to the producer (via SIGUSR1
again) that it may continue.
Both processes stop when the sum is 0.
Currently, each program begins by outputing its pid and reading from
stdin the other program's pid. This should probably :D be replaced by
something smarter, depending on exactly what you are doing.
Also, in practice, the "while (!cancontinue);"-like loops should be
replaced by something else :D, like semaphores. At least you should do
a small sleep inside each loop. Also, I think you do not truly need shared memory to solve this problem, it should be doable using message-passing techniques.
Here is an example session, showed in parallel:
```
# ./producer # ./consumer
Hi, I am the writer process and my pid is 11357 Hi, I am the reader process and my pid is 11358
Please give me the pid of the other process: 11358 Please give me the pid of the other process: 11357
Enter two integers: 2 Waiting for producer to signal me to do my work
3
Sending signal to consumer process Received signal
Waiting for consumer to allow me to continue Pretending to do a long calculation
... some times passes ...
The sum of the ints in the shared memory is 5
Signaling producer I'm done
Enter two integers: 0 Waiting for producer to signal me to do my work
0
Sending signal to consumer process Received signal
Waiting for consumer to allow me to continue Pretending to do a long calculation
... some times passes ...
The sum of the ints in the shared memory is 0
Signaling producer I'm done
Sum was 0, exiting...
```
I hope this helps. (when you run the programs, make sure the file test\_concur.c exists (it's used to establish the shared memory key (ftok function call))) | Not quite what you've asked for, but could you use pipes (named or otherwise) to affect the synchronization? This puts the locking burden onto the OS which already knows how to do it.
Just a thought.
---
**Response to comment:** What I had in mind was using pipes rather than shared memory to more the data around, and getting synchronization for free.
For instance:
1. Process A starts, sets up a bi-directional pipe **and** forks process B using `popen (3)`.
2. Immediately after the fork:
* A does some work and writes to the pipe
* B attempts to read the pipe, which will block until process A writes...
3. Next:
* A attempts to read the pipe, which will block until data is available...
* B does some work and writes to the pipe
4. goto step 2 until you reach a ending condition.
This is not what you asked for. No shared memory, no signals, but it should do the trick... | Stop and start running again processes in Linux using C++ | [
"",
"c++",
"linux",
"process",
"controls",
""
] |
How can I list all the local users configured on a windows machine (Win2000+) using java.
I would prefer doing this with ought using any java 2 com bridges, or any other third party library if possible.
Preferable some native method to Java. | Using a Java-COM Bridge , like [Jacob](http://danadler.com/jacob/). You then select an appropriate COM library, e.g. [COM API for WMI](http://msdn.microsoft.com/en-us/library/aa389276(VS.85).aspx) to list local users, or any other Windows management information.
The [Win32\_SystemUsers](http://msdn.microsoft.com/en-us/library/aa394490(VS.85).aspx) association WMI class relates a computer system and a user account on that system.
The [Win32\_Account](http://msdn.microsoft.com/en-us/library/aa394061(VS.85).aspx) abstract WMI class contains information about user accounts and group accounts known to the computer system running Windows. User or group names recognized by a Windows NT domain are descendants (or members) of this class.
Working Example (jacob 1.17-M2, javaSE-1.6):
```
import java.util.Enumeration;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;
public class ComTst {
public static void main(String[] args) {
ComThread.InitMTA();
try {
ActiveXComponent wmi = new ActiveXComponent("winmgmts:\\\\.");
Variant instances = wmi.invoke("InstancesOf", "Win32_SystemUsers");
Enumeration<Variant> en = new EnumVariant(instances.getDispatch());
while (en.hasMoreElements())
{
ActiveXComponent bb = new ActiveXComponent(en.nextElement().getDispatch());
System.out.println(bb.getPropertyAsString("PartComponent"));
}
} finally {
ComThread.Release();
}
}
}
``` | Using Java COM Object, i.e. Jacob:
```
public static void EnumerateUsers() {
String query = "SELECT * FROM Win32_UserAccount";
ActiveXComponent axWMI = new ActiveXComponent("winmgmts:\\");
Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));
EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
Dispatch item = null;
StringBuilder sb = new StringBuilder();
while (enumVariant.hasMoreElements()) {
item = enumVariant.nextElement().toDispatch();
sb.append("User: " + Dispatch.call(item, "Name")).toString();
System.out.println(sb);
sb.setLength(0);
}
}
``` | Using Java, How can I get a list of all local users on a windows machine | [
"",
"java",
"windows",
"security",
"operating-system",
""
] |
Does anyone know of a library to do fixed point arithmetic in Python?
Or, does anyone has sample code? | If you are interested in doing fixed point arithmetic, the Python Standard Library has a [decimal](http://docs.python.org/library/decimal.html) module that can do it.
Actually, it has a more flexible floating point ability than the built-in too. By flexible I mean that it:
* Has "signals" for various exceptional conditions (these can be set to do a variety of things on signaling)
* Has positive and negative
infinities, as well as NaN (not a
number)
* Can differentiate between positive
and negative 0
* Allows you to set different rounding
schemes.
* Allows you to set your own min and
max values.
All in all, it is handy for a [million household uses](http://www.skepticfiles.org/en001/monty16.htm). | The [deModel](http://www.dilloneng.com/demodel.html) package sounds like what you're looking for. | Fixed-point arithmetic | [
"",
"python",
"math",
""
] |
I've just written a small XBox 360 Wireless Controller managed interface that basically
wraps around the low-lever [SlimDX](http://slimdx.mdxinfo.com/wiki/index.php?title=Main_Page) wrapper library and provides a easy, managed API for the XBOX 360 controller.
Internally, the class polls the gamepad every N ms, and shoots events as it detects changes in the underlying state of the controller.
I'm experiencing some what dead end with timers that is basiclly forcing to choose between the lesser of two evils:
* Either make my XBox360GamePad class UI framework specific (i.e. support WPF/WinForms will be hard-coded in the class, and the class has to reference these frameworks...)
* Make the class completely framework agnostic, but force the users to sprinkle their code with Dispatcher.Invoke / Invoke() calls to be able to update UI according to the events generated.
If I choose the latter option (of making the code UI agnostic), then I basically use the "generic" System.Timers.Timer or any timer that has no UI dependency.
In that case I end up having events generated/called from a thread that is incapable of directly updating the UI, i.e. in WPF, I would have to issue every update originated form the 360 controller class through the (ugly) use of Dispatcher.Invoke.
On the other hand, If I use DispatcherTimer inside the XBox 360 Controller class I have a working component that can update the UI directly with no fuss, but now my whole controller class is coupled to WPF, and it can't be used without being dependent on WPF (i.e. in a pure console app)
What I'm kind of looking is a some sort solution that would allow me to be both framework agnostic and also update UI without having to resort to all kinds of Dispatcher.Invoke() techniques...
If for example there was a shared base class for all timers, I could somehow inject the timer as a dependency according to the relevant scenario..
Has anyone ever dealt successfully with this sort of problem? | So...
It appears the information / code @ [http://geekswithblogs.net/robp/archive/2008/03/28/why-doesnt-dispatcher-implement-isynchronizeinvoke.aspx](https://web.archive.org/web/20210125200028/http://geekswithblogs.net/robp/archive/2008/03/28/why-doesnt-dispatcher-implement-isynchronizeinvoke.aspx) does indeed provide a working solution.
The code is completely independent of any UI, and is instead only dependent on ISynchronizeInvoke for proper UI / Thread integration.
Having just used this, I'm still somewhat reluctant to leave it as is.
The gist of my problem is that every event invocation function looks something like this:
```
protected virtual void OnLeftThumbStickMove(ThumbStickEventArgs e)
{
if (LeftThumbStickMove == null) return;
if (_syncObj == null || !_syncObj.InvokeRequired)
LeftThumbStickMove(this, e);
else
_syncObj.BeginInvoke(LeftThumbStickMove, new object[] { this, e });
}
```
It's very annoying and confusing to write code this way, it looks, to me, like way too much fuss around just getting the damn thing to work. Basically I don't like having to wrap every event call with so much logic(!)
Therefore, I've opted for a different / additional strategy:
Basically, the constructor for the XBox360GamePad class now looks like this:
```
public XBox360GamePad(UserIndex controllerIndex, Func<int, Action, object> timerSetupAction)
{
CurrentController = new Controller(controllerIndex);
_timerState = timerSetupAction(10, UpdateState);
}
```
As you can see, it accepts a Func<int, Action, object> that is responsible for creating the timer and hooking it up.
This means that by default, INSIDE the 360 Controller class I don't need to use any
UI specific timers... In essence, my "default" constructor for the controller looks like this:
```
public XBox360GamePad(UserIndex controllerIndex) :
this(controllerIndex, (i,f) => new Timer(delegate { f(); }, null, i, i)) {}
```
I use a lambda function to code the dependency of the controller class on a timer "service".
From WPF, I use the more general constructor to ensure that the control will be using the DispatcherTimer like this:
```
_gamePad = new XBox360GamePad(UserIndex.One, (i, f) => {
var t = new DispatcherTimer(DispatcherPriority.Render) {Interval = new TimeSpan(0, 0, 0, 0, i) };
t.Tick += delegate { f(); };
t.Start();
return t;
});
```
This way, I basically leave it up to the "user" to provide the timer implementation for the control, where the default implementation doesn't have to use any WPF or WinForms specific code.
I personally find this more useful / nicer design than using ISynchronizeInvoke.
I would love to hear feedback from people that like this / want to improve this / are disgusted by this etc. | Is a polling architecture the only option?
In any case, personally I would restructure the system so that outside world can subscribe to events that is fired from the controller class.
If you want the controller to fire the events on the right thread context, then I would add a property for a ISynchronizeInvoke interface, and if this property is non-null inside the controller, use the interface, otherwise just invoke the events directly, on the thread the controller runs on.
This would for instance allow you make the entire polling thing into a thread that wakes up every N milliseconds to do its job, or even use event objects to just wait for events (if the 360 controller architecture has something like this). | Timers, UI Frameworks and bad coupling - Any Ideas? | [
"",
"c#",
".net",
"wpf",
"timer",
"coupling",
""
] |
I've built a small application which has User Management, a frontend console to enter data and a backend console to control parts of the frontend. The frontend adds rows to a MySQL database which are timestamped. The backend needs to be able to select rows from the database between X and Y dates.
Everything works so far, except the date part which I'm really struggling with.
The frontend SQL input looks like this (simplified with spurious code removed):
```
$date = time();
$top_level_category = $_POST['top_level_category'];
$sub_level_category = $_POST['sub_level_category'];
$company = $_POST['company'];
$agent_name = $_POST['agent_name'];
$ticket_id = $_POST['ticket_id'];
$sql = "INSERT INTO dacc_data ("
. "id, top_level_category, sub_level_category, "
. "agent_name, date, ticket_id, company"
. ") VALUES ("
. "NULL, '$top_level_category', '$sub_level_category', "
. "'$agent_name', FROM_UNIXTIME('$date'), '$ticket_id', '$company'"
. ")"
;
$result = mysql_query($sql) or die (mysql_error());
```
That seems to work ok, the timestamp is being picked up and added to a DATETIME column in my table. It displays as dd/mm/yyyy hh:mm:ss within the database.
So ... my first question is - is this the right way to do it?
The second question being, what sort of SQL statement would I need to pull out an array of rows between X and Y date.
Apologies if this is rambling a bit, hope it's clear but if you need more information let me know. | MySQL datetime should be formatted with dashes:
YYYY-MM-DD HH:MM:SS
<http://dev.mysql.com/doc/refman/5.0/en/datetime.html>
Then you can query for date ranges a couple of ways:
```
select *
from table
where date >= '[start date]' and date <= '[end date]';
```
or
```
select *
from table
where date between '[start date]' and '[end date]';
```
*where "table" is the name of your database table and "date" is the name of your datetime field.* | You are correct. I can confirm that the Database has "YYYY-MM-DD HH:MM:SS" - I am using SQLWave editor for browsing the DB quickly, it auto-formats the DATETIME column.
```
// Initial questions still stand :)
```
Or not, just noticed you updated the answer - thank you very much! I had actually tried that very same query several times to no avail, mainly because my WHERE was specifying the date format incorrectly. Misled by SQLWave :(
Back to using command line from now on !!! | php mysql date/time question | [
"",
"php",
"mysql",
"datetime",
"select",
""
] |
I think the answer to this question is so obivous that noone has bothered writing about this, but its late and I really can't get my head around this.
I've been reading into IoC containers (Windsor in this case) and I'm missing how you talk to the container from the various parts of your code.
I get DI, I've been doing poor mans DI (empty constructors calling overloaded injection constructors with default parameter implementations) for some time and I can completely see the benefit of the container. However, Im missing one vital piece of info; how are you supposed to reference the container every time you need a service from it?
Do I create a single global insance which I pass around? Surely not!
I know I should call this:
```
WindsorContainer container = new WindsorContainer(new XmlInterpreter());
```
(for example) when I want to load my XML config, but then what do I do with container? Does creating a new container every time thereafter persist the loaded config through some internal static majicks or otherwise, or do I have to reload the config every time (i guess not, or lifecycles couldnt work).
Failing to understand this is preventing me from working out how the lifecycles work, and getting on with using some IoC awsomeness
Thanks,
Andrew | 99% of the cases it's one container instance per app. Normally you initialize it in Application\_Start (for a web app), [like this](https://github.com/castleproject/Castle.MonoRail-READONLY/blob/45ac205867396b1b7ad287a872e5b20afd0af837/src/TempWeb/Global.asax.cs).
After that, it's really up to the consumer of the container. For example, some frameworks, like [Monorail](http://www.castleproject.org/MonoRail/) and [ASP.NET MVC](http://www.codeplex.com/aspnet) allow you to intercept the creation of the instances (the controllers in this case), so you just register the controllers and their dependencies in the container and that's it, whenever you get a request the container takes care of injecting each controller with its dependencies. See for example [this ASP.NET MVC controller](http://mvccontrib.codeplex.com/SourceControl/changeset/view/6aa25407de83#src%2fSamples%2fMvcContrib.Samples.WindsorControllerFactory%2fControllers%2fHomeController.cs).
In these frameworks, you hardly ever need to call or even reference the container in your classes, which is the recommended usage.
Other frameworks don't let you get in the creation process easily (like Webforms) so you have to resort to hacks like [this one](http://ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx), or *pull* the required dependencies (that is, explicitly calling the container). To pull dependencies, use a static gateway to the container like [this one](https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/commons/Rhino.Commons/RhinoContainer/IoC.cs) or the one described by [maxnk](https://stackoverflow.com/questions/367178/usage-of-ioc-containers-specifically-windsor#367190). Note that by doing this, you're actually using the container as a Service Locator, which doesn't decouple things as well as inversion of control. (see difference [here](http://martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection) and [here](http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx))
Hope this clears your doubts. | Generally you want to keep only one instance for the lifetime of the entire application.
What I do most of the time is I initialize the container when the app starts, and then I use typed factories for container-unaware pulling of objects.
Other popular approach is to wrap the container instance with static class and use that static class to access your (singleton) container. You can find an example of that in Ayende's Rhino.Commons library [here](https://svn.sourceforge.net/svnroot/rhino-tools/trunk/rhino-commons/Rhino.Commons/RhinoContainer/IoC.cs). This approach however has severe drawbacks and should be avoided. | Usage of IoC Containers; specifically Windsor | [
"",
"c#",
"inversion-of-control",
"castle-windsor",
""
] |
In .NET, a value type (C# `struct`) can't have a constructor with no parameters. According to [this post](https://stackoverflow.com/questions/203695/structure-vs-class-in-c#204009) this is mandated by the CLI specification. What happens is that for every value-type a default constructor is created (by the compiler?) which initialized all members to zero (or `null`).
Why is it disallowed to define such a default constructor?
One trivial use is for rational numbers:
```
public struct Rational {
private long numerator;
private long denominator;
public Rational(long num, long denom)
{ /* Todo: Find GCD etc. */ }
public Rational(long num)
{
numerator = num;
denominator = 1;
}
public Rational() // This is not allowed
{
numerator = 0;
denominator = 1;
}
}
```
Using current version of C#, a default Rational is `0/0` which is not so cool.
**PS**: Will default parameters help solve this for C# 4.0 or will the CLR-defined default constructor be called?
---
[Jon Skeet](https://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net#333840) answered:
> To use your example, what would you want to happen when someone did:
>
> ```
> Rational[] fractions = new Rational[1000];
> ```
>
> Should it run through your constructor 1000 times?
Sure it should, that's why I wrote the default constructor in the first place. The CLR should use the *default zeroing* constructor when no explicit default constructor is defined; that way you only pay for what you use. Then if I want a container of 1000 non-default `Rational`s (and want to optimize away the 1000 constructions) I will use a `List<Rational>` rather than an array.
This reason, in my mind, is not strong enough to prevent definition of a default constructor. | **Note:** the answer below was written a long time prior to C# 6, which is planning to introduce the ability to declare parameterless constructors in structs - but they still won't be called in all situations (e.g. for array creation) (in the end this feature [was not added to C# 6](https://stackoverflow.com/questions/31063109/parameterless-constructors-in-structs-for-c-sharp-6))... but then it *was* [added in C# 10](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/parameterless-struct-constructors) - but there are limitations, so you can't expect the constructor to run in every situation.
---
EDIT: I've edited the answer below due to Grauenwolf's insight into the CLR.
The CLR allows value types to have parameterless constructors, but C# doesn't. I believe this is because it would introduce an expectation that the constructor would be called when it wouldn't. For instance, consider this:
```
MyStruct[] foo = new MyStruct[1000];
```
The CLR is able to do this very efficiently just by allocating the appropriate memory and zeroing it all out. If it had to run the MyStruct constructor 1000 times, that would be a lot less efficient. (In fact, it doesn't - if you *do* have a parameterless constructor, it doesn't get run when you create an array, or when you have an uninitialized instance variable.)
The basic rule in C# is "the default value for any type can't rely on any initialization". Now they *could* have allowed parameterless constructors to be defined, but then not required that constructor to be executed in all cases - but that would have led to more confusion. (Or at least, so I believe the argument goes.)
EDIT: To use your example, what would you want to happen when someone did:
```
Rational[] fractions = new Rational[1000];
```
Should it run through your constructor 1000 times?
* If not, we end up with 1000 invalid rationals
* If it does, then we've potentially wasted a load of work if we're about to fill in the array with real values.
EDIT: (Answering a bit more of the question) The parameterless constructor isn't created by the compiler. Value types don't have to have constructors as far as the CLR is concerned - although it turns out it *can* if you write it in IL. When you write "`new Guid()`" in C# that emits different IL to what you get if you call a normal constructor. See [this SO question](https://stackoverflow.com/questions/203695/structure-vs-class-in-c) for a bit more on that aspect.
I *suspect* that there aren't any value types in the framework with parameterless constructors. No doubt NDepend could tell me if I asked it nicely enough... The fact that C# prohibits it is a big enough hint for me to think it's probably a bad idea. | A struct is a value type and a value type must have a default value as soon as it is declared.
```
MyClass m;
MyStruct m2;
```
If you declare two fields as above without instantiating either, then break the debugger, `m` will be null but `m2` will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated! | Why can't I define a default constructor for a struct in .NET? | [
"",
"c#",
".net",
"struct",
""
] |
I've two tables: TableA and TableB, joined by TableA.TableA\_Id->1..n<-TableB.TableA\_Id. A simple PK-FK.
I need to extract **distinct** TableA records given a certain condition on TableB. Here's my 1st approach:
SELECT \* FROM TableA A INNER JOIN TableB B ON A.idA = B.IdA AND B.Date = '2009-01-10' ORDER BY A.Id;
This is nice, but it doesn't give me "distinct" records. Some records on table B may be duplicate and hence I could get the same records more than once.
So I decided to perform a subselect (performance is not an issue given that the subselect will probably end up with 20/30 records max):
SELECT \* FROM TableA WHERE TableA.Id IN ( SELECT DISTINCT IdA FROM TableB WHERE Date = '20090110' ) ORDER BY TableA.IdA;
This works fine.
Now the question is: how can I use the Inner Join and still get the distinct values? Is this possible in one pass or the nested query is a must? What am I missing? | use a derived table
```
SELECT * FROM TableA
JOIN
(SELECT DISTINCT IdA FROM TableB WHERE Date = '20090110') a
ON a.IDA = TAbleA.IDA
ORDER BY TableA.IdA
``` | I think a normal exists statement is what you need:
```
SELECT *
FROM TableA A
WHERE Exists( select B.IdA from TableB B where A.IdA = B.IdA and B.Date = '2009-01-10' )
ORDER BY A.Id;
```
Performance-wise it should be the best approach.
If you need values from the other table, and to avoid using distinct, you could join to a sub query that is grouped like so:
```
Select TableA.*, groupedTableB.OtherData
From TableA
Inner join
(
select TableB.IdA, Sum(TableB.Data) SummaryData
from TableB where TableB.Date = '2009-01-10'
group by TableB.IdA
) groupedTableB on groupedTableB.IdA = TableA.IdA
``` | Best approach to SQL Server query using distinct | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I created a webservice when it hosted on my local computer it works fine, but when i publish it to the web host, it doesnt work any more, i guess its a question about how the webserver is configured, but can i make some changes in web.config so it will work?
## The error i get is below:
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load file or assembly 'MySql.Data, Version=5.0.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 37:
Line 38:
Line 39:
Line 40:
Line 41:
Source File: c:\webs\talkactive\gb1634\qaz.dk\web.config Line: 39
## Assembly Load Trace: The following information can be helpful to determine why the assembly 'MySql.Data, Version=5.0.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' could not be loaded.
The webservice uses a c# class placed in the app\_code folder. That c# class uses mysql.
When i use the class in a normal .aspx file it works fine | I guess the obvious thing would be to check whether the MySql.Data exist in the GAC (or the web service's bin folder) on the server and is of the correct version and public key? | Basically, you are missing this DLL. You should look at putting it in the bin directory of your webservice. | Error in webservice after publishing | [
"",
"c#",
"web-services",
""
] |
How can I get a DataSet with all the data from a SQL Express server using C#?
Thanks
edit: To clarify, I do want all the data from every table. The reason for this, is that it is a relatively small database. Previously I'd been storing all three tables in an XML file using DataSet's abilities. However, I want to migrate it to a database. | You can use the GetSchema method to get all the tables in the database and then use a data adapter to fill a dataset. Something like this (I don't know if it compiles, I just paste some code and change it a bit):
```
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DataTable tables = null;
DataSet database = new DataSet();
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
string[] restrictions = new string[4];
// Catalog
restrictions[0] = "Northwind";
// Owner
restrictions[1] = "dbo";
// Table - We want all, so null
restrictions[2] = null;
// Table Type - Only tables and not views
restrictions[3] = "BASE TABLE";
connection.Open();
// Here is my list of tables
tables = connection.GetSchema("Tables", restrictions);
// fill the dataset with the table data
foreach (DataRow table in tables.Rows)
{
string tableName = table["TABLE_NAME"].ToString();
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand command = factory.CreateCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select * from [" + tableName + "]";
adapter.SelectCommand = command;
adapter.Fill(database, tableName);
}
}
```
**EDIT:**
Now I refactored it a bit and now it's working as it should. The use of DbConnection and DbProviderFactories is for database engine abstraction, I recommend using it so you can change the database engine changing this line and the connection string:
```
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
```
The GetSchema method will retrive all tables from your database to a DataTable and then we get all the data from each table to the DataSet using the DataAdapter. | I think you need to narrow down the question somewhat... *All* the data? You mean, all the data in every table in every database? Well, the only answer to that is, *a lot of code*.
To connect to and talk to a SQL Server Express database engine, use the classes in the System.Data.SqlClient namespace, namely:
* [SqlConnection](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx): Connect to the database
* [SqlCommand](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx): Talk to the database
* [SqlDataReader](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx): Iterate over data retrieved from the database
You can check the MSDN pages for all of these classes by clicking on the links above.
Here are some overview-links with more information:
* [CodeProject: Beginners guide to accessing SQL Server through C#](http://www.codeproject.com/KB/database/sql_in_csharp.aspx)
* [DevHood: Accessing SQL Server Data in C# with ADO.NET](http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=454)
Note that by and large, you use a SQL Server Express database engine the same way as the full SQL Server product, the difference is more in the tools you get with it, and some limitations in the express engine. Other than that you can just use the classes and language that you would use for a normal SQL Server database engine installation.
If this post didn't answer your question, please elaborate, and you have a higher chance of getting the answer you seek. | Getting a DataSet from an SQL Express Server C# | [
"",
"c#",
"sql-server",
"database",
"dataset",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.