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 m...
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/w...
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...
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 loadin...
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...
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 ...
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 implement...
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-...
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. Althoug...
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 crit...
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 current...
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 { cla...
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 spec...
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 ...
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....
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 s...
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....
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...
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); ...
``` $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 > 1960931441410456834630852...
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 se...
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...
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: ``` pu...
[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 g...
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* exa...
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 J...
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 ...
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...
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?" ...
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. T...
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 Or...
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() ...
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); ...
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 ...
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-gener...
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; // exa...
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 } pub...
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 ```...
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 i...
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 becaus...
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 produc...
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/hardwa...
> 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 ...
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 u...
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...
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 comman...
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 = ...
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 extraditabl...
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. [![JAR Export Dialog](https://i.stack.imgur.com/...
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....
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 ...
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.co...
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 ...
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/...
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...
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:** S...
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 clas...
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::...
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`), initia...
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 a...
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) re...
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 reas...
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 `...
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...
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...
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> companiesWithEmploye...
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: `...
`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,...
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 =...
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...
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 my...
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 blockin...
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 waitin...
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) ...
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 y...
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 s...
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 HttpList...
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 HttpList...
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 readi...
***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 pro...
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 so...
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...
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 ...
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 ...
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...
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.WorkComple...
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(dou...
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 s...
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 tut...
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) RE...
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 ...
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 appreciate...
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 wind...
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() {...
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...
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...
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...
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(SPItemEventPropert...
``` 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; ...
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",...
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 ...
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 v...
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 luc...
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...
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 ...
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 `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. B...
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 we...
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 smalldateti...
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...
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 posti...
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...
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 ...
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> <...
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...
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 doe...
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 t...
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[strNam...
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...
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 ano...
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', bu...
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`,...
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...
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 ...
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 includ...
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 stri...
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 warn...
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 asso...
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.fileDownloadCou...
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 200...
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...
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, sta...
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 statemen...
``` 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;...
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...
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> N...
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 ...
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 l...
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 w...
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; } ``...
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 y...
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 ve...
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 in...
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) ...
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...
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], HeapCompatibilityInformat...
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 c...
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 ...
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 c...
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 answe...
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...
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 t...
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 inst...
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 gu...
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<Li...
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>> unmodi...
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 us...
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 evaluati...
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...
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: ...
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 der...
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 colu...
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 lin...
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...
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, t...
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 ...
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 M...
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...
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 f...
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(){ ...
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 wh...
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: *...
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 ex...
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 th...
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 st...
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 ...
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 informatio...
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' databa...
``` 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 b...
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 h...
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 fin...
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 place...
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....
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. ...
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 "headles...
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 link...
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. B...
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/EWSWeb...
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 PageMeth...
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 ...
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 memor...
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, an...
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...
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(vC...
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 cond...
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 sho...
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 ...
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 inter...
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 f...
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...
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 qu...
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 doi...
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 cont...
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 ...
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?) wh...
**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/...
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 f...
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; Th...
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...
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 Descriptio...
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 migr...
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...
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: * [SqlCon...
Getting a DataSet from an SQL Express Server C#
[ "", "c#", "sql-server", "database", "dataset", "" ]