Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have these tables: ``` customer -------- customer_id int name varchar(255) order ----- order_id int customer_id int discount boolean ``` I can get the number of orders made by each customer with a query like: ``` select c.id, count(o.order_id) from customer c left join order as o using c.customer_id = o.customer_id group by 1 ``` Alternatively, I can get the number of discounted orders made by each customer with: ``` select c.id, count(o.order_id) from customer c left join order as o using c.customer_id = o.customer_id and o.discount = true group by 1 ``` But I can't figure out a way to get both in a single query. I've tried the following: ``` select c.id, count(o.order_id), count(o2.order_id) from customer c left join order as o using c.customer_id = o.customer_id left join order as o2 using c.customer_id = o2.customer_id and o2.discount = true group by 1 ``` But it didn't work. Is it possible to calculate both in a single (MySql) query? Cheers, Don
How about something like ``` select c.id, count(o.order_id),sum(if(o.discount,1,0)) from customer c left join order as o using c.customer_id = o.customer_id group by c.id ```
You could do somethings like ``` select c.id, sum(case o.discount when true then 1 else 0 end) as 'total discounted', count(o.order_id) as 'total orders' from customer as c left join order as o using c.customer_id = o.customer_id group by c.id ```
group by query challenge
[ "", "sql", "mysql", "" ]
The .net framework provides in the Math class a method for powering double. But by precision requirement I need to raise a decimal to a decimal power [ Pow(decimal a, decimal b) ]. Does the framework have such a function? Does anyone know of a library with this kind of function?
To solve my problem I found some [expansion series](http://mathworld.wolfram.com/MaclaurinSeries.html "expansion series"), and them I had them implemented to solve the equation X^n = e^(n \* ln x). ``` // Adjust this to modify the precision public const int ITERATIONS = 27; // power series public static decimal DecimalExp(decimal power) { int iteration = ITERATIONS; decimal result = 1; while (iteration > 0) { fatorial = Factorial(iteration); result += Pow(power, iteration) / fatorial; iteration--; } return result; } // natural logarithm series public static decimal LogN(decimal number) { decimal aux = (number - 1); decimal result = 0; int iteration = ITERATIONS; while (iteration > 0) { result += Pow(aux, iteration) / iteration; iteration--; } return result; } // example void main(string[] args) { decimal baseValue = 1.75M; decimal expValue = 1/252M; decimal result = DecimalExp(expValue * LogN(baseValue)); } ``` The Pow() and Factorial() functions are simple because the power is always an int (inside de power series).
This should be the fastest for a positive integer Exponent and a decimal base: ``` // From http://www.daimi.au.dk/~ivan/FastExpproject.pdf // Left to Right Binary Exponentiation public static decimal Pow(decimal x, uint y){ decimal A = 1m; BitArray e = new BitArray(BitConverter.GetBytes(y)); int t = e.Count; for (int i = t-1; i >= 0; --i) { A *= A; if (e[i] == true) { A *= x; } } return A; } ```
Raising a decimal to a power of decimal?
[ "", "c#", "bigdecimal", "decimal", "" ]
I have a webpage on my site that displays a table, reloads the XML source data every 10 seconds (with an XmlHttpRequest), and then updates the table to show the user any additions or removals of the data. To do this, the JavaScript function first clears out all elements from the table and then adds a new row for each unit of data. Recently, I battled thru a number of memory leaks in Internet Explorer caused by this DOM destroy-and-create code (most of them having to do with circular references between JavaScript objects and DOM objects, and the JavaScript library we are using quietly keeping a reference to every JS object created with `new Element(...)` until the page is unloaded). With the memory problems solved, we've now uncovered a CPU-based problem: when the user has a large amount of data to view (100+ units of data, which equals 100 `<tr>` nodes to create, plus all of the table cells for each column), the process ties up the CPU until Internet Explorer prompts the user with: > Stop running this script? > A script on this page is causing Internet Explorer to run slowly. > If it continues to run, your computer may become > unresponsive. It seems that running the row-and-cell-creation code times 100+ pieces of data is what is causing the CPU usage to spike, the function to take "too long" (from IE's perspective) to run, thus causing IE to generate this warning for the user. I've also noticed that while the "update screen" function runs for the 100 rows, IE does not re-render the table contents until the function completes (since the JS interpreter is using 100% CPU for that time period, I assume). So my question is: Is there any way in JavaScript to tell the browser to pause JS execution and re-render the DOM? If not, are there any strategies for handling creating large amounts of DOM nodes and *not* having the browser choke? One method I can think of would be to handle the "update table" logic asynchronously; that is, once the Ajax method to reload the XML data is complete, put the data into some sort of array, and then set a function (using `setInterval()`) to run which will handle one element of the array at a time. However this seems a little bit like re-creating threading in a JavaScript environment, which seems like it could get very complicated (i.e. what if another Ajax data request fires while I'm still re-creating the table's DOM nodes?, etc.) --- **update**: Just wanted to explain why I'm accepting RoBurg's answer. In doing some testing, I've found that the `new Element()` method in my framework (I'm using [mootools](http://mootools.net/)) is about 2x as slow as the traditional `document.createElement()` in IE7. I ran a test to create 1000 `<spans>` and add them to a `<div>`, using `new Element()` takes about 1800ms on IE7 (running on Virtual PC), the traditional method takes about 800ms. My test also revealed an even quicker method, at least for a simple test such as mine: using [DocumentFragments as described by John Resig](http://ejohn.org/blog/dom-documentfragments/). Running the same test on the same machine with IE7 took 247ms, a **9x** improvement from my original method!
100 `<tr>`'s isn't really that much... are you still using that framework's `new Element()`? That might be the cause of it. You should test the speed of `new Element()` vs `document.createElement()` vs `.innerHTML` Also try building the dom tree "in memory" then append it to the document at the end. Finally watch that you're not looking at .length too often, or other bits and bobs like that.
I have experienced similar problems at round 3000 table rows of complex data, so there is something not entirely right with your code. How is it running in firefox ? Can you check in several different browsers. Are you binding to onPropertyChange anywhere ? This is a really dangerous ie event that has caused me severe ie-specific headaches earlier. Are you using CSS selectors anywhere ? These are notoriously slow on ie.
Possible to add large amount of DOM nodes without browser choking?
[ "", "javascript", "ajax", "dom", "" ]
Let's say I have two existing tables, "dogs" and "cats": ``` dog_name | owner ---------+------ Sparky | Bob Rover | Bob Snoopy | Chuck Odie | Jon cat_name | owner ---------+------ Garfield | Jon Muffy | Sam Stupid | Bob ``` How do I write a query with this output? ``` owner | num_dogs | num_cats ------+----------+--------- Bob | 2 | 1 Chuck | 1 | 0 Sam | 0 | 1 Jon | 1 | 1 ```
``` select owner, sum(num_dogs), sum(num_cats) from (select owner, 1 as num_dogs, 0 as num_cats from dogs union select owner, 0 as num_dogs, 1 as num_cats from cats) group by owner ```
I prefer this one: ``` select owner , count(dog_name) dogs , count(cat_name) cats from cats FULL OUTER JOIN dogs ON (cats.owner = dogs.owner) ```
Can SQL calculate aggregate functions across multiple tables?
[ "", "sql", "" ]
I can not figure out what all the parameters to the arc() function are (by experimentation) and I have not found any tutorial that seems to explain them. Where would a good explanation of the arc() function be?
``` arc(x, y, radius, startAngle, endAngle, anticlockwise) ``` The first three parameters, x and y and radius, describe a circle, the arc drawn will be part of that circle. startAngle and endAngle are where along the circle to start and stop drawing. 0 is east, Math.PI/2 is south, Math.PI is west, and Math.PI\*3/2 is north. If anticlockwise is 1 then the direction of the arc is reversed. <https://developer.mozilla.org/En/Canvas_tutorial/Drawing_shapes#Arcs> ![Clockwise](https://i.stack.imgur.com/1qF8E.jpg) ![AntiClockwise](https://i.stack.imgur.com/LqtRU.jpg) In the attached diagrams, the only difference is the anticlockwise param. Math.PI/2 always ends south when clockwise or anticlockwise
I was having the same problem and made a little interactive page to help make sense of it: <http://www.scienceprimer.com/drawing-circles-javascript-html5-canvas-element> All of the parameters can be adjusted and the resulting arc is rendered in real time. The page also demonstrates how the fill(), stroke() and closePath() methods interact with the arc() method.
tutorial for HTML canvas's arc function
[ "", "javascript", "html", "canvas", "" ]
For some reason the following code fails. You can't simply erase a reverse\_iterator by using its base() method. ``` #include <set> #include <iostream> int main() { std::set<int> setOfInts; setOfInts.insert(1); setOfInts.insert(2); setOfInts.insert(3); std::set<int>::reverse_iterator rev_iter = setOfInts.rbegin(); std::set<int>::reverse_iterator nextRevIter = setOfInts.rbegin(); ++nextIter; while ( rev_iter != setOfInts.rend()) { // Find 3 and try to erase if (*rev_iter == 3) { // SEGFAULT HERE setOfInts.erase( rev_iter.base()); } rev_iter = nextRevIter; ++nextRevIter; } } ``` How does one go about correctly doing the above? Given a reverse\_iterator that corresponds to something you want to erase, how do you erase it? **Note, erase won't take reverse\_iterators unfortunately. It wants the real thing.**
Apparently the solution is what base() returns is 1 off. The following identity holds for a reverse\_iterator: ``` &*(reverse_iterator(i)) == &*(i - 1) ``` Or in other words, the reverse\_iterator is always one pass the regular iterator it is the base of. Not sure why. # In GCC Simply change ``` // SEGFAULT HERE setOfInts.erase( rev_iter.base()); ``` to ``` // WORKS! setOfInts.erase( --rev_iter.base()); ``` I'm definitely curious though as to why the identity above makes sense. # In Visual Studio Coming back into work and trying this in visual studio, I see the above solution doesn't quite work. The "nextIter" becomes invalid on the erase. Instead, you need to save away the temporary from the erase to get the next iterator instead of keeping around a nextIter like above. ``` set<int>::iterator tempIter = setOfInts.erase(--rev_iter.base()); rev_iter = setOfInts.erase(tempIter); ``` So the final solution is ``` int main() { using namespace std; set<int> setOfInts; setOfInts.insert(1); setOfInts.insert(2); setOfInts.insert(3); set<int>::reverse_iterator rev_iter = setOfInts.rbegin(); while ( rev_iter != setOfInts.rend()) { // Find 3 and try to erase if (*rev_iter == 3) { cout << "Erasing : " << *rev_iter; set<int>::iterator tempIter = setOfInts.erase( --rev_iter.base()); rev_iter = set<int>::reverse_iterator(tempIter); } else { ++rev_iter; } } } ``` Note, associative containers do not return an iterator from erase. So this solution wouldn't work for map, multimap, etc.
When you iterate with a reverse iterator and want to use base() to modify its container, always keep in mind that a reverse\_iterator is always based on the next iterator from the original order. It's a little unintuitive but it actually makes the code simpler: ``` #include <set> int main() { std::set<int> setOfInts; setOfInts.insert(1); setOfInts.insert(2); setOfInts.insert(3); typedef std::set<int>::reverse_iterator RevIter; RevIter rev_iter = setOfInts.rbegin(); while (rev_iter != setOfInts.rend()) { // Find 3 and try to erase if (*rev_iter == 3) setOfInts.erase(--rev_iter.base()); ++rev_iter; } } ``` In this example, there is not need to keep a "next" iterator since the base iterator is not invalidated! (We do need it when dealing with normal iterators.) The behavior of reverse iterators creates weird off-by-one difficulties when treating with a single item but in facts it simplify ranges: ``` riValue = find(riEnd.base(), riBegin.base(), value); ``` is using exactly the same objects (in reverse order) as ``` iValue = find(riBegin, riEnd, value); ```
How do I erase a reverse_iterator from an stl data structure?
[ "", "c++", "stl", "iterator", "" ]
I was just wondering if it is possible to capture the output of a separate process running on windows? For instance if i have a console app running, could i run a second app, a forms app, and have that app capture the output from the console app and display it in a text box?
You can do this: ``` Process[] p = Process.GetProcessesByName("myprocess.exe"); StreamReader sr = p[0].StandardOutput; while (sr.BaseStream.CanRead) { Console.WriteLine(sr.ReadLine()); } ```
You can redirect the stdout / stderr (standary out put / error stream) of a process if you are the one starting it. For an example take a look at [this](http://channel9.msdn.com/forums/Coffeehouse/250664-C-Execute-External-App-and-capture-output/). Capturing the output stream of a process which was not started by you, well, that is whole different matter. I'm not sure it can be done. But if you have control over the source code of both apps, there are other ways to communicate, like pipes / remoting / WCF, and so on...
Capture output from unrelated process
[ "", "c#", "" ]
I'm wondering if it's possible to get a handle on running instances of a given class. The particular issue that triggered this was an application that doesn't exit nicely because of a number of running threads. Yes, I know you can daemonize the theads, and they won't then hold up the application exit. But it did get me to wondering if this was possible. The closest thing I can is the classloaders (protected!) [findLoadedClass](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#findLoadedClass(java.lang.String)), although you'd have to run through your own classloader to do this. On a related note, is this how profiling tools manage to track object handles? by running through their own custom classloaders? or is there some nice tricky way that I'm not seeing?
You can indeed get a stack trace of all running Threads dumped to the stdout by using `kill -QUIT <pid>` on a \*NIX like OS, or by running the application in a Windows console and pressing `Ctrl-Pause` (as another poster notes.) However, it seems like you're asking for programmatic ways to do it. So, assuming what you really want is the set of all Threads who's current call stacks include one or more methods from a given class... The best thing I can find that doesn't involve calls into the JVMTI is to inspect the stacks of all running threads. I haven't tried this, but it should work in Java 1.5 and later. Keep in mind that this is, by definition, not AT ALL thread-safe (the list of running threads - and their current stack traces - are going to constantly change underneath you...lots of paranoid stuff would be necessary to actually make use of this list.) ``` public Set<Thread> findThreadsRunningClass(Class classToFindRunning) { Set<Thread> runningThreads = new HashSet<Thread>(); String className = classToFindRunning.getName(); Map<Thread,StackTraceElement[]> stackTraces = Thread.getAllStackTraces(); for(Thread t : stackTraces.keySey()) { StackTraceElement[] steArray = stackTraces.get(t); for(int i = 0;i<steArray.size();i++) { StackTraceElement ste = steArray[i]; if(ste.getClassName().equals(className)) { runningThreads.add(t); continue; } } } return runningThreads; } ``` Let me know if this approach works out for you!
From [this page](http://alek.xspaces.org/2005/08/11/how-does-a-java-profiler-work-ej-technologies-jprofiler), > A Java profiler uses a native interface to the JVM (the JVMPI for Java <=1.4.2 or the [JVMTI for Java >=1.5.0](http://en.wikipedia.org/wiki/Java_Virtual_Machine_Tools_Interface)) to get profiling information from a running Java application. This amounts to some [Sun supplied native code](http://java.sun.com/javase/6/docs/technotes/guides/jvmti/) that gives a profiler hooks into the JVM.
Finding running instances in a running JVM
[ "", "java", "jvm", "classloader", "" ]
I'm wondering about the downsides of each servers in respect to a production environment. Did anyone have big problems with one of the features? Performance, etc. I also quickly took a look at the new Glassfish, does it match up the simple servlet containers (it seems to have a good management interface at least)?
I love Jetty for its low maintenance cost. It's just unpack and it's ready to roll. Tomcat is a bit high maintenance, requires more configuration and it's heavier. Besides, Jetty's continuations are very cool. EDIT: In 2013, there are reports that Tomcat has gotten easier. See comments. I haven't verified that.
I think tomcat is more disscussed and supported by application, Jetty is portable and can be embedded in an application. and Jetty has good continuations.
Tomcat VS Jetty
[ "", "java", "tomcat", "servlets", "webserver", "jetty", "" ]
So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface?
I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices. The grid comparison at djangopluggables.com certainly can make evaluating each of these easier. **django-cms** is the most full-featured and is something you could actually hand over to clients without being irresponsible. Even though it has features for integrating other apps, it doesn't have the extensibility/integration of FeinCMS or the simplicity of django-page-cms. That being said, I think the consensus is that this is the best Open Source CMS for Django. However, it's docs are a little lacking. ***update***: *I have been told that integrating apps into DjangoCMS 2.1 has been improved.* **FeinCMS** - Is a great set of tools for combining and building CMS functionality into your own apps. It's not "out of the box" at all, which means that you can integrate it however you want. It doesn't want to take over your urls.py or control how you route pages. It's probably a prototype for the next-generation of truly pluggable apps in Django. - We are moving from django-page-cms to FeinCMS because our primary models is high volume eCommerce and I have custom content-types I want to integrate that aren't blogs or flash. Good documentation and support as well. **Django-page-cms** - Is great if you want to just have some "About Us" pages around your principle application. Its menu system is not truly hierarchical and building your page presentation is up to you. But it's very simple, unobtrusive, and very easy to slap into your app and get a navigation going that clients can manage, or even for yourself. It has no docs that I know of, but you won't really need any. Read the code and you will get it all in 30 minutes or less. *update* **Mezzanine** - Is a very well designed CMS and one that I have finally settled on for most of my client work, mostly because it has an integrated eCommerce portion. But beyond that it has very extensible page models, and a custom admin interface that a client might be willing to use. It also has the best "out of the box" experience i.e. You can have a full fledged site up with one command.
If you do not necessarily want a finished CMS with a fixed feature set, but rather tools on top of Django to build your own CMS I recommend looking into FeinCMS. It follows a toolkit philosophy instead of trying to solve everything and (too) often failing to do so. <http://github.com/matthiask/feincms/tree/master> Disclaimer: It is my brainchild, and the result of too many frustrating experiences trying to customize another CMS for the needs of my customers.
Best Django 'CMS' component for integration into existing site
[ "", "python", "django", "content-management-system", "" ]
I've seen a couple of web pages say that `a = b || 'blah'` should assign `'blah'` to `a` if `b` is `undefined` or `null`. But if I type that into Firebug or use it in code, it complains that `b` is not defined, at the list on FF3/win. Any hints? Edit: I'm looking for the case where `b` may not exist at all. For example, a DOM node without an `id`.
I think you're looking for this: ``` var a = typeof b == 'undefined' ? 'blah' : b; ```
If b existed, and was false, null, etc, then it works in the way that you would expect. All you'll need to do is on the line above that, put `var b = null`; This makes sense if you think about it. It basically does something like this... ``` a = function(){ if(b){return b;} else{ return 'blah' } }(); ``` Note it is checking that the value of b is truthy... if b doesn't exist, you get an exception. ### Regarding Undefined variables "Undefined" in javascript doesn't mean 'variable doesn't exist'. It means "the value of the variable is the special value of `undefined`". Example: ``` alert(nosuchvariable); => throws exception var somevariable; // note it's never assigned alert(somevariable); => This alerts with 'undefined' ``` ### Regarding Checking if variables exist. So if we try to read `b` and there is no such variable as b, we get an exception. If we're trying to find out if b is defined, then this isn't helpful. You can see if global variables exist by checking the top-level `window` object. All global variables are actually just fields in the `window` object. Example: ``` foo = 'Hello'; alert( window.foo ); => alerts 'Hello' ``` Because you know the window object already exists, you can check it's fields. Checking for fields that don't exist in javascript will give you `undefined` and won't crash, so you can then do the coalesce, or put the `undefined` in a variable or whatever For **local** variables (things declared with `var`), ~~you can't check for their existence.~~ they don't "live" anywhere in the way that global variables "live" in the window object, and any normal attempt to reference one will cause an exception: eg: ``` alert(a); => exception because a is meaningless alert(d45pwiu4309m9rv43); => exception because that is equally meaningless ``` There is however one exception (that I know of, thanks J c in the comments), the `typeof` operator. If you try and get the type of something that doesn't exist, it *won't* crash, it will return *the string* `"undefined"`. This gives you a way of checking for non-existent local variables. eg: ``` if( typeof(djfsd) === "undefined" ) alert('no such variable'); ``` ### Regarding DOM elements that don't exist There have been several comments mentioning DOM elements without ID's and so forth... The fact that it's a DOM element isn't really relevant. Think of the DOM as a database or a file, and an element as a row in that database or word in that file. In order to *do* anything with it, you have to go searching through the database, find the right row, and pull it's data out. The data gets put into a javascript object. You then access it by manipulating that object, and maybe putting the object in a variable if you like. Example: ``` document.getElementById('foo'); ``` this goes into the dom and looks for an element with an ID of 'foo'. If it finds one, it puts some information about that element into a javascript object, and then hands that object back to you. If it can't find the element, it will hand you back `null`, but all the normal rules still apply (you can stick the `null` in a variable, or whatever). It doesn't affect the coalesce at all.
Why doesn't || seem to work as a coalesce/default operator in JavaScript?
[ "", "javascript", "firefox-3", "coalesce", "" ]
I've just started looking into M-V-VM for a WPF application. Everything makes sense so far besides this particular issue... I have a ViewModel I'll call Search. This ViewModel binds to a datagrid and lists results of items. Now, I have a command that needs to bring up **another view**, the item's details. Putting the logic to show another view in the Search View doesn't seem right, it's not testable at all. Here is my ViewModel implementation, which is not testable... ``` public class SearchViewModel { public void SelectItem() { // I want to call the DetailsView from here // this seems wrong, and is untestable var detailsView = new DetailsView(); detailsView.Show(); } } ``` **Where does the logic to show a view from a ViewModel method go in this pattern?**
Views should never be instantiated anywhere "below" the UI layer. VMs exist below that realm, therefore this is not the place to put that logic (as you've already realized). There will almost always be some UI level event that will indicate the need to create the view. In your example, it might be a row (double) click event on the datagrid. That would be the place to new-up and show your DetailsView window.
As Kiff noted: > Views should never be instantiated anywhere "below" the UI layer. VMs exist below that realm, therefore this is not the place to put that logic (as you've already realized). > > There will almost always be some UI > level event that will indicate the > need to create the view. In your > example, it might be a row (double) > click event on the datagrid. That > would be the place to new-up and show > your DetailsView window. You have to realize that M-V-VM is slightly different than other patterns like MVC or MVP. The ViewModel has no direct knowledge of the UI. Opening another view is a view-specific function. The View Model should care less what or how many views are using it's data. I most likely would never open the view via a command. [![alt text](https://web.archive.org/web/20060624141450/http://blogs.msdn.com:80/johngossman/attachment/576163.ashx)](https://web.archive.org/web/20060624141450/http://blogs.msdn.com:80/johngossman/attachment/576163.ashx)
M-V-VM Design Question. Calling View from ViewModel
[ "", "c#", "wpf", "mvvm", "" ]
How do I pass an array I have created on the server side onto the client side for manipulation by Javascript? Any pseudo code will help
You'll need to embed it as a javascript array declaration into the page. There are a number of ways to do this, but it generally means turning the array into text that you write to the page, probably using the ClientScriptManager. I'm hoping for better javascript integration in a upcoming verison of ASP.Net. Moving the *value* of a server variable —any server variable— to the client ought to be supported with a simple, one-line function call. Not the back-flips we need right now.
Convert it to string representation of a javascript array ("['val1','val2','val3']") and shove it into the value field of a hidden input.
How to pass array from Asp.net server side to Javascript function on client side
[ "", "asp.net", "javascript", "" ]
In C the following horror is valid: ``` myFunc() { return 42; // return type defaults to int. } ``` But, what about in C++? I can't find a reference to it either way... My compiler (Codegear C++Builder 2007) currently accepts it without warning, but I've had comments that this ***is*** an error in C++.
It's *ill-formed* in C++. Meaning that it doesn't compile with a standard conforming compiler. Paragraph **7.1.5/4** in Annex C of the Standard explains the change "Banning implicit int".
Implicit return types are valid in C89, but a lot of compilers warn about it. They are not valid in C++, nor in C99.
Does C++ allow default return types for functions?
[ "", "c++", "c", "" ]
I have a Linq to Entities query like this one: ``` var results = from r in entities.MachineRevision where r.Machine.IdMachine == pIdMachine && r.Category == (int)pCategory select r; ``` Usually, I use the code below to check if some results are returned: ``` if (results.Count() > 0) { return new oMachineRevision(results.First().IdMachineRevision); } ``` However, I'm getting **NotSupportedException** in the **if** condition. The error message is: *Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.* Note that **pCategory** is an Enum type.
**EDIT**: Based on your update, the error may be related to an enum in your entity class. See this [blog entry](http://gmontrone.com/problem-with-casting-enums-in-linq-to-entities/) for more information and a work-around. I'm leaving my original answer as an improvement on your query syntax. Try doing the selection of the first entity in the query itself using FirstOrDefault and then check if the result is null. ``` int compareCategory = (int)pCategory; // just a guess var result = (from r in entities.MachineRevision where r.Machine.IdMachine == pIdMachine && r.Category == compareCategory select r).FirstOrDefault(); if (result != null) { return new oMachineRevision(result.IdMachineRevision); } ```
Why not just use FirstOrDefault() instead, and check for null? I can't see the benefit in querying for the count and then taking the first element.
Linq returns list or single object
[ "", "c#", "linq", ".net-3.5", "enums", "" ]
Can you guys tell me the difference between them? By the way, is there something called C++ library or C library?
The `C++ Standard Library` and `C Standard Library` are the libraries that the C++ and C Standard define that is provided to C++ and C programs to use. That's a common meaning of those words, i haven't ever seen another definition of it, and C++ itself defines it as this: > The *C++ Standard Library* provides an extensible framework, and contains components for: language support, diagnostics, general utilities, strings, locales, containers, iterators, algorithms, numerics, and input/output. The language support components are required by certain parts of the C++ language, such as memory allocation (5.3.4, 5.3.5) and exception processing (clause 15). `C++ Runtime Library` and `C Runtime Library` aren't so equally used. Some say a runtime library is the part that a program uses at *runtime* (like, the code that implements `std::type_info` or the code supporting signal handlers) as opposed to stuff that they only use at compile time (like macro definitions). Other people say that a runtime library is one that is linked to a program at load time dynamically, as opposed to statically at compile time, though this use is very seldom. shared library or dynamically linked library are better terms for that. `C++ Library` and `C Library` are very broad terms. They just mean that a library is written in C++ and/or C. The above is not only limited to C++ and/or C. There are python libraries and there is a python [Standard Library](http://docs.python.org/library/) too.
According to <https://en.wikibooks.org/wiki/C_Programming/Standard_libraries#Common_support_libraries>, there is a very important difference between Standard Library and Runtime Library. While the Standard Library defines functions that are (always) available to the programmer (but not part of the (initial) specification of the programming language, at least in C), the Runtime Library contains functions that are necessary to actually run a program on a given platform (and are platform-specific / vendor-specific). For example, printf() is part of the C Standard Library, while program startup (which is in many cases invisible to the programmer) is implemented in the Runtime Library. So for example, you could write a C-program which does not use the Standard Library but you always need the Runtime Library because otherwise, your program could not be executed. But to be honest, this would be of little use because a C-program without the Standard Library could not do input/output so it could not tell you something about its impressive results. What leads to confusion concerning the difference between those two is: 1. In every case, the Runtime Library is needed/used and in (nearly) all cases, the Standard Library is used. Furthermore, the Standard Library could be dependent on the Runtime Library and is most probably developed by the same vendor. Therefore, the distinction is not clear and in most cases not necessary. 2. Microsoft has put the C Standard Library and C Runtime Library together and just calls it C Run-Time Library.
Difference between C/C++ Runtime Library and C/C++ Standard Library
[ "", "c++", "c", "" ]
I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities. Does anyone have a good example of this?
Here's another more recent snippet (July 2008, updated Dec 2015): [Authentication Against Active Directory (LDAP) over SSL](http://djangosnippets.org/snippets/901/)
The link provided by Jeff indeed works though it assumes you have a you have a default group where users are added to. I simply replaced: ``` group=Group.objects.get(pk=1) ``` by ``` group,created=Group.objects.get_or_create(name="everyone") ``` If you want tighter integration & more features there is also [django-auth-ldap](http://packages.python.org/django-auth-ldap/) which gives you you more control over how ldap users/group are mapped onto django users/groups. For debugging the ldap connection I found [this blog post](http://www.djm.org.uk/using-django-auth-ldap-active-directory-ldaps/) useful, in particular the command for testing the ldap connection with ldap-utils: ``` ldapsearch -H ldaps://ldap-x.companygroup.local:636 -D "CN=Something LDAP,OU=Random Group,DC=companygroup,DC=local" -w "p4ssw0rd" -v -d 1 ``` If you are using ssl there is also the issue of getting hold of a certificate will play nice with. Either you extract it from the server, or you can follow [these instructions](http://support.microsoft.com/kb/321051) to generate your own.
Using AD as authentication for Django
[ "", "python", "django", "active-directory", "ldap", "" ]
I've been reading [Filthy Rich Clients](http://filthyrichclients.org/) lately and noticed that, although the version of Java is 6, there is no mention of the Concurrent Framework. So, they talk about java.util.Timer and javax.swing.Timer but not about the ExecutorService. I read about the advantages of ExecutorService in the question "[Java Timer vs ExecutorService](https://stackoverflow.com/questions/409932/java-timer-vs-executorservice)" and decided to use the latter over the former. But the book talks about javax.swing.Timer and it's advantages of being specific for Swing development. So, does this mean that, for Swing development (animating buttons etc.), javax.swing.Timer is still a better choice or is there a relevant class in the new Concurrent Framework that replaces it?
Well the Swing Timer at least runs on the EDT so you do not have to wrap everything with calls to invokeLater. It also ties nicely in with Swing as it uses Actions, ActionListeners and other Swing related classes. I'd stick with Swing Timer for Swing related tasks and use the new concurrent package for things that does not involve updating the GUI. Have a look at [Using Timers in Swing Applications](http://java.sun.com/products/jfc/tsc/articles/timer/) as it might contain more information to swing (sorry) the decision.
I would say that for simple swing related stuff the better choice is the `javax.swing.Timer` because of the advantages mentioned [here](http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html). > Note that the Swing timer's task is > performed in the event dispatch > thread. This means that the task can > safely manipulate components, but it > also means that the task should > execute quickly. On the other side, if you need to perform non-swing related or more complex/lengthy processing operations, the `ExecutorService` is very robust and is definitely the way to go.
ExecutorService vs Swing Timer
[ "", "java", "swing", "timer", "" ]
Is there any way to get a String[] with the roles a user has in the JSP or Servlet? I know about request.isUserInRole("role1") but I also want to know all the roles of the user. I searched the servlet source and it seems this is not possible, but this seems odd to me. So... any ideas?
Read in all the possible roles, or hardcode a list. Then iterate over it running the isUserInRole and build a list of roles the user is in and then convert the list to an array. ``` String[] allRoles = {"1","2","3"}; HttpServletRequest request = ... (or from method argument) List userRoles = new ArrayList(allRoles.length); for(String role : allRoles) { if(request.isUserInRole(role)) { userRoles.add(role); } } // I forgot the exact syntax for list.toArray so this is prob wrong here return userRoles.toArray(String[].class); ```
The answer is messy. First you need to find out what type request.getUserPrincipal() returns in your webapp. ``` System.out.println("type = " + request.getUserPrincipal().getClass()); ``` Let's say that returns org.apache.catalina.realm.GenericPrincipal. Then cast the result of getUserPrincipal() to that type and use the methods it provides. ``` final Principal userPrincipal = request.getUserPrincipal(); GenericPrincipal genericPrincipal = (GenericPrincipal) userPrincipal; final String[] roles = genericPrincipal.getRoles(); ``` I said it was going to be messy. It's not very portable either.
How to get user roles in a JSP / Servlet
[ "", "java", "authentication", "jsp", "servlets", "jboss", "" ]
I am looking out for a good open source Reporting tool/framework for windows based application (WPF). The database I am using is sql server 2005. The typical reports format which I am interested is for e.g. Trial balance, balance sheet, etc (typical banking / finance reporting application). There should be good support for charting as well. If anyone has any experience with reporting for WPF application, your inputs will be highly appreciated.
Since this may form part of the answer, I thought of putting this in the answer section. I just found this series of article [WPF multipage reports](https://web.archive.org/web/20121214141444/http://janrep.blog.codeplant.net/post/WPF-Multipage-Reports-Part-I.aspx) **(note: original link dead, replaced with Wayback Machine link)**. Thought of putting this here as this may benefit some other learner. This article walks through creating a reporting framework for LOB Apps. As the saying goes "A Bird in the hand is worth two in the Bush", I will have a deep look at this until something else comes up with something better :)
Take a look at <http://wpfreports.codeplex.com/>
Good open source Reporting tool/framework for WPF (C#)
[ "", "c#", "wpf", "open-source", "reporting", "" ]
I have a vector with 1000 "nodes" ``` if(count + 1 > m_listItems.capacity()) m_listItems.reserve(count + 100); ``` The problem is I also clear it out when I'm about to refill it. ``` m_listItems.clear(); ``` The capacity doesn't change. I've used the resize(1); but that doesn't seem to alter the capacity. So how does one change the reserve?
``` vector<Item>(m_listItems).swap(m_listItems); ``` will shrink `m_listItems` again: <http://www.gotw.ca/gotw/054.htm> (Herb Sutter) If you want to clear it anyway, swap with an empty vector: ``` vector<Item>().swap(m_listItems); ``` which of course is way more efficient. (Note that swapping vectors basicially means just swapping two pointers. Nothing really time consuming going on)
You can swap the vector as others have suggested, and as described in <http://www.gotw.ca/gotw/054.htm> but be aware that it is *not* free, you're performing a copy of every element, because the vector has to allocate a new, smaller, chunk of memory, and copy all the old contents over. (The swap operation is essentially free, but you're swapping with a temporary initialized with a copy of the original vector's data, which is *not* free) If you know in advance how big the vector is, you should allocate the right size to begin with, so no resizing is necessary: ``` std::vector<foo> v(1000); // Create a vector with capacity for 1000 elements ``` And if you don't know the capacity in advance, why does it matter whether it wastes a bit of space? Is it worth the time spent copying every element to a new and smaller vector (which is what std::vector(v).swap(v) will do), just to save a few kilobytes of memory? Similarly, when you clear the vector, if you intend to refill it *anyway*, setting its capacity to zero seems to be an impressive waste of time. *Edit*: > baash05: what if you had 1000000 items > an 10 megs of ram. would you say > reducing the amount of overhead is > important? No. Resizing the vector requires *more* memory, temporarily, so if you're memory-limited, that might break your app. (You have to have the original vector in memory, *and* the temporary, before you can swap them, so you end up using up to twice as much RAM at that point). Afterwards, you might save a small amount of memory (up to a couple of MB), but this doesn't matter, because the excess capacity in the vector would never be accessed, so it would get pushed to the pagefile, and so not count towards your RAM limit in the first place. If you have 1000000 items, then you should initialize the vector to the correct size *in the first place*. And if you can't do that, then you'll typically be better off leaving the capacity alone. Especially since you stated that you're going to refill the vector, you should definitely reuse the capacity that has already been allocated, rather than allocating, reallocating, copying and freeing everything constantly. You have two possible cases. Either you know how many elements you need to store, or you don't. If you know, then you can create the vector with the correct size in the first place, and so you never need to resize it, or you don't know, and then you might as well keep the excess capacity, so at least it won't have to resize upwards when you refill your vector.
Changing the reserve memory of C++ vector
[ "", "c++", "memory", "stl", "vector", "resize", "" ]
I'm working with an n-Tier application using WinForm and WCF Engine Service (Windows Service) => WCF Service => Windows Form Client Application The problem is that the WinForm Client Application need to be 100% available for work even if Engine Service is down. So how can I make a disconnected architecture in order to make my winform application always available ? Thanks.
Typically you implement a queue that's internal to your application. The queue will forward the requests to the web service. In the event the web service is down, it stays queued. The queue mechanism should check every so often to see if the web service is alive, and when it is then forward everything it has stored up. Alternatively, you can go direct to the web service, then simply post it to the queue in the event of initial failure. However, the queue will still need to check on the web service every so often. **EDIT:** Just to clarify, yes all of the business logic would need to be available client side. Otherwise you would need to provide a "verify" mechanism when the client connects back up. However, this isn't a bad thing. As you should be placing the business logic in it's own assembly(ies) anyway.
Have a look at Smart Client Factory: <http://msdn.microsoft.com/en-us/library/aa480482.aspx> Just to highlight the goals (this is sniped from the above link): * They have a rich user interface that takes advantage of the power of the Microsoft Windows desktop. * They connect to multiple back-end systems to exchange data with them. * They present information coming from multiple and diverse sources through an integrated user interface, so the data looks like it came from one back-end system. * **They take advantage of local storage and processing resources to enable operation during periods of no network connectivity or intermittent network connectivity.** * They are easily deployed and configured. # Edit I'm going ansewr this with the usual CYA statement of it really depends. Let me give you some examples. Take an application which will watch the filesystem for files to be generated in any number of different formats (DB2, Flatfile, xml). The application will then import the files, displaying to the user a unified view of the document. And allow him to place e-commerce orders. In this app, you could choose to detect the files zip them up and upload to the server do the transforms (applying business logic like normalization of data etc). But then what happens if the internet connection is down. Now the user has to wait for his connection before he can place his e-Commerce order. A better solution would be to run the business rules in the client transforming the files. Now let's say, you had some business logic which would based on the order determine additional rules such as a salesman to route it to or pricing discounts...These might make sense to sit on the server. The question you will need to ask is what functionality do I need to make my application function when the server is not there. Anything thing which falls within this category will need to be client side. I've also never used Click Once deployment we had to roll our own updater which is a tale for another thread, but you should be able to send down updates preety easily. You could also code your business logic in an assembly, that you load from a URL, so while it runs client side it can be updated easily.
Disconnected Architecture With .NET
[ "", "c#", ".net", "architecture", "" ]
I need a solution to export a dataset to an excel file without any asp code (HttpResonpsne...) but i did not find a good example to do this... Best thanks in advance
I've created a class that exports a `DataGridView` or `DataTable` to an Excel file. You can probably change it a bit to make it use your `DataSet` instead (iterating through the `DataTables` in it). It also does some basic formatting which you could also extend. To use it, simply call ExcelExport, and specify a filename and whether to open the file automatically or not after exporting. I also could have made them extension methods, but I didn't. Feel free to. Note that Excel files can be saved as a glorified XML document and this makes use of that. EDIT: This used to use a vanilla `StreamWriter`, but as pointed out, things would not be escaped correctly in many cases. Now it uses a `XmlWriter`, which will do the escaping for you. The `ExcelWriter` class wraps an `XmlWriter`. I haven't bothered, but you might want to do a bit more error checking to make sure you can't write cell data before starting a row, and such. The code is below. ``` public class ExcelWriter : IDisposable { private XmlWriter _writer; public enum CellStyle { General, Number, Currency, DateTime, ShortDate }; public void WriteStartDocument() { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\""); _writer.WriteStartElement("ss", "Workbook", "urn:schemas-microsoft-com:office:spreadsheet"); WriteExcelStyles(); } public void WriteEndDocument() { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteEndElement(); } private void WriteExcelStyleElement(CellStyle style) { _writer.WriteStartElement("Style", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteAttributeString("ID", "urn:schemas-microsoft-com:office:spreadsheet", style.ToString()); _writer.WriteEndElement(); } private void WriteExcelStyleElement(CellStyle style, string NumberFormat) { _writer.WriteStartElement("Style", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteAttributeString("ID", "urn:schemas-microsoft-com:office:spreadsheet", style.ToString()); _writer.WriteStartElement("NumberFormat", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteAttributeString("Format", "urn:schemas-microsoft-com:office:spreadsheet", NumberFormat); _writer.WriteEndElement(); _writer.WriteEndElement(); } private void WriteExcelStyles() { _writer.WriteStartElement("Styles", "urn:schemas-microsoft-com:office:spreadsheet"); WriteExcelStyleElement(CellStyle.General); WriteExcelStyleElement(CellStyle.Number, "General Number"); WriteExcelStyleElement(CellStyle.DateTime, "General Date"); WriteExcelStyleElement(CellStyle.Currency, "Currency"); WriteExcelStyleElement(CellStyle.ShortDate, "Short Date"); _writer.WriteEndElement(); } public void WriteStartWorksheet(string name) { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteStartElement("Worksheet", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteAttributeString("Name", "urn:schemas-microsoft-com:office:spreadsheet", name); _writer.WriteStartElement("Table", "urn:schemas-microsoft-com:office:spreadsheet"); } public void WriteEndWorksheet() { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteEndElement(); _writer.WriteEndElement(); } public ExcelWriter(string outputFileName) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; _writer = XmlWriter.Create(outputFileName, settings); } public void Close() { if (_writer == null) throw new InvalidOperationException("Already closed."); _writer.Close(); _writer = null; } public void WriteExcelColumnDefinition(int columnWidth) { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteStartElement("Column", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteStartAttribute("Width", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteValue(columnWidth); _writer.WriteEndAttribute(); _writer.WriteEndElement(); } public void WriteExcelUnstyledCell(string value) { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteStartElement("Cell", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteStartElement("Data", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "String"); _writer.WriteValue(value); _writer.WriteEndElement(); _writer.WriteEndElement(); } public void WriteStartRow() { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteStartElement("Row", "urn:schemas-microsoft-com:office:spreadsheet"); } public void WriteEndRow() { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteEndElement(); } public void WriteExcelStyledCell(object value, CellStyle style) { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); _writer.WriteStartElement("Cell", "urn:schemas-microsoft-com:office:spreadsheet"); _writer.WriteAttributeString("StyleID", "urn:schemas-microsoft-com:office:spreadsheet", style.ToString()); _writer.WriteStartElement("Data", "urn:schemas-microsoft-com:office:spreadsheet"); switch (style) { case CellStyle.General: _writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "String"); break; case CellStyle.Number: case CellStyle.Currency: _writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "Number"); break; case CellStyle.ShortDate: case CellStyle.DateTime: _writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "DateTime"); break; } _writer.WriteValue(value); // tag += String.Format("{1}\"><ss:Data ss:Type=\"DateTime\">{0:yyyy\\-MM\\-dd\\THH\\:mm\\:ss\\.fff}</ss:Data>", value, _writer.WriteEndElement(); _writer.WriteEndElement(); } public void WriteExcelAutoStyledCell(object value) { if (_writer == null) throw new InvalidOperationException("Cannot write after closing."); //write the <ss:Cell> and <ss:Data> tags for something if (value is Int16 || value is Int32 || value is Int64 || value is SByte || value is UInt16 || value is UInt32 || value is UInt64 || value is Byte) { WriteExcelStyledCell(value, CellStyle.Number); } else if (value is Single || value is Double || value is Decimal) //we'll assume it's a currency { WriteExcelStyledCell(value, CellStyle.Currency); } else if (value is DateTime) { //check if there's no time information and use the appropriate style WriteExcelStyledCell(value, ((DateTime)value).TimeOfDay.CompareTo(new TimeSpan(0, 0, 0, 0, 0)) == 0 ? CellStyle.ShortDate : CellStyle.DateTime); } else { WriteExcelStyledCell(value, CellStyle.General); } } #region IDisposable Members public void Dispose() { if (_writer == null) return; _writer.Close(); _writer = null; } #endregion } ``` Then you can export your `DataTable` using the following: ``` public static void ExcelExport(DataTable data, String fileName, bool openAfter) { //export a DataTable to Excel DialogResult retry = DialogResult.Retry; while (retry == DialogResult.Retry) { try { using (ExcelWriter writer = new ExcelWriter(fileName)) { writer.WriteStartDocument(); // Write the worksheet contents writer.WriteStartWorksheet("Sheet1"); //Write header row writer.WriteStartRow(); foreach (DataColumn col in data.Columns) writer.WriteExcelUnstyledCell(col.Caption); writer.WriteEndRow(); //write data foreach (DataRow row in data.Rows) { writer.WriteStartRow(); foreach (object o in row.ItemArray) { writer.WriteExcelAutoStyledCell(o); } writer.WriteEndRow(); } // Close up the document writer.WriteEndWorksheet(); writer.WriteEndDocument(); writer.Close(); if (openAfter) OpenFile(fileName); retry = DialogResult.Cancel; } } catch (Exception myException) { retry = MessageBox.Show(myException.Message, "Excel Export", MessageBoxButtons.RetryCancel, MessageBoxIcon.Asterisk); } } } ```
The following site demonstrates how to export a DataSet (or DataTable or List<>) into a "**genuine**" Excel 2007 .xlsx file. It uses the *OpenXML* libraries, so you **don't** need to have Excel installed on your server. [C# ExportToExcel library](https://www.codeproject.com/Articles/692121/Csharp-Export-data-to-Excel-using-OpenXML-librarie) All of the source code is provided, **free of charge**, along with instructions using it with ASP.NET, ASP.NET Core 2+ or regular C#. It's *very* easy to add to your own applications, you just need to call one function, passing in an Excel filename, and your data source: ``` DataSet ds = CreateSampleData(); string excelFilename = "C:\\Sample.xlsx"; CreateExcelFile.CreateExcelDocument(ds, excelFilename); ``` Hope this helps.
c# (WinForms-App) export DataSet to Excel
[ "", "c#", "winforms", "excel", "dataset", "export", "" ]
I'm trying to add a class to the selected radio input and then remove that class when another radio of the same type is selected The radio buttons have the class 'radio\_button' but i can't get the class to change with the below code. ``` jQuery(".radio_button").livequery('click',function() { $('input.radio_button :radio').focus(updateSelectedStyle); $('input.radio_button :radio').blur(updateSelectedStyle); $('input.radio_button :radio').change(updateSelectedStyle); } function updateSelectedStyle() { $('input.radio_button :radio').removeClass('focused'); $('input.radio_button :radio:checked').addClass('focused'); } ```
Tre problem is caused by one extra space in your selectors. Instead of: ``` $('input.radio_button :radio') ``` you wanted to write: ``` $('input.radio_button:radio') ```
You might also want to take advantage of jQuery's chainability to reduce the amount of work you're doing. (Rather than re-finding these buttons over and over again.) Something like this: ``` jQuery(".radio_button").livequery('click',function() { $('input.radio_button:radio') .focus(updateSelectedStyle) .blur(updateSelectedStyle) .change(updateSelectedStyle); }); function updateSelectedStyle() { $('input.radio_button:radio') .removeClass('focused') .filter(':checked').addClass('focused'); } ```
"Pin" a class to the selected radio button?
[ "", "javascript", "jquery", "button", "radio-button", "" ]
I'm working on a new project and I'm using the repository pattern, I have my repository that pulls the data from the database and a "service" class which uses the repository and does all the business logic. something similar to the following; ``` public class UserRepository : IUserRepository { public IQueryable<User> GetUsers() { // do stuff } } public class UserService { public IList<User> GetUserById { var rep = new UserRepository(); var users = rep.GetUsers(); // do business logic return users.ToList(); } } ``` Would you test both the UserService and the UserRepository or do you think testing just the Service would suffice? I figure since the service is using the repository it should be fun, but it does kill code coverage.
You should test them both, because it's possible that someday there will be other clients of UserRepository than UserService, and those clients may use UserRepository differently than UserService.
test the features that you require: * some features may reside in one class * some may reside in the other class * some may require both classes from your description it looks like you get to define the features, so you can pretty much justify testing anything you like ;-) if you're looking for minimal TDD efficiency, **test only the current feature, and move on**. *Code coverage is not relevant* for TDD; that is a unit-testing metric (of questionable value) [let the downvoting begin! ;-)]
TDD - How much do you test?
[ "", "c#", ".net", "unit-testing", "tdd", "" ]
I have a simple html page with a div. I am using jQuery to load the contents of an aspx app into the "content" div. Code looks like this: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"> </script> <script type="text/javascript"> jQuery.noConflict(); </script> </head> <body> <div id="content"> <div id="loading"> <div class="loading-indicator">Loading...</div> </div> </div> </body> <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#content").load("default.aspx"); }); </script> </html> ``` The problem is default.aspx uses shadowbox and other javascript libraries. When that code tries to execute on default.aspx it acts like the js source files were not loaded. I check in firebug and the js files are there (no 404 or anything). Anyone know what I'm missing? As you can see I used the jQuery noConflict function because I thought the use of $ might be conflicting with the other libraries but no help there...
Is the code that is not executing rendered out as script blocks, I understand the libraries loaded but any script blocks or inline javascript will not execute when loaded dynamically like that. You have to come up witha solution that will evaluate the script blocks returned for any of it to be valid. I'll see if I can dig an example from prototype, I remember them having one. UPDATE: This is straight from prototype... ``` ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>' extractScripts: function() { var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); return (this.match(matchAll) || []).map(function(scriptTag) { return (scriptTag.match(matchOne) || ['', ''])[1]; }); } evalScripts: function() { return this.extractScripts().map(function(script) { return eval(script) }); } ``` Of course you can simplify that for your needs, but when a page is returned dynamically you have to manually evaluate all scripts as the browser will not evaluate script injected into the element automagically.
I have code doing this, it might be more verbose than is needed, but nested js files shouldn't be a problem. ``` jQuery.get('default.aspx', null, function(data) { $('#default').append(data); }, 'html'); ```
Using jQuery .load breaks links to other library resources?
[ "", "javascript", "jquery", "shadowbox", "" ]
I was looking at ways to authenticate users in a web app, but in a way where the main web app doesn't need to process the password. Something like OpenId, but the authentication server would definitely need to be hosted on an intranet, internet services can't be accessed by the application server. My environement is pretty much Java web apps, but it would be interesting to connect the system to other type of apps as well.
You could [run your own OpenID server](http://wiki.openid.net/Run_your_own_identity_server). You didn't mention your environment, but another option is to use Windows Authentication with Active Directory if you're running in a Windows domain situation.
Do you want to have single sign-on between applications? (That is, if the same user is using more than one of your web apps, if they've logged in on one, they don't need to log in again when they move to another one.) If so, there are several options, The one I've used extensively is [CAS](http://www.ja-sig.org/products/cas/) (the Central Authentication Service), which is widely used in educational institutions. It has a variety of client libraries for many languages, and the server part is Java. This can of course be combined with LDAP to give both single sign-on and a single repository of user credentials.
Best way to authenticate users in a web application
[ "", "java", "security", "authentication", "web-applications", "openid", "" ]
I'm looking for a best way to implement common Windows keyboard shortcuts (for example `Ctrl`+`F`, `Ctrl`+`N`) in my [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) application in C#. The application has a main form which hosts many child forms (one at a time). When a user hits `Ctrl`+`F`, I'd like to show a custom search form. The search form would depend on the current open child form in the application. I was thinking of using something like this in the *ChildForm\_KeyDown* event: ``` if (e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control) // Show search form ``` But this doesn't work. The event doesn't even fire when you press a key. What is the solution?
You probably forgot to set the form's [KeyPreview](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx) property to True. Overriding the [ProcessCmdKey()](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.processcmdkey.aspx) method is the generic solution: ``` protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == (Keys.Control | Keys.F)) { MessageBox.Show("What the Ctrl+F?"); return true; } return base.ProcessCmdKey(ref msg, keyData); } ```
On your Main form 1. Set `KeyPreview` to True 2. Add KeyDown event handler with the following code ``` private void MainForm_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.N) { SearchForm searchForm = new SearchForm(); searchForm.Show(); } } ```
Best way to implement keyboard shortcuts in a Windows Forms application?
[ "", "c#", "winforms", "keyboard-shortcuts", "" ]
What is the purpose of `__builtin_offsetof` operator (or `_FOFF` operator in Symbian) in C++? In addition what does it return? Pointer? Number of bytes?
It's a builtin provided by the GCC compiler to implement the `offsetof` macro that is specified by the C and C++ Standard: [GCC - offsetof](http://gcc.gnu.org/onlinedocs/gcc/Offsetof.html#Offsetof) It returns the offset in bytes that a member of a POD struct/union is at. Sample: ``` struct abc1 { int a, b, c; }; union abc2 { int a, b, c; }; struct abc3 { abc3() { } int a, b, c; }; // non-POD union abc4 { abc4() { } int a, b, c; }; // non-POD assert(offsetof(abc1, a) == 0); // always, because there's no padding before a. assert(offsetof(abc1, b) == 4); // here, on my system assert(offsetof(abc2, a) == offsetof(abc2, b)); // (members overlap) assert(offsetof(abc3, c) == 8); // undefined behavior. GCC outputs warnings assert(offsetof(abc4, a) == 0); // undefined behavior. GCC outputs warnings ``` @Jonathan provides a nice example of where you can use it. I remember having seen it used to implement intrusive lists (lists whose data items include next and prev pointers itself), but i can't remember where it was helpful in implementing it, sadly.
As @litb points out and @JesperE shows, offsetof() provides an integer offset in bytes (as a `size_t` value). When might you use it? One case where it might be relevant is a table-driven operation for reading an enormous number of diverse configuration parameters from a file and stuffing the values into an equally enormous data structure. Reducing enormous down to SO trivial (and ignoring a wide variety of necessary real-world practices, such as defining structure types in headers), I mean that some parameters could be integers and others strings, and the code might look faintly like: ``` #include <stddef.h> typedef stuct config_info config_info; struct config_info { int parameter1; int parameter2; int parameter3; char *string1; char *string2; char *string3; int parameter4; } main_configuration; typedef struct config_desc config_desc; static const struct config_desc { char *name; enum paramtype { PT_INT, PT_STR } type; size_t offset; int min_val; int max_val; int max_len; } desc_configuration[] = { { "GIZMOTRON_RATING", PT_INT, offsetof(config_info, parameter1), 0, 100, 0 }, { "NECROSIS_FACTOR", PT_INT, offsetof(config_info, parameter2), -20, +20, 0 }, { "GILLYWEED_LEAVES", PT_INT, offsetof(config_info, parameter3), 1, 3, 0 }, { "INFLATION_FACTOR", PT_INT, offsetof(config_info, parameter4), 1000, 10000, 0 }, { "EXTRA_CONFIG", PT_STR, offsetof(config_info, string1), 0, 0, 64 }, { "USER_NAME", PT_STR, offsetof(config_info, string2), 0, 0, 16 }, { "GIZMOTRON_LABEL", PT_STR, offsetof(config_info, string3), 0, 0, 32 }, }; ``` You can now write a general function that reads lines from the config file, discarding comments and blank lines. It then isolates the parameter name, and looks that up in the `desc_configuration` table (which you might sort so that you can do a binary search - multiple SO questions address that). When it finds the correct `config_desc` record, it can pass the value it found and the `config_desc` entry to one of two routines - one for processing strings, the other for processing integers. The key part of those functions is: ``` static int validate_set_int_config(const config_desc *desc, char *value) { int *data = (int *)((char *)&main_configuration + desc->offset); ... *data = atoi(value); ... } static int validate_set_str_config(const config_desc *desc, char *value) { char **data = (char **)((char *)&main_configuration + desc->offset); ... *data = strdup(value); ... } ``` This avoids having to write a separate function for each separate member of the structure.
what is the purpose and return type of the __builtin_offsetof operator?
[ "", "c++", "offsetof", "" ]
I just purchased *C++ GUI Programming with Qt4* and after reading the code samples in this book I'm beginning to realize that my knowledge of C++ is incomplete. I learned C++ two years ago from online tutorials and a couple of ebooks I downloaded, and it turns out none of these resources were good enough. Since then I haven't touched the language and have been using Python instead. Now I'm thinking of purchasing a good book on C++ that covers advanced topics, and the one I have in mind is Bruce Eckel's *Thinking in C++* (both volumes). I know they are available for free on the web, but I really can't stand reading books on a laptop screen. Since C++0x might be out pretty soon, is it wise to go ahead and spend cash on these books? Will C++0x break backwards compatibility? Volume 2 covers features like multithreading, templates etc. Would any of these features change significantly in C++0x?
I wouldn't hold my breath for C++0x. I doubt it will be out by the end of this decade. Even when it will be out, you should probably count a year or so for compilers to implement it. Learn the fundamentals now, and it should be relatively easy for you to learn most of the new features when the standard is out. The Standards Committee is known for its efforts to maintain backward compatibility. I personally check with the evolution of the standard from time to time, just out of curiosity. Subscribe to Herb Sutter's [blog](http://herbsutter.wordpress.com/) [feed](http://herbsutter.wordpress.com/feed/) and look for Standard updates. My personal favourite advanced C++ book is Bjarne Stroustrup's The C++ Programming Language, 3e. It is the one single C++ book from which I think I learnt the most, with respect to language and STL details. Scott Meyers' books helped clarify a lot of things too. Meyers writes in a very readable language (English, I believe), and often what would happen is that I'd read an entire Item from Meyers' book, and then find the same information in Stroustrup's book condensed into a single sentence or so. That is to say Meyers' books are extremely useful in getting your attention to interesting details. As for the changes I expect for threading, I think there going to be two new libraries for this purpose in the standard. Concepts are an even bigger change coming, and they are somewhat related to templates. Up until now we had concepts in the STL, but these were *conventions*; an algorithm would make assumptions about a type you pass to a template, and you'd know to pass the correct "type of type" because of the conventions. This implied terribly error messages, the STL template errors we all know and "love". Concepts will help solve these. There are other improvements (complexities) to the language. Herb Sutter talks about them a lot.
It is certainly wise to buy the book. C++1x will hardly break with previous code. Nearly everything you learn is also possible with the next C++, and it will greatly help you understand the need of *why* C++1x will introduce what feature. For example, why will it have *variadic templates*, and why those *concepts*?
Is it Wise to Spend Cash on a C++ Book Keeping in View the Upcoming C++0x?
[ "", "c++", "c++11", "" ]
I'm calling a SSIS package using LoadPackage(...). Is it possible to make this call an Asynchronous call?
Yes, use an asynchronous delegate, as demostrated here: <http://msdn.microsoft.com/en-us/library/h80ttd5f.aspx>
If you just want it to run in the background then yes, you can either spool up a thread or call some T-SQL to dynamically create a job (and remove it again afterwards). If you want to run it asynchronously and want a callback when it's done, then I think you're out of luck unfortunately.
Calling SSIS package Asynchronously
[ "", "c#", ".net", "ssis", "asynchronous", "" ]
I need a template like this, which work perfectly ``` template <typename container> void mySuperTempalte (const container myCont) { //do something here } ``` then i want to specialize the above template for std::string so i came up with ``` template <typename container> void mySuperTempalte (const container<std::string> myCont) { //check type of container //do something here } ``` which doesnt't work, and throws an error. I would like to make the second example work and then IF possible i would like to add some code in the template to check if a std::vector/std::deque/std::list was used, to do something differently in each case. So i used templates because 99% of the code is the same for both vectors and deques etc.
If I am understanding your problem correctly you have an algorithm that will work for STL containers vector, deque etc but are trying to write a template specialisation for string. If this is the case then you can write the generalised templated method that you defined in your question:- ``` template<typename container> void mySuperTempalte( const container &myCont ) { // Implement STL container code } ``` Then for your string specialisation you declare:- ``` template<> void mySuperTempalte( const container<std::string> &myCont ) { // Implement the string code } ``` For any other specialisation just change the type declaration for myCont. If you really need to do this for the vector and deque containers then make the template parameter the parameter for the type in that container rather than the container itself as Sep suggested. ``` template<typename C> void mySuperTempalte( const std::vector<C> &myCont) { // check type of container // do something here } ``` It's worth trying to avoid this by making your first implementation work with all STL containers to make your life easier, then you only need the specialisation for the string class. Even consider converting your string to a vector to avoid the specialisation all together. On a side note, I've changed the container parameter to a const reference, I assume this is what you want, as you declare the object const anyway, this way you avoid a copy.
To specialize: ``` template<> void mySuperTempalte<std:string>(const std::string myCont) { //check type of container //do something here } ``` To specialize for vector: ``` template<typename C> void mySuperTempalte (std::vector<C> myCont) { //check type of container //do something here } ``` To specialize for deque: ``` template<typename C> void mySuperTempalte (std::deque<C> myCont) { //check type of container //do something here } ```
simple C++ templates suited for STL Containers
[ "", "c++", "templates", "stl", "containers", "" ]
This is a(n) historical question, not a comparison-between-languages question: [This article from 2005](http://tomayko.com/writings/no-rails-for-python) talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. **Why, historically speaking, did this happen for Ruby but not for Python?** (or did it happen, and that framework is Django?) Also, the hypothetical questions: **would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?** **[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]** **Edit:** Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one **in terms of popularity** is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.
As I see it, Rails put Ruby on the map. The simple fact is that before Rails, Ruby was a minor esoteric language, with very little adoption. Ruby owes its success to Rails. As such, Rails has a central place in the Ruby ecosystem. As slim points out, there are other web frameworks, but it's going to be very difficult to overtake Rails as the leader. Python on the other hand, had a very different adoption curve. Before Rails, Python was much more widely used than Ruby, and so had a number of competing web frameworks, each slowly building their constituencies. Django has done a good job consolidating support, and becoming the leader in the Python web framework world, but it will never be the One True Framework simply because of the way the community developed.
The real technical answer is that there are three major approaches to web-development in Python: one is CGI-based, where the application is built just like an old one-off Perl application to run through CGI or FastCGI, e.g. [Trac](http://trac.edgewall.org/); then there is [Zope](http://zope.org/), which is a bizarro overengineered framework with its own DB concept, a strange misguided through-the-web software development concept, etc. (but [Plone](http://plone.org) is still quite popular); and then there is Django (and [Turbogears](http://turbogears.org/), etc.), which is guided by the same just-the-tools-needed philosophy as Rails (it can be argued who got there first or who did it better). A lot of people would probably agree that the Django/Rails/[CakePHP](http://cakephp.org) approach is better than the older approaches, but as the older language Python has a lot more legacy frameworks that are still trying to evolve and stay relevant. These frameworks will hang on because there is already developer buy-in for them. For example, in hindsight many people would probably say that Zope (especially ZODB) was a terrible mistake, but Zope 3 is much better than Zope 2, and there are already whole companies built around Zope technologies.
Why does Ruby have Rails while Python has no central framework?
[ "", "python", "ruby-on-rails", "ruby", "frameworks", "history", "" ]
I have 2 textbox in my asp.net page and also have one hiddenfield in my asp.net page , my hiddenfield will always have numeric value like 123.00 , and in my one textbox also I will always have numeric value like 20.00 now I want to add this hiddenfield value and textbox value and display it into second textbox thru javascript I wrote the following code to do this ``` var amt = document.getElementById("txtsecond"); var hiddenamt = document.getElementById("AmtHidden").value var fee = document.getElementById("txtFirst").value; amt.value = hiddenamt + fee; ``` this should give me result like 123.00+20.00 = 143.00 but this is concatnating hiddenamt value and fee value and giving me result like 12320.00 in my first textbox can anybody suggest me what is wrong in my code and what is the right way to get desired value
``` amt.value = parseFloat(hiddenamt) + parseFloat(fee); ```
the value of an input is just a string - [convert to float](http://www.w3schools.com/jsref/jsref_parseFloat.asp) `parseFloat(foo)` in JS and you'll be fine *edited to make float as I notice it's probably important for you*
how to add 2 values of textbox in asp.net using javascript
[ "", "asp.net", "javascript", "" ]
I have a class that parses very large file (that can't fit in memory) and I'm currently utilizing the IEnumerable interface to use foreach so I can easily grab the parsed contents of the file line by line. Currently, I'm trying to write this to file using an XMLSerializer. It insists on enumerating the class and in my case, this means dumping large, parsed content of files to the XML. Is there anyway (hackish or elegant) to use this interface and still get the "expected" functionality out of a XMLSerializer? (I only call this "expected" because this seems an expected outcome if I was implementing some collection interface rather than IEnumerable. Perhaps my concepts of IEnumerable and collections is all out of whack. :( )
I managed to fix this problem without having to change my design. None of my code was relying on the IEnumerable interface, just the implementation of IEnumerable GetEnumerator() (apparently foreach doesn't check to see if IEnumerable is implemented). Just commenting out the interface in the class declaration did the trick.
Well, you could implement `IXmlSerializable` and seize full control. It isn't entirely clear (without pseudo code) what the setup is - sometimes `[XmlIgnore]` can help, but I'm not sure in this case without an example of what you have, and what you do/don't want.
How can I use IEnumerable interface and at the same time, have XMLSerializer not use GetEnumerator()?
[ "", "c#", ".net", "xml-serialization", "ienumerable", "" ]
I was looking through my code and I found a couple of extension methods that I wrote in order to remove items from a System.Collections.Generic.Stack. I was curious, so I looked at the source of Stack with Reflector and I can see that they implemented it as an array instead of a linked list and I'm just wondering why? With a linked list there would be no need to resize an internal array... Here are my extensions, any criticisms or suggestions are welcome. Thanks. ``` public static Stack<T> Remove<T>(this Stack<T> stack, T item) { Stack<T> newStack = new Stack<T>(); EqualityComparer<T> eqc = EqualityComparer<T>.Default; foreach( T newItem in stack.Reverse() ) { if( !eqc.Equals(newItem, item) ) { newStack.Push(newItem); } } return newStack; } /// <summary> /// Returns a new Stack{T} with one or more items removed, based on the given predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="stack"></param> /// <param name="fnRemove"></param> /// <returns>The new stack.</returns> /// <remarks> /// We have to turn tricks in order to save the LIFO order of the pool /// since there is no built-in remove method since they implement a Stack internally /// as an array instead of a linked list. Maybe they have a good reason, I don't know... /// /// So, to fix this I'm just using a LINQ extension method to enumerate in reverse. /// </remarks> public static Stack<T> RemoveWhere<T>(this Stack<T> stack, Predicate<T> fnRemove) { Stack<T> newStack = new Stack<T>(); foreach( T newItem in stack.Reverse() ) { /// Check using the caller's method. if( fnRemove(newItem) ) { /// It's not allowed in the new stack. continue; } newStack.Push(newItem); } return newStack; } ```
Consider the size of a `Stack<byte>` with 1,000,000 items. * With an array, size ~= 1,000,000 bytes. Usually more due to spare capacity, but probably not more than double. * With a linked list, each entry needs its own object, the data itself, and at least one reference (for a singly-linked list, which is probably all that's needed for a stack). With padding to 4 bytes, total size is likely to be ~16,000,000 bytes. Ouch. Add to that the locality of reference and the reduced GC pressure, and I think it makes perfect sense to use arrays as the underlying data structure for stacks, queues and deques - the last two would use the array as a circular buffer, of course. The only obvious downsides are the wasted "spare capacity" and the need to copy everything when that capacity runs out.
A LIFO queue (a stack) is typically most efficient with an array, because you are pushing items onto the end of the array and pulling items off the same end of the array. So an array works well, without the memory and allocation overhead of a linked list. The cost of making and resizing an array is offset by not needing to create and garbage collect the list item wrapper objects.
Why isn't System...Stack<T> implemented as a Linked List?
[ "", "c#", ".net", "data-structures", "" ]
I'm trying to come up with a clean way of sorting a set of strings based on a "sorting template". I apologize if my wording is confusing, but I can't think of a better way to describe it (maybe someone can come up with a better way to describe it after reading what I'm trying to do?). Consider the following list of strings (my "sort template", each item in the list a "command"): * [FA, TY, AK, PO, PR, ZZ, QW, BC] I'd like to use the order of the strings within that list to sort a list of those commands. For example, I'd like the following list: * [TY, PR, PR, ZZ, BC, AK] to be sorted into the following list based on the "sorting template": * [TY, AK, PR, PR, ZZ, BC] What would be a good way to acomplish this? The best idea I have yet is to use an enumeration... ``` enum Command { FA, TY, AK, PO, PR, ZZ, QW, BC }; ``` ...and do an Enum.Parse() on each command in my list I want sorted, converting that list from a list of strings into a list of Commands, which would then be sorted based on the order of the enumeration. I don't know. The enumeration seems like it would work, but is there a better way I could go about this?
You could use a `Dictionary<string, int>` to store and retrieve your sorting template tokens. However, this basically does the same as your enum (only perhaps in a slightly more readable manner), because `Enum.Parse` here could be confusing. ``` var ordering = Dictionary<string, int>(); ordering.Add("FA", 0); ordering.Add("TY", 1); // … MyList.Sort((a, b) => ordering[a].CompareTo(ordering[b])); ``` This uses an appropriate overload of the `List<T>.Sort` method to compare two elements based on their value in the `template` dictionary.
Here is a very simple way to do it! ``` List<string> template = new List<string>{ "ZD", "AB", "GR"}; List<string> myList = new List<string>{"AB", "GR", "ZD", "AB", "AB"}; myList.Sort((a, b) => template.IndexOf(a).CompareTo(template.IndexOf(b))); ```
String "Sort Template" in C#
[ "", "c#", "sorting", "" ]
I see a lot of code like this: ``` function Base() {} function Sub() {} Sub.prototype = new Base(); ``` However, if you do: ``` s = new Sub(); print(s.constructor == Sub); ``` This is false. This seems confusing to me, since s's constructor is, indeed, Sub. Is it conventional/better to do this? ``` function Base() {} function Sub() {} Sub.prototype = new Base(); Sub.prototype.constructor = Sub; ``` or does it not really matter?
'constructor' doesn't do what it looks like it does. This, in addition to its non-standardness, is a good reason to avoid using it - stick with instanceof and prototype. Technically: 'constructor' is not a property of the 's' instance, it is a property of the 'Sub' prototype object showing through. When you create the 'Sub' function in Mozilla, you get a newly-minted default Sub.prototype object which has a 'constructor' pointing back to the Sub function as a courtesy. However you then replace that prototype with a new Base(). The original default prototype with the link back to Sub is lost; instead, Sub.prototype is an instance of Base without any overriding 'constructor' property. So: ``` new Sub().constructor=== Sub.prototype.constructor=== new Base().constructor=== Base.prototype.constructor=== Base ``` ...all the way down to the most basic object whose prototype you didn't change. > Is it conventional/better to do this? When dealing with JavaScript objects/classes there is no one convention; every library's metaclass system behaves slightly differently. I haven't seen one that writes 'constructor' to each derived class manually, but it seems as good a solution as any if you really want to have the real constructor available; it will also make the code compatible with browsers/engines that don't give you 'constructor'. I'd consider giving it a different name, though, to avoid confusion with the existing and differently-behaving 'constructor' property.
If you want to test whether an object is exactly an instance of Sub use the `instanceof` operator:- ``` print(s instanceof Sub); ``` If you want to know whether an object is an instance of Sub or an instance of a sub-class of Sub use the `isPrototypeOf` method:- ``` print(Sub.prototype.isPrototypeOf(s)); ```
Convention for prototype inheritance in JavaScript
[ "", "javascript", "inheritance", "constructor", "prototype", "" ]
How can I have that functionality in my game through which the players can change their hairstyle, look, style of clothes, etc., and so whenever they wear a different item of clothing their avatar is updated with it. Should I: * Have my designer create all possible combinations of armor, hairstyles, and faces as sprites (this could be a lot of work). * When the player chooses what they should look like during their introduction to the game, my code would automatically create this sprite, and all possible combinations of headgear/armor with that sprite. Then each time they select some different armor, the sprite for that armor/look combination is loaded. * Is it possible to have a character's sprite divided into components, like face, shirt, jeans, shoes, and have the pixel dimensions of each of these. Then whenever the player changes his helmet, for example, we use the pixel dimensions to put the helmet image in place of where its face image would normally be. (I'm using Java to build this game) * Is this not possible in 2D and I should use 3D for this? * Any other method? Please advise.
3D will not be necessary for this, but the painter algorithm that is common in the 3D world might IMHO save you some work: The painter algorithm works by drawing the most distant objects first, then overdrawing with objects closer to the camera. In your case, it would boild down to generating the buffer for your sprite, drawing it onto the buffer, finding the next dependant sprite-part (i.e. armour or whatnot), drawing that, finding the next dependant sprite-part (i.e. a special sign that's on the armour), and so on. When there are no more dependant parts, you paint the full generated sprite on to the display the user sees. The combinated parts should have an alpha channel (RGBA instead of RGB) so that you will only combine parts that have an alpha value set to a value of your choice. If you cannot do that for whatever reason, just stick with one RGB combination that you will treat as transparent. Using 3D might make combining the parts easier for you, and you'd not even have to use an offscreen buffer or write the pixel combinating code. The flip-side is that you need to learn a little 3D if you don't know it already. :-) **Edit to answer comment:** The combination part would work somewhat like this (in C++, Java will be pretty similar - please note that I did not run the code below through a compiler): ``` // // @param dependant_textures is a vector of textures where // texture n+1 depends on texture n. // @param combimed_tex is the output of all textures combined void Sprite::combineTextures (vector<Texture> const& dependant_textures, Texture& combined_tex) { vector< Texture >::iterator iter = dependant_textures.begin(); combined_tex = *iter; if (dependant_textures.size() > 1) for (iter++; iter != dependant_textures.end(); iter++) { Texture& current_tex = *iter; // Go through each pixel, painting: for (unsigned char pixel_index = 0; pixel_index < current_tex.numPixels(); pixel_index++) { // Assuming that Texture had a method to export the raw pixel data // as an array of chars - to illustrate, check Alpha value: int const BYTESPERPIXEL = 4; // RGBA if (!current_tex.getRawData()[pixel_index * BYTESPERPIXEL + 3]) for (int copied_bytes = 0; copied_bytes < 3; copied_bytes++) { int index = pixel_index * BYTESPERPIXEL + copied_bytes; combined_tex.getRawData()[index] = current_tex.getRawData()[index]; } } } } ``` To answer your question for a 3D solution, you would simply draw rectangles with their respective textures (that would have an alpha channel) over each other. You would set the system up to display in an orthogonal mode (for OpenGL: `gluOrtho2D()`).
One major factor to consider is animation. If a character has armour with shoulder pads, those shoulderpads may need to move with his torso. Likewise, if he's wearing boots, those have to follow the same cycles as hid bare feet would. Essentially what you need for your designers is a [Sprite Sheet](http://sdb.drshnaps.com/sheets/Capcom/MegaMan/Customs/FireMan32bit.gif) that lets your artists see all possible frames of animation for your base character. You then have them create custom hairstyles, boots, armour, etc. based on those sheets. Yes, its a lot of work, but in most cases, the elements will require a minimal amount of redrawing; boots are about the only thing I could see really taking a lot of work to re-create since they change over multiple frames of animation. Be rutheless with your sprites, try to cut down the required number as much as possible. After you've amassed a library of elements you can start cheating. Recycle the same hair style and adjust its colour either in Photoshop or directly in the game with sliders in your character creator. The last step, to ensure good performance in-game, would be to flatten all the different elements' sprite sheets into a single sprite sheet that is then split up and stored in sprite buffers.
Customizable player avatar in a 2D Game
[ "", "java", "3d", "2d", "" ]
After writing code to populate textboxes from an object, such as: ``` txtFirstName.Text = customer.FirstName; txtLastName.Text = customer.LastName; txtAddress.Text = customer.Address; txtCity.Text = customer.City; ``` is there way in Visual Studio (or even something like Resharper) to copy and paste this code into a save function and reverse the code around the equal sign, so that it will look like: ``` customer.FirstName = txtFirstName.Text; customer.LastName = txtLastName.Text; customer.Address = txtAddress.Text; customer.City = txtCity.Text; ```
Before VS2012: * Copy and paste the original block of code * Select it again in the place you want to switch * Press Ctrl-H to get the "Replace" box up * Under "Find what" put: `{[a-zA-Z\.]*} = {[a-zA-Z\.]*};` * Under "Replace with" put: `\2 = \1;` * Look in: "Selection" * Use: "Regular expressions" * Hit Replace All With VS2012 (and presumably later) which uses .NET regular expressions: * Copy and paste the original block of code * Select it again in the place you want to switch * Press Ctrl-H to get the "Replace" box up * Under "Find what" put: `([a-zA-Z\.]*) = ([a-zA-Z\.]*);` * Under "Replace with" put: `${2} = ${1};` * Make sure that the `.*` (regular expressions) icon is selected (the third one along under the replacement textbox) * Hit Replace All
None that I know of. Of course, if you use one of the many binding approaches available, then you won't have to - the binding will do the update in both directions (including change via notifications). So for winforms: ``` txtFirstName.DataBindings.Add("Text", customer, "FirstName"); ``` etc
How can I reverse code around an equal sign in Visual Studio?
[ "", "c#", "visual-studio-2008", "" ]
I'm having difficulty getting widgets in a QDialog resized automatically when the dialog itself is resized. In the following program, the textarea resizes automatically if you resize the main window. However, the textarea within the dialog stays the same size when the dialog is resized. Is there any way of making the textarea in the dialog resize automatically? I've tried using `setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)` on the dialog itself and the two widgets within, but that seems to have no effect. I'm using Qt version 3.3.7 and PyQt version 3.5.5-29 on openSuSE 10.2, if that's relevant. ``` import sys from qt import * # The numbers 1 to 1000 as a string. NUMBERS = ("%d " * 1000) % (tuple(range(1,1001))) # Add a textarea containing the numbers 1 to 1000 to the given # QWidget. def addTextArea(parent, size): textbox = QTextEdit(parent) textbox.setReadOnly(True) textbox.setMinimumSize(QSize(size, size*0.75)) textbox.setText(NUMBERS) class TestDialog(QDialog): def __init__(self,parent=None): QDialog.__init__(self,parent) self.setCaption("Dialog") everything = QVBox(self) addTextArea(everything, 400) everything.resize(everything.sizeHint()) class TestMainWindow(QMainWindow): def __init__(self,parent=None): QMainWindow.__init__(self,parent) self.setCaption("Main Window") everything = QVBox(self) addTextArea(everything, 800) button = QPushButton("Open dialog", everything) self.connect(button, SIGNAL('clicked()'), self.openDialog) self.setCentralWidget(everything) self.resize(self.sizeHint()) self.dialog = TestDialog(self) def openDialog(self): self.dialog.show() if __name__ == '__main__': app = QApplication(sys.argv) mainwin = TestMainWindow(None) app.setMainWidget(mainwin) mainwin.show() app.exec_loop() ```
QMainWindow has special behavior for the central widget that a QDialog does not. To achieve the desired behavior you need to create a [layout](http://doc.trolltech.com/3.3/layout.html), add the text area to the layout and assign the layout to the dialog.
Just to add a little note about this - I was trying to have a child window spawned from an application, which is a `QDialog`, containing a single `QTextEdit` as a child/content - and I wanted the `QTextEdit` to resize automatically whenever the `QDialog` window size changes. This seems to have done the trick for me with `PyQt4`: ``` def showTextWindow(self): #QVBox, QHBox # don't exist in Qt4 dialog = QDialog(self) #dialog.setGeometry(QRect(100, 100, 400, 200)) dialog.setWindowTitle("Title") dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose) textbox = QTextEdit(dialog) textbox.setReadOnly(True) textbox.setMinimumSize(QSize(400, 400*0.75)) textbox.setText("AHAAA!") # this seems enough to have the QTextEdit # autoresize to window size changes of dialog! layout = QHBoxLayout(dialog) layout.addWidget(textbox) dialog.setLayout(layout) dialog.exec_() ```
PyQt: getting widgets to resize automatically in a QDialog
[ "", "python", "qt", "pyqt", "qdialog", "" ]
I'm probably missing something simple here, but I can't find the answer elsewhere. I just want to display an applet in my GWT code. OS: Windows XP Java: JDK 1.6.0\_10 Other: GWT, GWT-Ext 2.0.5 Here is the applet (obviously simplified for testing): ``` package foo.applet; import javax.swing.JApplet; import java.awt.Graphics; public class HelloApplet extends JApplet { public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString("Hello world!", 5, 15); } } ``` Here is the code calling it: ``` package foo.applet; import com.google.gwt.user.client.ui.HTML; import com.gwtext.client.widgets.Panel; public class AppletPanel extends Panel { ``` ``` public AppletPanel() { HTML applet = new HTML(); applet.setHTML("<applet name=\"HelloApplet\" code=\"HelloApplet.class\" width=\"300\" height=\"300\"" ); this.add(applet); } ``` } When I launch the app in hosted mode, the jvm crashes (filed incident 1425130 with Sun). When I try to compile the GWT code for running in a browser, I get this: ``` [ERROR] Errors in 'file:/C:/<blah>/applet/HelloApplet.java' [ERROR] Line 3: The import javax.swing cannot be resolved [ERROR] Line 4: The import java.awt cannot be resolved [ERROR] Line 6: JApplet cannot be resolved to a type [ERROR] Line 8: Graphics cannot be resolved to a type [ERROR] Line 11: The method getSize() is undefined for the type HelloApplet [ERROR] Line 12: The method getSize() is undefined for the type HelloApplet ``` Obviously I'm missing some applet library, but I've grepped through all the jars in the jdk and tried including all of the ones that list JApplet or awt (plugin.jar, resources.jar, rt.jar, deploy.jar, javaws.jar). Also, I'm pretty sure once I solve this problem there's another one lurking right after it, but I'll save that for another question. Thanks! --- The legacy app is not an applet - it is a thick-client Swing application. We've hacked it to run as an applet because our customers want a browser client and this is the fastest way to get that done. I don't know if GWT would accept the JPanel solution - the app is not written in any way that GWT can parse - i.e. it's not using the GWT API, it's using the Swing API. AFAIK, the only way to mix Swing with GWT would be in an applet fashion. Am I missing something?
Are you trying to GWT-compile your applet? This won't work, as GWT compilation (which is just translation from Java to Javascript) supports only handful of Java libraries and certainly not applets. Make sure that your applet is not on GWT source path (move it to another package). Reference: <http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=RefJreEmulation>
Don't use the GWTCompiler to compile your applet code. I would recommend creating a second module (or project) that contains only the applet code. Compile this to a separate JAR using the standard Javac compiler (or your IDE/ant) The GWTCompiler uses a subset of the Java libraries, and should only be used to generate the code which is going to eventually run as Javascript.
How to display java applet inside GWT page?
[ "", "java", "gwt", "applet", "gwt-ext", "" ]
I have an application which had optional extras depending on if the user has the software installed. On Linux what is the best way to determine if something like python and PyUsb is installed? I am developing a C++ Qt application if that helps.
This is inefficient (requires forking and exec'ing */bin/sh*). There has to be a better way! But as a generic approach... There's always *system()*. (Remember to use *WEXITSTATUS()*! Watch out for making programs uninterruptable!) ``` #define SHOW(X) cout << # X " = " << (X) << endl int main() { int status; SHOW( status = system( "which grep > /dev/null 2>&1" ) ); SHOW( WEXITSTATUS(status) ); SHOW( status = system( "which no_matching_file > /dev/null 2>&1" ) ); SHOW( WEXITSTATUS(status) ); } ``` There is also *popen()*, which can be useful for grabbing output from programs to verify version numbers, libraries, or whatnot. If you need bidirectional (read&write) access to a subprocess, best to use *pipe()*, *fork()*, *exec()*, *close()*, & *dup2()*.
You can require that they be in the path, etc. Check for the existence of the executable files you will require (using `which` or similar). You can also use the executable files' arguments and check for required versions as well, if needed.
What is the best way to check that external applications are available?
[ "", "c++", "linux", "deployment", "dependencies", "" ]
I need to be able to programmatically transcode mpeg-2 files to .mp4, .mp3, .wmv, .rm (optional), and .flv (optional), and hopefully generate a thumbnail as well. I found the Java Media Framework, but it frankly looks pretty crappy. This will be running a Linux server, so I could shell out to ffmpeg using Commons Exec - does ffmpeg do everything I need to do? FFmpeg seems pretty daunting, which is why I'm having trouble finding this information, but it definitely seems to be a jack-of-all-trades. Any suggestions?
Ffmpeg is the best and easiest. To output/convert video: ``` ffmpeg -i {input}.ext -r {target_frame_rate} -ar {target_audio_rate} -b {target_bitrate} -s {width}x{height} {target}.ext ``` And your screenshot: ``` ffmpeg -i {input}.ext -r 1 -ss 00:00:04:005 -t 00:00:01 -an -s {width}x{height} {target_name}%d.jpg ``` 15 fps is standard for flv and audio sample rate should be 44100 for flv. Options to use: `-r` specifies a frame rate of 1 fps (one frame used as the screenshot), `-ss` seeks to the position you want `hh:mm:ss:fff`, `-t` is the duration (one second to match your one fps), `-an` tells ffmpeg to ignore audio, and `-s` is the size of the screenshot. The `%d` is necessary as it will be the digit incremented on how many screenshots you use. With the above, `%d` will always be the number 1 (one frame, one screenshot). Good luck.
An interesting web service from [encoding.com](http://www.encoding.com/) will transcode files for you.
Programmatically transcode MPEG-2 videos
[ "", "java", "video", "ffmpeg", "mpeg", "transcoding", "" ]
I am constructing a large HTML document from fragments supplied by users that have the annoying habit of being malformed in various ways. Browsers are robust and forgiving enough but I want to be able to validate and (ideally) fix any malformed HTML if at all possible. For example: ``` <td><b>Title</td> ``` can be reasonably fixed to: ``` <td><b>Title</b></td> ``` Is there a way of doing this easily in PHP?
You can use [HTML Tidy](http://devzone.zend.com/article/761-Tidying-up-your-HTML-with-PHP-5), man pages are [here](http://au.php.net/tidy).
I highly recommend [HTML Purifier](http://htmlpurifier.org/). From their site: > HTML Purifier is a standards-compliant > HTML filter library written in PHP. > HTML Purifier will not only remove all > malicious code (better known as XSS) > with a thoroughly audited, secure yet > permissive whitelist, it will also > make sure your documents are standards > compliant, something only achievable > with a comprehensive knowledge of > W3C's specifications. Tired of using > BBCode due to the current landscape of > deficient or insecure HTML filters? > Have a WYSIWYG editor but never been > able to use it? Looking for > high-quality, standards-compliant, > open-source components for that > application you're building? HTML > Purifier is for you!
Fixing malformed HTML in PHP?
[ "", "php", "html", "parsing", "" ]
How do I get the actual value (or text) of the item selected in an HTML select box? Here are the main methods I've tried... ``` document.getElementById('PlaceNames').value ``` ``` $("#PlaceNames option:selected").val() ``` ``` $("#PlaceNames option:selected").text() ``` And I've tried various variations on these. All I ultimately want to do is get that data and send it to a web service via AJAX, I just need the string representation of what the user selected. This seems like it should be really easy and I've even found a question similar to this here, but I'm still having issues getting it worked out. Google doesn't seem to be helping either. I feel like it must be due to some fundamental misunderstanding of Javascript and jQuery. EDIT: I should mention that I'm using IE7
`$('#placeNames').val()` returns the [value](http://docs.jquery.com/Attributes/val) of the selected option in the latest version of jQuery.
Non-jQuery variant: ``` var select = document.getElementById('PlaceNames'); var value = select.options[select.selectedIndex].value; ``` Older jQuery variant: ``` var select = $('#PlaceNames:first')[0]; var value = select.options[select.selectedIndex].value; ``` Current jQuery variant: ``` var value = $('#PlaceNames:first').val(); ``` I'm probably just being overly safe using :first.
Checking to see what item is selected in an HTML select list via jQuery
[ "", "javascript", "jquery", "" ]
I am going to start a C# project from scratch that will consist of several modules so it **can be sold by modules** of an existing PHP/ASP/MySQL/Oracle/MS SQL application that manages to show 3D objects and create 2D and 3D CAD files from a web app that the user can use to create all the stuff. **My question is**, to start from ground zero, and having the "sell" point of view, it should be a good programming method that I should implement, design patterns, unit testing, etc... how will I know how to apply them, and is there any good tutorial / "show me the way" kind'a thing to know about these things, like... * what classes should I make available to be overridden by the client so I can provide extensibility in our modules? * what kind of "package" should I use to "sell"? DLL, CAB, MSI? * should I use SubSonic / NHibernate so the user can generate their own DAL? Our prototype implementation will use only Oracle. I'm kinda lost right now, I know what to do, but not how I can accomplish it (having this perfect coding path in mind). Any good programming ideas are gladly appreciated :)
For a quick hit of each of your explicit questions I would say. As for the how of integration, learn inversion of control principals and how it is used for extensibility purposes. Keep an eye on MEF, Microsoft Extensibility Framework. As for the what, your integration points will depend mostly on the type of application you are writing and your target audience. It also depends on how much control you want to give third parties. Reflector for example has a great, almost wide open plugin structure in place. DLL's and CABs are libraries and storage formats respectively. By themselves, they don't do much. MSI's are one form of installer and can contain the DLLs that will make up your application. Regardless of the type of installer you have, the easier it is to use, the more people that will try your product. The data layer itself doesn't necessarily matter so much. People probably won't be creating their own data layers for your application and if they do, they should be able to use what ever they want if your extensibility framework is doing its job. More importantly is that whatever DAL you do decide on, you need to check to see if it is capable of running on different databases if that is important to you and how much work it takes. You also need to make sure the features you use in the DAL work for all of the databases you want to support. NHibernate has several features that don't work in all of the databases it runs on.
you'll rewrite any application at least once in its lifecycle. get something out to establish value then worry about how pretty your code is. you can spend a year making the perfectly coded application that nobody wants to use, or you can spend a couple months and the rest of the year either improving it, or working on something else if it falls on its face.
Creating an extensive project to be sold
[ "", "c#", "design-patterns", "module", "" ]
Basically this code below returns the right information, but I need to add the quantities together to bring back one record. Is there any way of doing this? ``` select category.category_name, (equipment.total_stock-equipment.stock_out) AS Current_Stock, equipment.stock_out from EQUIPMENT, CATEGORY WHERE EQUIPMENT.CATEGORY_ID = CATEGORY.CATEGORY_ID and category.category_name = 'Power Tools' ```
You want to use the SUM function and a GROUP BY clause. ``` select category.category_name, SUM((equipment.total_stock-equipment.stock_out)) AS Current_Stock, SUM(equipment.stock_out) as stock_out from EQUIPMENT, CATEGORY WHERE EQUIPMENT.CATEGORY_ID = CATEGORY.CATEGORY_ID and category.category_name = 'Power Tools' GROUP BY Category.Category_Name ```
1 - Sum() and Group By will do the trick 2 - Post your questions only once, in one post, its easyer
sql help: how can I add quantities together?
[ "", "sql", "database", "" ]
I have a windows service written in C# that acts as a proxy for a bunch of network devices to the back end database. For testing and also to add a simulation layer to test the back end I would like to have a GUI for the test operator to be able run the simulation. Also for a striped down version to send out as a demo. The GUI and service do not have to run at the same time. What is the best way to achieve this duel operation? Edit: Here is my solution combing stuff from [this question](https://stackoverflow.com/questions/421516) , [Am I Running as a Service](https://stackoverflow.com/questions/200163/am-i-running-as-a-service) and [Install a .NET windows service without InstallUtil.exe](https://stackoverflow.com/questions/255056/install-a-net-windows-service-without-installutil-exe/255062#255062) using [this excellent code](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/4d45e9ea5471cba4/4519371a77ed4a74) by [Marc Gravell](https://stackoverflow.com/users/23354/marc-gravell) It uses the following line to test if to run the gui or run as service. ``` if (arg_gui || Environment.UserInteractive || Debugger.IsAttached) ``` Here is the code. ``` using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.ComponentModel; using System.ServiceProcess; using System.Configuration.Install; using System.Diagnostics; namespace Form_Service { static class Program { /// /// The main entry point for the application. /// [STAThread] static int Main(string[] args) { bool arg_install = false; bool arg_uninstall = false; bool arg_gui = false; bool rethrow = false; try { foreach (string arg in args) { switch (arg) { case "-i": case "-install": arg_install = true; break; case "-u": case "-uninstall": arg_uninstall = true; break; case "-g": case "-gui": arg_gui = true; break; default: Console.Error.WriteLine("Argument not expected: " + arg); break; } } if (arg_uninstall) { Install(true, args); } if (arg_install) { Install(false, args); } if (!(arg_install || arg_uninstall)) { if (arg_gui || Environment.UserInteractive || Debugger.IsAttached) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { rethrow = true; // so that windows sees error... ServiceBase[] services = { new Service1() }; ServiceBase.Run(services); rethrow = false; } } return 0; } catch (Exception ex) { if (rethrow) throw; Console.Error.WriteLine(ex.Message); return -1; } } static void Install(bool undo, string[] args) { try { Console.WriteLine(undo ? "uninstalling" : "installing"); using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args)) { IDictionary state = new Hashtable(); inst.UseNewContext = true; try { if (undo) { inst.Uninstall(state); } else { inst.Install(state); inst.Commit(state); } } catch { try { inst.Rollback(state); } catch { } throw; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } } [RunInstaller(true)] public sealed class MyServiceInstallerProcess : ServiceProcessInstaller { public MyServiceInstallerProcess() { this.Account = ServiceAccount.NetworkService; } } [RunInstaller(true)] public sealed class MyServiceInstaller : ServiceInstaller { public MyServiceInstaller() { this.Description = "My Service"; this.DisplayName = "My Service"; this.ServiceName = "My Service"; this.StartType = System.ServiceProcess.ServiceStartMode.Manual; } } } ```
You basically have two choices. Either expose an API on the service which you can then call from the UI app OR enable the service to run either as a winforms app or a service. The first option is pretty easy - use remoting or WCF to expose the API. The second option can be achieved by moving the "guts" of your app into a separate class then create a service wrapper and a win-forms wrapper that both call into your "guts" class. ``` static void Main(string[] args) { Guts guts = new Guts(); if (runWinForms) { System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); FormWrapper fw = new FormWrapper(guts); System.Windows.Forms.Application.Run(fw); } else { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ServiceWrapper(guts) }; ServiceBase.Run(ServicesToRun); } } ```
If you use the below code: ``` [DllImport("advapi32.dll", CharSet=CharSet.Unicode)] static extern bool StartServiceCtrlDispatcher(IntPtr services); [DllImport("ntdll.dll", EntryPoint="RtlZeroMemory")] static extern void ZeroMemory(IntPtr destination, int length); static bool StartService(){ MySvc svc = new MySvc(); // replace "MySvc" with your service name, of course typeof(ServiceBase).InvokeMember("Initialize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, svc, new object[]{false}); object entry = typeof(ServiceBase).InvokeMember("GetEntry", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, svc, null); int len = Marshal.SizeOf(entry) * 2; IntPtr memory = Marshal.AllocHGlobal(len); ZeroMemory(memory, len); Marshal.StructureToPtr(entry, memory, false); return StartServiceCtrlDispatcher(memory); } [STAThread] static void Main(){ if(StartService()) return; Application.Run(new MainWnd()); // replace "MainWnd" with whatever your main window is called } ``` Then your EXE will run as either a service (if launched by the SCM) or as a GUI (if launched by any other process). Essentially, all I've done here is used [Reflector](http://www.red-gate.com/products/reflector/) to figure out what the meat of [`ServiceBase.Run`](http://msdn.microsoft.com/en-us/library/tks2stkt.aspx) does, and duplicate it here (reflection is required, because it calls private methods). The reason for not calling `ServiceBase.Run` directly is that it pops up a message box to tell the *user* that the service cannot be started (if not launched by the SCM) and doesn't return anything to tell the *code* that the service cannot be started. Because this uses reflection to call private framework methods, it may not function correctly in future revisions of the framework. *Caveat codor.*
How to write c# service that I can also run as a winforms program?
[ "", "c#", "winforms", "windows-services", "installation", "service", "" ]
Let's say I have a class that implements the **IDisposable** interface. Something like this: ![http://www.flickr.com/photos/garthof/3149605015/](https://farm4.static.flickr.com/3199/3149605015_f090f20185_o.png) **MyClass** uses some unmanaged resources, hence the *Dispose()* method from **IDisposable** releases those resources. **MyClass** should be used like this: ``` using ( MyClass myClass = new MyClass() ) { myClass.DoSomething(); } ``` --- Now, I want to implement a method that calls *DoSomething()* asynchronously. I add a new method to **MyClass**: ![http://www.flickr.com/photos/garthof/3149605005/](https://farm4.static.flickr.com/3103/3149605005_bde86e4e0b_o.png) Now, from the client side, **MyClass** should be used like this: ``` using ( MyClass myClass = new MyClass() ) { myClass.AsyncDoSomething(); } ``` However, if I don't do anything else, this could fail as the object *myClass* might be disposed before *DoSomething()* is called (and throw an unexpected **ObjectDisposedException**). So, the call to the *Dispose()* method (either implicit or explicit) should be delayed until the asynchronous call to *DoSomething()* is done. I think the code in the *Dispose()* method should be executed **in a asynchronous way, and only once all asynchronous calls are resolved**. I'd like to know which could be the best way to accomplish this. Thanks. *NOTE: For the sake of simplicity, I haven't entered in the details of how Dispose() method is implemented. In real life I usually follow the [Dispose pattern](http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.80).aspx).* --- **UPDATE:** Thank you so much for your responses. I appreciate your effort. As [chakrit](https://stackoverflow.com/users/3055/chakrit) [has commented](https://stackoverflow.com/questions/400130/how-to-dispose-asynchronously#400165), I need that **multiple calls to the async DoSomething can be made**. Ideally, something like this should work fine: ``` using ( MyClass myClass = new MyClass() ) { myClass.AsyncDoSomething(); myClass.AsyncDoSomething(); } ``` I'll study the counting semaphore, it seems what I'm looking for. It could also be a design problem. If I find it convenient, I will share with you some bits of the real case and what **MyClass** really does.
So, my idea is to keep how many *AsyncDoSomething()* are pending to complete, and only dispose when this count reaches to zero. My initial approach is: ``` public class MyClass : IDisposable { private delegate void AsyncDoSomethingCaller(); private delegate void AsyncDoDisposeCaller(); private int pendingTasks = 0; public DoSomething() { // Do whatever. } public AsyncDoSomething() { pendingTasks++; AsyncDoSomethingCaller caller = new AsyncDoSomethingCaller(); caller.BeginInvoke( new AsyncCallback( EndDoSomethingCallback ), caller); } public Dispose() { AsyncDoDisposeCaller caller = new AsyncDoDisposeCaller(); caller.BeginInvoke( new AsyncCallback( EndDoDisposeCallback ), caller); } private DoDispose() { WaitForPendingTasks(); // Finally, dispose whatever managed and unmanaged resources. } private void WaitForPendingTasks() { while ( true ) { // Check if there is a pending task. if ( pendingTasks == 0 ) { return; } // Allow other threads to execute. Thread.Sleep( 0 ); } } private void EndDoSomethingCallback( IAsyncResult ar ) { AsyncDoSomethingCaller caller = (AsyncDoSomethingCaller) ar.AsyncState; caller.EndInvoke( ar ); pendingTasks--; } private void EndDoDisposeCallback( IAsyncResult ar ) { AsyncDoDisposeCaller caller = (AsyncDoDisposeCaller) ar.AsyncState; caller.EndInvoke( ar ); } } ``` Some issues may occur if two or more threads try to read / write the *pendingTasks* variable concurrently, so the **lock** keyword should be used to prevent race conditions: ``` public class MyClass : IDisposable { private delegate void AsyncDoSomethingCaller(); private delegate void AsyncDoDisposeCaller(); private int pendingTasks = 0; private readonly object lockObj = new object(); public DoSomething() { // Do whatever. } public AsyncDoSomething() { lock ( lockObj ) { pendingTasks++; AsyncDoSomethingCaller caller = new AsyncDoSomethingCaller(); caller.BeginInvoke( new AsyncCallback( EndDoSomethingCallback ), caller); } } public Dispose() { AsyncDoDisposeCaller caller = new AsyncDoDisposeCaller(); caller.BeginInvoke( new AsyncCallback( EndDoDisposeCallback ), caller); } private DoDispose() { WaitForPendingTasks(); // Finally, dispose whatever managed and unmanaged resources. } private void WaitForPendingTasks() { while ( true ) { // Check if there is a pending task. lock ( lockObj ) { if ( pendingTasks == 0 ) { return; } } // Allow other threads to execute. Thread.Sleep( 0 ); } } private void EndDoSomethingCallback( IAsyncResult ar ) { lock ( lockObj ) { AsyncDoSomethingCaller caller = (AsyncDoSomethingCaller) ar.AsyncState; caller.EndInvoke( ar ); pendingTasks--; } } private void EndDoDisposeCallback( IAsyncResult ar ) { AsyncDoDisposeCaller caller = (AsyncDoDisposeCaller) ar.AsyncState; caller.EndInvoke( ar ); } } ``` I see a problem with this approach. As the release of resources is asynchronously done, something like this might work: ``` MyClass myClass; using ( myClass = new MyClass() ) { myClass.AsyncDoSomething(); } myClass.DoSomething(); ``` When the expected behavior should be to launch an **ObjectDisposedException** when *DoSomething()* is called outside the **using** clause. But I don't find this bad enough to rethink this solution.
It looks like you're using the event-based async pattern ([see here for more info about .NET async patterns](http://msdn.microsoft.com/en-us/library/ms228969.aspx)) so what you'd typically have is an event on the class that fires when the async operation is completed named `DoSomethingCompleted` (note that `AsyncDoSomething` should really be called `DoSomethingAsync` to follow the pattern correctly). With this event exposed you could write: ``` var myClass = new MyClass(); myClass.DoSomethingCompleted += (sender, e) => myClass.Dispose(); myClass.DoSomethingAsync(); ``` The other alternative is to use the `IAsyncResult` pattern, where you can pass a delegate that calls the dispose method to the `AsyncCallback` parameter (more info on this pattern is in the page above too). In this case you'd have `BeginDoSomething` and `EndDoSomething` methods instead of `DoSomethingAsync`, and would call it something like... ``` var myClass = new MyClass(); myClass.BeginDoSomething( asyncResult => { using (myClass) { myClass.EndDoSomething(asyncResult); } }, null); ``` But whichever way you do it, you need a way for the caller to be notified that the async operation has completed so it can dispose of the object at the correct time.
How to dispose asynchronously?
[ "", "c#", "asynchronous", "dispose", "" ]
When trying to launch and run a flex/java project in eclipse I kept getting a "Out of Memory Exception" and "Java Heap Space" using Eclipse, Tomcat and a JRE. While researching trying to adjust the memory settings I found three places to adjust these: * Eclipse.ini * The JRE Settings under Window > Preferences * Catalina.sh or Catalina.bat What are the differences between setting -xms and -xmx in these different places and what does is mean? Is there any way to verify these memory settings are being set accordingly? What are the optimal -xms and -xmx settings for a computer with 2gb of RAM? Any other memory tips? Thanks.
-xms is the start memory (at the VM start), -xmx is the maximum memory for the VM * eclipse.ini : the memory for the VM running eclipse * jre setting : the memory for java programs run from eclipse * catalina.sh : the memory for your tomcat server
First of all, I suggest that you narrow the problem to which component throws the "Out of Memory Exception". This could be: 1. **Eclipse** itself (which I doubt) 2. **Your application** under **Tomcat** The JVM parameters `-xms` and `-xmx` represent the heap's "start memory" and the "maximum memory". Forget the "start memory". This is not going to help you now and you should only change this parameter if you're sure your app will consume this amount of memory rapidly. In production, I think the only parameter that you can change is the `-xmx` under the Catalina.sh or Catalina.bat files. But if you are testing your webapp directly from Eclipse with a configured debug environment of Tomcat, you can simply go to your "Debug Configurations" > "Apache Tomcat" > "Arguments" > "VM arguments" and set the `-xmx` there. As for the optimal `-xmx` for 2gb, this depends a lot of your environment and the number of requests your app might take. I would try values from 500mb up to 1gb. Check your OS virtual memory "zone" limit and the limit of the JVM itself.
Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"
[ "", "java", "apache-flex", "eclipse", "memory", "" ]
I'm pulling back a Date and a Time from a database. They are stored in separate fields, but I would like to combine them into a java.util.Date object that reflects the date/time appropriately. Here is my original approach, but it is flawed. I always end up with a Date/Time that is 6 hours off what it should be. I think this is because the Time has a timezone offset as well as the Date, and I really only need one of them to have the timezone offset. Any suggestions on how to do this so that it will give me the correct Date/Time? ``` import java.sql.Time; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.time.DateUtils; public static Date combineDateTime(Date date, Time time) { if (date == null) return null; Date newDate = DateUtils.truncate(date, Calendar.DATE); if (time != null) { Date t = new Date(time.getTime()); newDate = new Date(newDate.getTime() + t.getTime()); } return newDate; } ```
I would put both the Date and the Time into Calendar objects, and then use the various Calendar methods to extract the time values from the second object and put them into the first. ``` Calendar dCal = Calendar.getInstance(); dCal.setTime(date); Calendar tCal = Calendar.getInstance(); tCal.setTime(time); dCal.set(Calendar.HOUR_OF_DAY, tCal.get(Calendar.HOUR_OF_DAY)); dCal.set(Calendar.MINUTE, tCal.get(Calendar.MINUTE)); dCal.set(Calendar.SECOND, tCal.get(Calendar.SECOND)); dCal.set(Calendar.MILLISECOND, tCal.get(Calendar.MILLISECOND)); date = dCal.getTime(); ```
Use Joda Time instead of Java's own Date classes when doing these types of things. It's a far superior date/time api that makes the sort of thing you are trying to do extremely easy and reliable.
How do I combine a java.util.Date object with a java.sql.Time object?
[ "", "java", "date", "time", "" ]
I'd like to create a workspace with status bar and menu, and within this workspace container have smaller windows of various types. For example, if you un-maximise a worksheet in Excel but not the main window, it becomes a window in a larger workspace. I've tried searching for the result but the main problem is in knowing the right terminology.
You want an MDI (Multiple Document Interface) Form Just set the IsMdiContainer property of your main form to True, and you should be able to add other forms as mdi children.
Check into MDI programming. Here's a couple links [Creating an MDI Application (CodeProject)](http://www.codeproject.com/KB/cs/myBestMDI.aspx) [Developing MDI Application in C# (C-Sharp Corner)](http://www.c-sharpcorner.com/UploadFile/ggaganesh/DevelopingMDIAppplicationsinCSharp11272005225843PM/DevelopingMDIAppplicationsinCSharp.aspx)
How do I create a workspace window for other windows using c# in visual studio 2008?
[ "", "c#", "visual-studio", "layout", "" ]
I am a little confused here. I would like to do something like this: 1. create some kind of buffer I can write into 2. clear the buffer 3. use a printf()-like function several times to append a bunch of stuff into the buffer based on some complicated calculations I only want to do once 4. use the contents of the buffer and print it to several `PrintStream` objects 5. repeat steps 2-4 as necessary e.g.: ``` SuperBuffer sb = new SuperBuffer(); /* SuperBuffer is not a real class, so I don't know what to use here */ PrintStream[] streams = new PrintStream[N]; /* ... initialize this array to several streams ... */ while (!done) { sb.clear(); sb.printf("something %d something %d something %d", value1, value2, value3); if (some_complicated_condition()) sb.printf("something else %d something else %d", value4, value5); /* ... more printfs to sb ... */ for (PrintStream ps : streams) ps.println(sb.getBuffer()); } ``` It looks like wrapping a [PrintWriter](http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html) around [StringWriter](http://java.sun.com/j2se/1.5.0/docs/api/java/io/StringWriter.html) will do what I want for the `sb` object above, except there's no `clear()` method. I suppose I could create a new PrintWriter and StringWriter object each time through the loop, but that seems like a pain. (in my real code I do this in several places, not just once in one loop...) I've also used `java.nio.CharBuffer` and other NIO buffers a lot, and that seems like a promising approach, but I'm not sure how I can wrap them with an object that will give me `printf()` functionality. any advice?
ah: I think I've got it. The [`Formatter`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html) class has a `format()` method that's like `printf()`, and it can be constructed to wrap around any kind of object that implements `Appendable`. [`CharBuffer`](http://java.sun.com/j2se/1.5.0/docs/api/java/nio/CharBuffer.html) implements `Appendable`, and I can `clear()` or read out the contents of the `CharBuffer` as necessary.
Why is it a pain to create a new buffer in the loop? That's what the garbage collector is there for. There would need to be a new allocation under the covers in clear() anyway. If you really want to implement your SuperBuffer, it would not be that hard at all. Just create a subclass of OutputStream with a clear() function, and then wrap a PrintStream around that. You could use a CharBuffer in your super buffer if you wanted.
printf() functionality in Java combined with a CharBuffer or something like it
[ "", "java", "stream", "printf", "" ]
We've a table with a `varchar2(100)` column, that occasionally contains carriage-return & line-feeds. We should like to remove those characters in the SQL query. We're using: ``` REPLACE( col_name, CHR(10) ) ``` which has **no effect**, however replacing 'CHR(10)' for a more conventional 'letter' character proves that the REPLACE function works otherwise. We have also found that ``` REPLACE( col_name, CHR(10), '_' ) ``` finds the *location* of the new-line, but *inserts* the underscore after it, rather than replacing it. Running on Oracle8i. Upgrading is not an option.
Another way is to use [TRANSLATE](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions196.htm#i1501659): ``` TRANSLATE (col_name, 'x'||CHR(10)||CHR(13), 'x') ``` The 'x' is any character that you don't want translated to null, because TRANSLATE doesn't work right if the 3rd parameter is null.
Ahah! Cade is on the money. An artifact in TOAD prints `\r\n` as two placeholder 'blob' characters, but prints a single `\r` also as two placeholders. The 1st step toward a solution is to use .. ``` REPLACE( col_name, CHR(13) || CHR(10) ) ``` .. but I opted for the slightly more robust .. ``` REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) ) ``` .. which catches offending characters in any order. My many thanks to Cade. M.
Oracle REPLACE() function isn't handling carriage-returns & line-feeds
[ "", "sql", "oracle", "" ]
I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using random numbers and stuff, but I need to keep using that particular number in some other function which is a callback or something and so can't be part of the same function. If the originally generated number is a local variable, it won't be accessible from, there. If the functions were object methods, I could make the number a property but they're not and it seems somewhat overcomplicated to change the whole program structure to do this. Is a global variable really so bad?
To make a variable calculated in function A visible in function B, you have three choices: * make it a global, * make it an object property, or * pass it as a parameter when calling B from A. If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method: ``` function A() { var rand_num = calculate_random_number(); B(rand_num); } function B(r) { use_rand_num(r); } ```
I think your best bet here may be to define a *single* global-scoped variable, and dumping your variables there: ``` var MyApp = {}; // Globally scoped object function foo(){ MyApp.color = 'green'; } function bar(){ alert(MyApp.color); // Alerts 'green' } ``` No one should yell at you for doing something like the above.
Accessing variables from other functions without using global variables
[ "", "javascript", "global-variables", "" ]
I need to call a const function from a non-const object. See example ``` struct IProcess { virtual bool doSomeWork() const = 0L; }; class Foo : public IProcess { virtual bool doSomeWork() const { ... } }; class Bar { public: const IProcess& getProcess() const {return ...;} IProcess& getProcess() {return ...;} void doOtherWork { getProcess().doSomeWork(); } }; ``` Calling ``` getProcess().doSomeWork(); ``` will always results in a call to ``` IProcess& getProcess() ``` Is there another way to call ``` const IProcess& getProcess() const ``` from a non constant member function? I have so far used ``` const_cast<const Bar*>(this)->getProcess().doSomeWork(); ``` which does the trick but seems overly complicated. --- Edit: I should mention that code is being refactored and eventually only one function will remain. ``` const IProcess& getProcess() const ``` However, currently there is a side effect and the const call may return a different instance of IProcess some of the time. Please keep on topic.
Avoid the cast: assign this to a `const Bar *` or whatever and use that to call `getProcess()`. There are some pedantic reasons to do that, but it also makes it more obvious what you are doing without forcing the compiler to do something potentially unsafe. Granted, you may never hit those cases, but you might as well write something that doesn't use a cast in this case.
`const_cast` is for casting **away** constness! You're casting from non-const to const which is safe, so use `static_cast`: ``` static_cast<const Bar*>(this)->getProcess().doSomeWork(); ``` *I mean techincally speaking you can cast in constness with `const_cast`, but it's not a pragmatic use of the operator. The purpose of new style casts (versus the old c-style cast), is to communicate the intent of the cast. `const_cast` is a code smell, and it's use should be reviewed at least. `static_cast` on the other hand is safe. But it's a matter of C++ style.* Or you can create a new (private) const method, and call that from `doOtherWork`: ``` void doSomeWorkOnProcess() const { getProcess().doSomeWork(); } ``` Using a const temporary is also an option (answer by "MSN"): ``` const Bar* _this = this; _this->getProcess().doSomeWork(); ```
Calling a const function from a non-const object
[ "", "c++", "function", "constants", "" ]
This is the SP... ``` USE [EBDB] GO /****** Object: StoredProcedure [dbo].[delete_treatment_category] Script Date: 01/02/2009 15:18:12 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /* RETURNS 0 FOR SUCESS 1 FOR NO DELETE AS HAS ITEMS 2 FOR DELETE ERROR */ ALTER PROCEDURE [dbo].[delete_treatment_category] ( @id INT ) AS SET NOCOUNT ON IF EXISTS ( SELECT id FROM dbo.treatment_item WHERE category_id = @id ) BEGIN RETURN 1 END ELSE BEGIN BEGIN TRY DELETE FROM dbo.treatment_category WHERE id = @id END TRY BEGIN CATCH RETURN 2 END CATCH RETURN 0 END ``` And I'm trying to get the return value using the below code (sqlDataSource & Gridview combo in VB .NET ``` Protected Sub dsTreatmentCats_Deleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsTreatmentCats.Deleted Select Case CInt(e.Command.Parameters(0).Value) Case 0 'it worked so no action lblError.Visible = False Case 1 lblError.Text = "Unable to delete this category because it still has treatments associated with it." lblError.Visible = True Case 2 lblError.Text = "Unable to delete this category due to an unexpected error. Please try again later." lblError.Visible = True End Select End Sub ``` The problem is that the line CInt(e.Command.Parameters(0).Value) returns a DBNull instead of the return value but only on deletes - this approach works fine with both updates and inserts. Hopefully I'm just being a bit dense and have missed something obvious - any ideas? **Edit** I'm still having this problem and have tried all of the options below to no avail - I'm surprised no one else has had this problem? Code for adding parameters: ``` <asp:SqlDataSource ID="dsTreatmentCats" runat="server" ConnectionString="<%$ ConnectionStrings:EBDB %>" DeleteCommand="delete_treatment_category" DeleteCommandType="StoredProcedure" InsertCommand="add_treatment_category" InsertCommandType="StoredProcedure" SelectCommand="get_treatment_categories" SelectCommandType="StoredProcedure" UpdateCommand="update_treatment_category" UpdateCommandType="StoredProcedure" ProviderName="System.Data.SqlClient"> <DeleteParameters> <asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" /> <asp:Parameter Name="id" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" /> <asp:Parameter Name="id" Type="Int32" /> <asp:Parameter Name="name" Type="String" /> <asp:Parameter Name="additional_info" Type="String" /> </UpdateParameters> <InsertParameters> <asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" /> <asp:ControlParameter ControlID="txtCat" Name="name" PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="txtAddInfo" Name="additional_info" PropertyName="Text" Type="String" /> </InsertParameters> </asp:SqlDataSource> ```
I'm a little late to the game here, but for the sake of people who stumble upon this question... If you're using ExecuteReader in ADO.Net, the return value will not be populated until you close either the Reader or the underlying connection to the database. ([See here](http://dhenztm.spaces.live.com/blog/cns!761D77A7A749C21B!727.entry)) This will not work: ``` SqlConnection conn = new SqlConnection(myConnectionString); SqlCommand cmd = new SqlCommand(mySqlCommand, conn); // Set up your command and parameters cmd.Parameters.Add("@Return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { // Read your data } int resultCount = (int)cmd.Parameters["@Return"].Value; conn.Close(); return resultCount; ``` This will: ``` SqlConnection conn = new SqlConnection(myConnectionString); SqlCommand cmd = new SqlCommand(mySqlCommand, conn); // Set up your command and parameters cmd.Parameters.Add("@Return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { // Read your data } conn.Close(); int resultCount = (int)cmd.Parameters["@Return"].Value; return resultCount; ```
When you added the Parameter, did you set the Direction to [ReturnValue](http://msdn.microsoft.com/en-us/library/system.data.parameterdirection.aspx)?
Return value from SQL 2005 SP returns DBNULL - Where am I going wrong?
[ "", "asp.net", "sql", "vb.net", "t-sql", "sql-server-2005", "" ]
I have a Database table that I want to display in a DataGridView. However, it has several foreign keys and I don't want to show the integer that represents the other Table to the user. I have this DataTable with a column userId I have another DataTable with a column id, and a column username I want the DataGridView to show the username instead of userId where the userId = id. How can I do this? I also have to do this on several columns in the same table to be displayed. edit: windows forms, not web forms.
How are you populating the DataTable? You can specify custom SQL with the joins and appropriate columns to the .SelectCommand of a DataAdapter or specify the custom SQL in the .CommandText of a xxxCommand object. Eg ``` myAdapter.SelectCommand = "Select a.column1, a.column2, b.username from tablea a inner join tableb b on b.userid = a.userId" ``` Or ``` myCommand.CommandType = Text; myCommand.CommandText = ""Select a.column1, a.column2, b.username from tablea a inner join tableb b on b.userid = a.userId"; ``` Or as has been mentioned, you could create a view or storedproc in your database and call that.
Here are a couple options to consider... 1 - If you have access to the database, have a view or stored procedure created that returns the "denormalized" data. You can then bind your GridView directly to this and everything is done. 2 - Create template columns for those fields that you need to retrieve. Then in the RowDatabound event for the GridView, you can programmatically call out and get the appropriate lookup information and display that in the column specified. Your code would look something like this: ``` protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[1].Text = GetUserId(Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "userid")); } } ```
DataBinding with a DataGridView C#
[ "", "c#", "database", "data-binding", "datagridview", "" ]
I saw this keyword for the first time and I was wondering if someone could explain to me what it does. * What is the `continue` keyword? * How does it work? * When is it used?
A `continue` statement without a label will re-execute from the condition the innermost `while` or `do` loop, and from the update expression of the innermost `for` loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested `if` statements. In the following example `continue` will get the next line, without processing the following statement in the loop. ``` while (getNext(line)) { if (line.isEmpty() || line.isComment()) continue; // More code here } ``` With a label, `continue` will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity. Sometimes `continue` is also used as a placeholder in order to make an empty loop body more clear. ``` for (count = 0; foo.moreData(); count++) continue; ``` The same statement without a label also exists in C and C++. The equivalent in Perl is `next`. This type of control flow is not recommended, but if you so choose you can also use `continue` to simulate a limited form of `goto`. In the following example the `continue` will re-execute the empty `for (;;)` loop. ``` aLoopName: for (;;) { // ... while (someCondition) // ... if (otherCondition) continue aLoopName; ```
`continue` is kind of like `goto`. Are you familiar with `break`? It's easier to think about them in contrast: * `break` terminates the loop (jumps to the code below it). * `continue` terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.
What is the "continue" keyword and how does it work in Java?
[ "", "java", "keyword", "continue", "" ]
I know that [CodeRush Xpress](http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/) is intended to be used on VS 2008 and not on VS 2005. But since I can't migrate to VS2008 yet, I want to install it on VS2005 and don't care it's not supposed to work. My base assumption is that it can be done, this is based on the fact that the rest of the free re factoring products from DevExpress do work on VS 2005.
It is possible, and here what you need to do it. Make sure VS is closed. Install [RefactorCpp](http://devexpress.com/Products/Visual_Studio_Add-in/RefactorCPP/). Install [CodeRush Xpress](http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/). Apply this registry patch: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Developer Express] [HKEY_LOCAL_MACHINE\SOFTWARE\Developer Express\CodeRush for VS\3.2] "HideMenu"=dword:00000000 "LoadDXPlugInsOnly"=dword:00000000 "StatusTextEnabled"=dword:00000001 ``` Open VS. Enable "DevExpress Tools" add-in in visual studio, Tools -> Add-in manager. Check the enable and startup checkboxes. And now you are the proud user of CodeRush Xpress on VS 2005. P.S. This works for me on: Microsoft Visual Studio 2005 Version 8.0.50727.762 (SP.050727-7600)
Bad notice! It's not possible because the plugin is for .NET Framework 3 and Visual Studio 2008 aka Orcas. I try to install in Visual Studio 2005 but unsuccessfull.
How to install CodeRush Xpress on VS2005
[ "", "c#", "visual-studio-2005", "coderush-xpress", "" ]
I am finishing off a C# ASP.NET program that allows the user to build their own computer by selecting hardware components such as memory, cpu, etc from a drop down lists. The SQL datatable has 3 columns; ComputerID, Attribute and Value. The computerID is an ID that corresponds to a certain computer in my main datatable of products, the Attribtute is the name of the hardware component; memory,cpu, hard drive etc.. and the value is the value assigned to that attribute, such as 1GB or 2.8GHz 320GB. This means that a computer will have multiple attributes. What I am trying to do it narrow down the results by first selecting all computers that meet the first attribute requirements and then getting from that list, all computers that meet the next requirement.. and so on for about 10+ attributes. I thought it might be a good idea to show you an example of my LINQ to SQL query so that you have a btter idea of what I am trying to do. This basically selects the ComputerID where the the computers memory is larger than 1GB. ``` var resultsList = from results in db.ComputerAttributes where computer.Value == "MEMORY" && computer.Value >= "1" select results.ComputerID; ``` Next I want to select from the resultsList where the CPU is say, faster than 2.8Ghz and so on. I hope I have given you enough information. If anyone could please give me some advice as to how I might go about finishing this project that would be great. Thanks
You need to use Concat as a "Union All". ``` IQueryable<ComputerAttribute> results = null; foreach(ComputerRequirement z in requirements) { //must assign to a locally scoped variable to avoid using // the same reference in all of the where methods. ComputerRequirement cr = z; if (results == null) { results = db.ComputerAttributes .Where(c => c.Attribute == cr.Attribute && c.Value >= cr.Value); } else { results = results .Concat(db.ComputerAttributes .Where(c => c.Attribute == cr.Attribute && c.Value >= cr.Value) ); } } int requirementCount = requirements.Count(); //Get the id's of computers that matched all requirements. IQueryable<int> ids = results .GroupBy(x => x.ComputerId) .Where(g => g.Count == requirementsCount) .Select(g => g.Key); //Get all attributes for those id's List<ComputerAttributes> data = db .ComputerAttributes.Where(c => ids.Contains(c.ComputerId)) .ToList(); ```
I'm assuming you're asking: > How do I refine the content of a search I've done using LINQ to SQL? Or something similar right? To my understanding, you have two options: 1. Filter your results in memory (if you have them cached). 2. Extend your SQL query and hit the DB again. I'm not sure that LINQ to SQL allows you to requery an existing result set. I'm pretty sure it doesn't.
LINQ to SQL
[ "", "sql", "sql-server", "linq", "" ]
I am writing a library in standard C++ which does the phonetic conversion. I have used std::string as of now. But in future I may have to change this to someother (std::wstring or something else). So I need to write my library in such a way that I can switch this easily. I have done the following so far to achieve this. 1. Created a header file which will be used by all CPP files 2. Added a "typedef std::string" to this and used the new name everywhere in the file. If I need to change the type, I can simply change in the header file and it will be reflected everywhere. I'd appreciate if someone can see this is the correct approach or is there a better way to do this? Thanks
You can write template functions that will work with either type of string, or for that matter anything that has the proper methods. If you do the typedef as you suggest, you will need to change all your code in the future when you change the typedef. I'd recommend against it. Edit: the point is that string and wstring are not interchangeable. Sure, you'll be able to update your library by changing a single line, but that's just the start - changing the typedef means you're changing the public API of your library. You'll have to change and test all of the code that interacts with your library, and this might represent the majority of the work involved. It's even possible that a simple search and replace is sufficient to update your library, and then the typedef has bought you nothing. There's value in sticking to the standard types that everyone knows and understands.
I think typedeffing std::string is reasonable. You are still bound to an interface though. If you ever switch to a string implementation with an incompatible interface you can change the value of your typedef to some adapter class. In C++, you can do this with minimal to no overhead. Changing to a new string type then implies changing the adapter class. If you find yourself changing the adapter often you might set it as a template. You are still not immune however from others (or yourself in a later time) forgetting about the typedef and using std::string directly.
typedef a std::string - Best practice
[ "", "c++", "typedef", "" ]
I'd like to include **Python scripting** in one of my applications, that is written in Python itself. My application must be able to call external Python functions (written by the user) as **callbacks**. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that. What is the best way to do this? Thanks. *edit*: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.
Use `__import__` to import the files provided by the user. This function will return a module. Use that to call the functions from the imported file. Use `try..except` both on `__import__` and on the actual call to catch errors. Example: ``` m = None try: m = __import__("external_module") except: # invalid module - show error if m: try: m.user_defined_func() except: # some error - display it ```
If you'd like the user to interactively enter commands, I can highly recommend the [code](http://docs.python.org/library/code.html) module, part of the standard library. The InteractiveConsole and InteractiveInterpreter objects allow for easy entry and evaluation of user input, and errors are handled very nicely, with tracebacks available to help the user get it right. Just make sure to catch SystemExit! ``` $ python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> shared_var = "Set in main console" >>> import code >>> ic = code.InteractiveConsole({ 'shared_var': shared_var }) >>> try: ... ic.interact("My custom console banner!") ... except SystemExit, e: ... print "Got SystemExit!" ... My custom console banner! >>> shared_var 'Set in main console' >>> shared_var = "Set in sub-console" >>> sys.exit() Got SystemExit! >>> shared_var 'Set in main console' ```
Scripting inside a Python application
[ "", "python", "scripting", "" ]
Hey, im doing a little app for my smart phone, using Windows Mobile 6. I'm trying to get all currently running processec, but method CreateToolhelp32Snapshot always returns -1. So now im stuck. I tried to get error with invoking GetLastError() method, but that method returns 0 value. Here is a snippet of my code. ``` private const int TH32CS_SNAPPROCESS = 0x00000002; [DllImport("toolhelp.dll")] public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processid); public static Process[] GetProcesses() { ArrayList procList = new ArrayList(); IntPtr handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if ((int)handle > 0) { try { PROCESSENTRY32 peCurr; PROCESSENTRY32 pe32 = new PROCESSENTRY32(); // get byte array to pass to API call byte[] peBytes = pe32.ToByteArray(); // get the first process int retval = Process32First(handle, peBytes); ```
* First, your handle check is wrong. It's common for the high bit to be on in a handle, causing it to look like a negative number when cast to a signed int. You should be checking that is isn't NULL (0) or INVALID\_HANDLE\_VALUE (-1 / 0xffffffff). * You shouldn't be "invoking GetLastError" but calling Marshal.GetLastWin32Error() * You've not set the SetLastError attribute in the P/Invoke declaration. In C# it defaults to false, in VB it defaults to true. * Where's your PROCESS32 implementation? The [docs clearly state](http://msdn.microsoft.com/en-us/library/aa915359.aspx) that the dwLength member must be set before the call and it's not clear here if that's happening. As a side note, the [Smart Device Framework](http://www.smartdeviceframework.com)'s [OpenNETCF.ToolHelp namespace](http://opennetcf.com/library/sdf/html/a2bccceb-fc28-262d-c05c-26565a0986d1.htm) has all of this implemented and working (in case you'd rather not reinvent the wheel).
Instead of ``` CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); ``` use ``` private const int TH32CS_SNAPNOHEAPS = 0x40000000; CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPNOHEAPS, 0); ``` By default CreateToolhelp32Snapshot will try to snapshot the heaps and that can cause an out of memory error. Found this at <https://social.msdn.microsoft.com/Forums/en-US/e91d845d-d51e-45ad-8acf-737e832c20d0/createtoolhelp32snapshot-windows-mobile-5?forum=vssmartdevicesnative> and it solved my problem.
P/Invoking CreateToolhelp32Snapshot failing in Compact Framework
[ "", "c#", ".net", "compact-framework", "windows-ce", "" ]
Can anyone explain to me why I would want to use IList over List in C#? *Related question: [Why is it considered bad to expose `List<T>`](https://stackoverflow.com/questions/387937)*
If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change. If you are just using it internally, you may not care so much, and using `List<T>` may be ok.
The less popular answer is programmers like to pretend their software is going to be re-used the world over, when infact the majority of projects will be maintained by a small amount of people and however nice interface-related soundbites are, you're deluding yourself. [Architecture Astronauts](http://www.joelonsoftware.com/items/2008/05/01.html). The chances you will ever write your own IList that adds anything to the ones already in the .NET framework are so remote that it's theoretical jelly tots reserved for "best practices". ![Software astronauts](https://t2.gstatic.com/images?q=tbn:ga6-86aP3KtEeM:http://hannahsworld.files.wordpress.com/2007/11/astronaut.jpg) Obviously if you are being asked which you use in an interview, you say IList, smile, and both look pleased at yourselves for being so clever. Or for a public facing API, IList. Hopefully you get my point.
List<T> or IList<T>
[ "", "c#", "list", "generics", "" ]
Simple question - In c++, what's the neatest way of getting which of two numbers (u0 and u1) is the smallest positive number? (that's still efficient) Every way I try it involves big if statements or complicated conditional statements. Thanks, Dan Here's a simple example: ``` bool lowestPositive(int a, int b, int& result) { //checking code result = b; return true; } lowestPositive(5, 6, result); ```
I prefer clarity over compactness: ``` bool lowestPositive( int a, int b, int& result ) { if (a > 0 && a <= b) // a is positive and smaller than or equal to b result = a; else if (b > 0) // b is positive and either smaller than a or a is negative result = b; else result = a; // at least b is negative, we might not have an answer return result > 0; // zero is not positive } ```
If the values are represented in twos complement, then ``` result = ((unsigned )a < (unsigned )b) ? a : b; ``` will work since negative values in twos complement are larger, when treated as unsigned, than positive values. As with Jeff's answer, this assumes at least one of the values is positive. ``` return result >= 0; ```
Neatest / Fastest Algorithm for Smallest Positive Number
[ "", "c++", "algorithm", "optimization", "" ]
Does anyone ever use stopwatch benchmarking, or should a performance tool always be used? Are there any good free tools available for Java? What tools do you use? To clarify my concerns, stopwatch benchmarking is subject to error due to operating system scheduling. On a given run of your program the OS might schedule another process (or several) in the middle of the function you're timing. In Java, things are even a little bit worse if you're trying to time a threaded application, as the JVM scheduler throws even a little bit more randomness into the mix. How do you address operating system scheduling when benchmarking?
Stopwatch benchmarking is fine, provided you measure **enough** iterations to be meaningful. Typically, I require a total elapsed time of some number of single digit seconds. Otherwise, your results are easily significantly skewed by scheduling, and other O/S interruptions to your process. For this I use a little set of static methods I built a long time ago, which are based on `System.currentTimeMillis()`. For the profiling work I have used [jProfiler](http://www.ej-technologies.com/products/jprofiler/overview.html) for a number of years and have found it very good. I have recently looked over [YourKit](http://www.yourkit.com/), which seems great from the WebSite, but I've not used it at all, personally. To answer the question on scheduling interruptions, I find that doing repeated runs until consistency is achieved/observed works in practice to weed out anomalous results from process scheduling. I also find that thread scheduling has no practical impact for runs of between 5 and 30 seconds. Lastly, after you pass the few seconds threshold scheduling has, in my experience, negligible impact on the results - I find that a 5 second run consistently averages out the same as a 5 minute run for time/iteration. You may also want to consider prerunning the tested code about 10,000 times to "warm up" the JIT, depending on the number of times you expect the tested code to run over time in real life.
It's totally valid as long as you measure large enough intervals of time. I would execute 20-30 runs of what you intend to test so that the total elapsed time is over 1 second. I've noticed that time calculations based off System.currentTimeMillis() tend to be either 0ms or ~30ms; I don't think you can get anything more precise than that. You may want to try out System.nanoTime() if you really need to measure a small time interval: * documentation: <http://java.sun.com/javase/6/docs/api/java/lang/System.html#nanoTime()> * SO question about measuring small time spans, since System.nanoTime() has some issues, too: [How can I measure time with microsecond precision in Java?](https://stackoverflow.com/q/503877/750378)
Is stopwatch benchmarking acceptable?
[ "", "java", "benchmarking", "" ]
I've been trying to find a way to match a number in a Javascript string that is surrounded by parenthesis at the end of the string, then increment it. Say I have a string: ``` var name = "Item Name (4)"; ``` I need a RegExp to match the (4) part, and then I need to increment the 4 then put it back into the string. This is the regex I have so far: ``` \b([0-9]+)$\b ``` This regex does not work. Furthermore, I do not know how to extract the integer retrieved and put it back in the same location in the string. Thanks.
The replace method can take a function as its second argument. It gets the match (including submatches) and returns the replacement string. Others have already mentioned that the parentheses need to be escaped. ``` "Item Name (4)".replace(/\((\d+)\)/, function(fullMatch, n) { return "(" + (Number(n) + 1) + ")"; }); ```
I can can only think of a way of doing it in three steps: Extract, increment and replace. ``` // Tested on rhino var name = "Item Name (4)"; var re = /\((\d+)\)/; match = re.exec(name); number = parseInt(match[1]) + 1; name = name.replace(re, "(" + number + ")"); ``` The important parts of the pattern: 1. You need to escape the parens to match literal parens 2. You also need the to use parens to capture the number so that you can extract it from the match. 3. \d matches a digit and is shorter and more common than writing out [0-9].
Use RegExp to match a parenthetical number then increment it
[ "", "javascript", "regex", "string", "" ]
I have a webpage that implements a set of tabs each showing different content. The tab clicks do not refresh the page but hide/unhide contents at the client side. Now there is a requirement to change the page title according to the tab selected on the page ( for SEO reasons ). Is this possible? Can someone suggest a solution to dynamically alter the page title via javascript without reloading the page?
**Update**: as per the comments and reference on [SearchEngineLand](https://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157) most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable. > You can just do something like, `document.title = "This is the new > page title.";`, but that would totally defeat the purpose of SEO. Most > crawlers aren't going to support javascript in the first place, so > they will take whatever is in the element as the page title. > > If you want this to be compatible with most of the important crawlers, > you're going to need to actually change the title tag itself, which > would involve reloading the page (PHP, or the like). You're not going > to be able to get around that, if you want to change the page title in > a way that a crawler can see.
I want to say hello from the future :) Things that happened recently: 1. Google now runs javascript that is on your website[1](http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157) 2. People now use things like React.js, Ember and Angular to run complex javascript tasks on the page and it's still getting indexed by Google[1](http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157) 3. you can use html5 history api (pushState, react-router, ember, angular) that allows you to do things like have separate urls for each tab you want to open and Google will index that[1](http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157) So to answer your question you can safely change title and other meta tags from javascript (you can also add something like <https://prerender.io> if you want to support non-Google search engines), just make them accessible as separate urls (otherwise how Google would know that those are different pages to show in search results?). Changing SEO related tags (after user has changed page by clicking on something) is simple: ``` if (document.title != newTitle) { document.title = newTitle; } $('meta[name="description"]').attr("content", newDescription); ``` Just make sure that css and javascript is not blocked in robots.txt, you can use **Fetch as Google** service in Google Webmaster Tools. 1: <http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157>
How to dynamically change a web page's title?
[ "", "javascript", "html", "" ]
I want to store the username/password information of my windows service 'logon as' user in the app.config. So in my Installer, I am trying to grab the username/password from app.config and set the property but I am getting an error when trying to install the service. It works fine if I hard code the username/password, and fails when I try and access the app.config ``` public class Blah : Installer { public Blah() { ServiceProcessInstaller oServiceProcessInstaller = new ServiceProcessInstaller(); ServiceInstaller oServiceInstaller = new ServiceInstaller(); oServiceProcessInstaller.Account = ServiceAccount.User; oServiceProcessInstaller.Username = ConfigurationManager.AppSettings["ServiceProcessUsername"].ToString(); } } ```
The problem is that when your installer runs, you are still in installation phase and your application hasn't been fully installed. The app.config will only be available when the actual application is run. You can however do the following: 1. Prompt the user for the username and password within the installer (or on the command line). 2. Pass this information to your installer class (google it) 3. Within your installer class, there is a variable that tells you the installation path 4. Within the appropriate event in the installer, use System.IO functions to open the app.config file and insert the user entered information
Just some ideas on accessing config files inside an installer. ``` Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyPath); ConnectionStringsSection csSection = config.ConnectionStrings; ``` Assembly Path can be gotten several ways: Inside Installer class implementation with: ``` this.Context.Parameters["assemblypath"].ToString(); ``` or sometimes with reflection: ``` Assembly service = Assembly.GetAssembly(typeof(MyInstaller)); string assemblyPath = service.Location; ```
Windows service, can't access app.config from within my Installer's constructor
[ "", "c#", ".net", "security", "configuration", "windows-services", "" ]
I am working on project in Linux which involves 1) Static Lib in C++ 2) GUI developed in C++/QT which uses static lib. Now both the lib and gui are build from command prompt using makefiles. I am trying to debug both like when I hit one button, call should go from GUI to lib. Is it possible to do like this in Linux with eclipse? I can easily follow same debugging procedure in Windows using Visual studio and attaching lib to GUI but I cannot find any good way to do here with eclipse. I have tried many IDEs/debuggers like Anjuta Code Blocks. DDD,Kdbg but none is working properly. I am not sure that if I am wrong or is it much complex to debug? Can some one suggest one proper way to debug ?
Well I figured it out.. I am currently using Kdevelop.. With Kdevelp we can create QT project as well as c++(lib) project. And there is option to attach process also. So I can step through lib code by attaching GUI .
There shouldn't be any problem with debugging a static library as the relevant portions of it will be built in to the binary that you are debugging. If you are having problems then some things to check are that both the library and the binary are built with debugging information (usually the option `-g` to the compiler on linux) and that your debugger has access to the source code to the library. Can you be any more specific about how debugging isn't working? It sounds like 'stepping in' to a library function isn't working as you are expecting it to.
Debugging C++ lib with eclipse
[ "", "c++", "linux", "debugging", "" ]
I have a table with almost 800,000 records and I am currently using dynamic sql to generate the query on the back end. The front end is a search page which takes about 20 parameters and depending on if a parameter was chosen, it adds an " AND ..." to the base query. I'm curious as to if dynamic sql is the right way to go ( doesn't seem like it because it runs slow). I am contemplating on just creating a denormalized table with all my data. Is this a good idea or should I just build the query all together instead of building it piece by piece using the dynamic sql. Last thing, is there a way to speed up dynamic sql?
It is more likely that your indexing (or lack thereof) is causing the slowness than the dynamic SQL. What does the execution plan look like? Is the same query slow when executed in SSMS? What about when it's in a stored procedure? If your table is an unindexed heap, it will perform poorly as the number of records grows - this is regardless of the query, and a dynamic query can actually perform better as the table nature changes because a dynamic query is more likely to have its query plan re-evaluated when it's not in the cache. This is not normally an issue (and I would not classify it as a design advantage of dynamic queries) except in the early stages of a system when SPs have not been recompiled, but statistics and query plans are out of date, but the volume of data has just drastically changed. Not the static one yet. I have with the dynamic query, but it does not give any optimizations. If I ran it with the static query and it gave suggestions, would applying them affect the dynamic query? – Xaisoft (41 mins ago) Yes, the dynamic query (EXEC (@sql)) is probably not going to be analyzed unless you analyzed a workload file. – Cade Roux (33 mins ago) When you have a search query across multiple tables that are joined, the columns with indexes need to be the search columns as well as the primary key/foreign key columns - but it depends on the cardinality of the various tables. The tuning analyzer should show this. – Cade Roux (22 mins ago)
I'd just like to point out that if you use this style of optional parameters: ``` AND (@EarliestDate is Null OR PublishedDate < @EarliestDate) ``` The query optimizer will have no idea whether the parameter is there or not when it produces the query plan. I have seen cases where the optimizer makes bad choices in these cases. A better solution is to build the sql that uses only the parameters you need. The optimizer will make the most efficient execution plan in these cases. Be sure to use parameterized queries so that they are reusable in the plan cache.
Is a dynamic sql stored procedure a bad thing for lots of records?
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
* I have a *Client* and *Groupe* Model. * A *Client* can be part of multiple *groups*. * *Clients* that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (*ClientGroupe*) comes in with that extra data. For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing? ## Here are my models: ``` class Groupe(models.Model): nom = models.CharField(max_length=1500, blank=True) class Client(models.Model): nom = models.CharField(max_length=450, blank=True) prenom = models.CharField(max_length=450, blank=True) groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe') class ClientGroupe(models.Model): client = models.ForeignKey(Client) groupe = models.ForeignKey(Groupe) dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate class Meta: db_table = u'clients_groupes' ``` ## and here's my view: ``` def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) dict = { "form": form , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) if form.is_valid(): client_mod = form.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) ``` **EDIT**: and here's the ClientForm code: ``` class ClientForm(ModelForm): class Meta: model = Client ``` **EDIT #2**: here's the error message: ``` AttributeError at /client/445/ Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Request Method: POST Request URL: http://localhost/client/445/ Exception Type: AttributeError Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574 Python Executable: C:\xampp\apache\bin\apache.exe Python Version: 2.5.2 ```
``` … if form.is_valid(): client_mod = form.save(commit=False) client_mod.save() for groupe in form.cleaned_data.get('groupes'): clientgroupe = ClientGroupe(client=client_mod, groupe=groupe) clientgroupe.save() … ```
If you use the save method right now, Django will try to save using the manager (which Django doesn't allow). Unfortunately, the behavior you want is a little bit trickier than what `ModelForm` does by default. What you need to do is create a *formset*. First of all, you will need to change the options of your `ClientForm` so that it doesn't display the `groupes` attribute. ``` class ClientForm(ModelForm): class Meta: model = Client exclude = ('groupes',) ``` Next, you must change the view to display the formset: ``` from django.forms.models import inlineformset_factory def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) # Create the formset class GroupeFormset = inlineformset_factory(Client, Groupe) # Create the formset formset = GroupeFormset(instance = client) dict = { "form": form , "formset" : formset , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) formset = GroupeFormset(request.POST, instance = client) if form.is_valid() and formset.is_valid(): client_mod = form.save() formset.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) ``` And obviously, you must also tweak your template to render the formset. If you need any other advice on formsets, see these articles: [Model formsets](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets) [Formsets](http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets)
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?
[ "", "python", "django", "django-models", "django-templates", "django-forms", "" ]
I prefer to use OOP in large scale projects like the one I'm working on right now. I need to create several classes in JavaScript but, if I'm not mistaken, there are at least a couple of ways to go about doing that. What would be the syntax and why would it be done in that way? I would like to avoid using third-party libraries - at least at first. Looking for other answers, I found the article *[Object-Oriented Programming with JavaScript, Part I: Inheritance - Doc JavaScript](http://www.webreference.com/js/column79/)* that discusses object-oriented programming in JavaScript. Is there a better way to do inheritance?
Here's the way to do it without using any external libraries: ``` // Define a class like this function Person(name, gender){ // Add object properties like this this.name = name; this.gender = gender; } // Add methods like this. All Person objects will be able to invoke this Person.prototype.speak = function(){ alert("Howdy, my name is" + this.name); }; // Instantiate new objects with 'new' var person = new Person("Bob", "M"); // Invoke methods like this person.speak(); // alerts "Howdy, my name is Bob" ``` Now the real answer is a whole lot more complex than that. For instance, there is no such thing as classes in JavaScript. JavaScript uses a `prototype`-based inheritance scheme. In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript. You'll want to check out at least [Prototype](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) and [jQuery](http://en.wikipedia.org/wiki/JQuery). Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow. If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery. As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it.
The best way to define a class in JavaScript is to not define a class. Seriously. There are several different flavors of object-orientation, some of them are: * class-based OO (first introduced by Smalltalk) * prototype-based OO (first introduced by Self) * multimethod-based OO (first introduced by CommonLoops, I think) * predicate-based OO (no idea) And probably others I don't know about. JavaScript implements prototype-based OO. In prototype-based OO, new objects are created by copying other objects (instead of being instantiated from a class template) and methods live directly in objects instead of in classes. Inheritance is done via delegation: if an object doesn't have a method or property, it is looked up on its prototype(s) (i.e. the object it was cloned from), then the prototype's prototypes and so on. In other words: there are no classes. JavaScript actually has a nice tweak of that model: constructors. Not only can you create objects by copying existing ones, you can also construct them "out of thin air", so to speak. If you call a function with the `new` keyword, that function becomes a constructor and the `this` keyword will not point to the current object but instead to a newly created "empty" one. So, you can configure an object any way you like. In that way, JavaScript constructors can take on one of the roles of classes in traditional class-based OO: serving as a template or blueprint for new objects. Now, JavaScript is a very powerful language, so it is quite easy to implement a class-based OO system *within JavaScript* if you want to. However, you should only do this if you really have a need for it and not just because that's the way Java does it.
What techniques can be used to define a class in JavaScript, and what are their trade-offs?
[ "", "javascript", "oop", "class", "" ]
Consider the following: ``` <div onclick="alert('you clicked the header')" class="header"> <span onclick="alert('you clicked inside the header');">something inside the header</span> </div> ``` How can I make it so that when the user clicks the span, it does not fire the `div`'s click event?
Use [event.stopPropagation()](https://developer.mozilla.org/en/DOM/event.stopPropagation). ``` <span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span> ``` For IE: `window.event.cancelBubble = true` ``` <span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span> ```
There are two ways to get the event object from inside a function: 1. The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+) 2. The window.event object in Internet Explorer (<=8) If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following: ``` function(e) { var event = e || window.event; [...]; } ``` which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an `e` object to use. In that case you have to take advantage of the `arguments` collection which is always available and refers to the complete set of arguments passed to a function: ``` onclick="var event = arguments[0] || window.event; [...]" ``` However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.
How to stop event propagation with inline onclick attribute?
[ "", "javascript", "html", "events", "dom", "" ]
From a web service (WCF), I want an endpoint to take 10 seconds to finish. Is there a way I can do a `thread.sleep(10);` on the method?
You could create a wrapper method which does the appropriate sleep. ``` Thread.Sleep(TimeSpan.FromSeconds(10)) ```
Start a new thread that sleeps for 10 sec, then return, that way the time that the methos takes to run won't add to the 10 seconds ``` using System.Threading; public static WCF(object obj) { Thread newThread = new Thread(new ThreadStart(Work)); newThread.Start(); //do method here newThread.Join(); return obj; } static void Work() { Thread.Sleep(10000); } ```
Calling a C# method, and make it take 10 seconds to return
[ "", "c#", ".net", "wcf", "multithreading", "" ]
I am working with an object which has sub objects within (see example below). I am attempting to bind a `List<rootClass>` to the datagrid. When I bind the `List<>`, in the cell that contains the `subObject`, I see the following value `... "namespace.subObject" ...` the string values display correctly. Ideally I would like to see the “Description” property of the `subObject` in the datacell. How can I map the `subObject.Description` to show in the datacell? ``` public class subObject { int id; string description; public string Description { get { return description; } } } public class rootClass { string value1; subObject value2; string value3; public string Value1 { get { return value1; } } public subObject Value2 { get { return value2; } } public string Value3 { get { return value3; } } } ```
If I'm not mistaken, it shows the result of calling .ToString() on your subObject, so you can override that to return the contents of Description. Have you tried just binding to Value1.Description? (I'm guessing it doesn't work). I have a class that can be used instead of List when binding, that will handle this, it implements ITypedList, which allows a collection to provide more "properties" for its objects, including calculated properties. The last version of the files I have are here: <https://gist.github.com/lassevk/64ecea836116882a5d59b0f235858044> To use: ``` List<rootClass> yourList = ... TypedListWrapper<rootClass> bindableList = new TypedListWrapper<rootClass>(yourList); bindableList.BindableProperties = "Value1;Value2.Description;Value3.Description"; gridView1.DataSource = bindableList; ``` Basically you bind to an instance of `TypedList<T>` instead of `List<T>`, and adjust the BindableProperties property. I have some changes in the work, including one that just builds up BindableProperties automatically as it goes, but it isn't in the trunk yet. You can also add calculated properties, like this: ``` yourList.AddCalculatedProperty<Int32>("DescriptionLength", delegate(rootClass rc) { return rc.Value2.Description.Length; }); ``` or with .NET 3.5: ``` yourList.AddCalculatedProperty<Int32>("DescriptionLength", rc => rc.Value2.Description.Length); ```
Since you mention `DataGridViewColumn` (tags), I assume you mean winforms. Accessing sub-properties is a pain; the currency-manager is bound to the list, so you only have access to immediate properties by default; however, you can get past this *if you absolutely need* by using a custom type descriptor. You would need to use a different token too, like "Foo\_Bar" instead of "Foo.Bar". However, this is a **major** amount of work that requires knowledge of `PropertyDescriptor`, `ICustomTypeDescriptor` and probably `TypeDescriptionProvider`, and almost certainly isn't worth it, The simplest fix is to expose the property as a shim / pass-thru: ``` public string Value2Description { get {return Value2.Description;} // maybe a null check too } ``` Then bind to "Value2Description" etc.
Binding a object with a sub objects as properties to a datagrid
[ "", "c#", "datagrid", "binding", "object", "datagridviewcolumn", "" ]
I'm currently writing a data access layer for an application. The access layer makes extensive use of linq classes to return data. Currently in order to reflect data back to the database I've added a private data context member and a public save method. The code looks something like this: ``` private DataContext myDb; public static MyClass GetMyClassById(int id) { DataContext db = new DataContext(); MyClass result = (from item in db.MyClasss where item.id == id select item).Single(); result.myDb = db; return result; } public void Save() { db.SubmitChanges(); } ``` That's a gross over simplification but it gives the general idea. Is there a better way to handle that sort of pattern? Should I be instantiating a new data context every time i want to visit the db?
It actually doesn't matter too much. I asked Matt Warren from the LINQ to SQL team about this a while ago, and here's the reply: > There are a few reasons we implemented > IDisposable: > > If application logic needs to hold > onto an entity beyond when the > DataContext is expected to be used or > valid you can enforce that contract by > calling Dispose. Deferred loaders in > that entity will still be referencing > the DataContext and will try to use it > if any code attempts to navigate the > deferred properties. These attempts > will fail. Dispose also forces the > DataContext to dump its cache of > materialized entities so that a single > cached entity will not accidentally > keep alive all entities materialized > through that DataContext, which would > otherwise cause what appears to be a > memory leak. > > The logic that automatically closes > the DataContext connection can be > tricked into leaving the connection > open. The DataContext relies on the > application code enumerating all > results of a query since getting to > the end of a resultset triggers the > connection to close. If the > application uses IEnumerable's > MoveNext method instead of a foreach > statement in C# or VB, you can exit > the enumeration prematurely. If your > application experiences problems with > connections not closing and you > suspect the automatic closing behavior > is not working you can use the Dispose > pattern as a work around. But basically you don't *really* need to dispose of them in most cases - and that's by design. I personally prefer to do so anyway, as it's easier to follow the rule of "dispose of everything which implements IDisposable" than to remember a load of exceptions to it - but you're unlikely to leak a resource if you *do* forget to dispose of it.
Treat your datacontext as a resource. And the rule of using resource says > "acquire a resource as late as > possible, release it as soon as its > safe"
When should I dispose of a data context
[ "", "c#", "linq", "linq-to-sql", "" ]
Is there a way to (ab)use the **C** preprocessor to emulate namespaces in **C**? I'm thinking something along these lines: ``` #define NAMESPACE name_of_ns some_function() { some_other_function(); } ``` This would get translated to: ``` name_of_ns_some_function() { name_of_ns_some_other_function(); } ```
When using namespace prefixes, I normally add macros for the shortened names which can be activated via `#define NAMESPACE_SHORT_NAMES` before inclusion of the header. A header foobar.h might look like this: ``` // inclusion guard #ifndef FOOBAR_H_ #define FOOBAR_H_ // long names void foobar_some_func(int); void foobar_other_func(); // short names #ifdef FOOBAR_SHORT_NAMES #define some_func(...) foobar_some_func(__VA_ARGS__) #define other_func(...) foobar_other_func(__VA_ARGS__) #endif #endif ``` If I want to use short names in an including file, I'll do ``` #define FOOBAR_SHORT_NAMES #include "foobar.h" ``` I find this a cleaner and more useful solution than using namespace macros as described by Vinko Vrsalovic (in the comments).
Another alternative would be to declare a struct to hold all your functions, and then define your functions statically. Then you'd only have to worry about name conflicts for the global name struct. ``` // foo.h #ifndef FOO_H #define FOO_H typedef struct { int (* const bar)(int, char *); void (* const baz)(void); } namespace_struct; extern namespace_struct const foo; #endif // FOO_H // foo.c #include "foo.h" static int my_bar(int a, char * s) { /* ... */ } static void my_baz(void) { /* ... */ } namespace_struct const foo = { my_bar, my_baz } // main.c #include <stdio.h> #include "foo.h" int main(void) { foo.baz(); printf("%d", foo.bar(3, "hello")); return 0; } ``` In the above example, `my_bar` and `my_baz` can't be called directly from main.c, only through `foo`. If you have a bunch of namespaces that declare functions with the same signatures, then you can standardize your namespace struct for that set, and choose which namespace to use at runtime. ``` // goo.h #ifndef GOO_H #define GOO_H #include "foo.h" extern namespace_struct const goo; #endif // GOO_H // goo.c #include "goo.h" static int my_bar(int a, char * s) { /* ... */ } static void my_baz(void) { /* ... */ } namespace_struct const goo = { my_bar, my_baz }; // other_main.c #include <stdio.h> #include "foo.h" #include "goo.h" int main(int argc, char** argv) { namespace_struct const * const xoo = (argc > 1 ? foo : goo); xoo->baz(); printf("%d", xoo->bar(3, "hello")); return 0; } ``` The multiple definitions of `my_bar` and `my_baz` don't conflict, since they're defined statically, but the underlying functions are still accessible through the appropriate namespace struct.
Namespaces in C
[ "", "c++", "c", "namespaces", "c-preprocessor", "" ]
Is there any way to have a Windows batch file directly input SQL statements without calling a script? I want the batch file to login to SQL and then enter in the statements directly. **EDIT:** I'm using Oracle v10g
For a single command you can use this trick: ``` echo select * from dual; | sqlplus user/pw@db ```
To run something on SQL server 2005/2008, you could use `sqlcmd` command line utility. `sqlcmd -h` prints the list of switches.
SQL Statements in a Windows Batch File
[ "", "sql", "batch-file", "" ]
What's a good way to ensure that a temp file is deleted if my application closes or crashes? Ideally, I would like to obtain a temp file, use it, and then forget about it. Right now, I keep a list of my temp files and delete them with an EventHandler that's triggered on Application.ApplicationExit. Is there a better way?
Nothing is guaranteed if the process is killed prematurely, however, I use "`using`" to do this.. ``` using System; using System.IO; sealed class TempFile : IDisposable { string path; public TempFile() : this(System.IO.Path.GetTempFileName()) { } public TempFile(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); this.path = path; } public string Path { get { if (path == null) throw new ObjectDisposedException(GetType().Name); return path; } } ~TempFile() { Dispose(false); } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { GC.SuppressFinalize(this); } if (path != null) { try { File.Delete(path); } catch { } // best effort path = null; } } } static class Program { static void Main() { string path; using (var tmp = new TempFile()) { path = tmp.Path; Console.WriteLine(File.Exists(path)); } Console.WriteLine(File.Exists(path)); } } ``` Now when the `TempFile` is disposed or garbage-collected the file is deleted (if possible). You could obviously use this as tightly-scoped as you like, or in a collection somewhere.
Consider using the FileOptions.DeleteOnClose flag: ``` using (FileStream fs = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.RandomAccess | FileOptions.DeleteOnClose)) { // temp file exists } // temp file is gone ```
How do I automatically delete temp files in C#?
[ "", "c#", ".net", "temporary-files", "" ]
I have some data stored as `ArrayList`. And when I want to backup this data,java bounds two objects forever. Which means when I change values in data `ArrayList` this changes come to backup. I tried to copy values from data separately to backup in the loop, tried to use method `data.clone()` — nothing helps.
I think you need to `.clone()` the individual objects. Cloning the `ArrayList` is not "deep"; it will only clone the references to the object.
Your question isn't very clear. If you clone() an ArrayList, the clone will not be modified if you change the contents of the original (ie if you add or remove elements) but it's a "shallow copy" so if you change the actual objects in the original they will also be changed in the clone. If you want to make a "deep copy", so that changes to the actual objects will not affect the backups of them in the clone, then you need to create a new ArrayList and then go through the original one and for each element, clone it into the new one. As in ``` ArrayList backup = new ArrayList(); for (Object obj : data) backup.add(obj.clone()); ```
How to backup ArrayList in Java?
[ "", "java", "arraylist", "" ]
I recently ran across some 3rd party C# code which does the following: ``` public int RecvByteDataFromPrinter(ref byte[] byteData) { byte[] recvdata = new byte[1024]; ///...fills recvdata array... byteData = recvdata; return SUCCESS; } ``` What does the line "`byteData = recvdata`" actually do in this case? It appears that the goal is to have byteData contain the contents of the recvdata array. However, I was under the impression that you would need to do an `Array.Copy(...)` operation in order for that to happen. Is this actually modifying the byteData reference to point to the newly allocated array? If so, is that array guaranteed to stick around?
Yes, because of ref - it does modify the reference passed. Stick around? you mean - not destroyed? Yes, it will not be GC'd because of a new reference. The old array (passed) might be GC'd though after this assignment if no more references... Array.Copy will actually copy elements, then you don't need "ref", but this will be more time-consuming
You guessed right, the assignment is modifying the byteData array reference to point to the newly allocated array (because of the 'ref' keyword). The callers of the function will "see" the contents of the recvData array (whatever was filled in there). And yes, the array sticks around as long as there's one reference to it left (in this case, whatever array you passed along to this function).
Modifications of arrays passed by reference
[ "", "c#", "arrays", "" ]
I have a form that has a public property ``` public bool cancelSearch = false; ``` I also have a class which is sitting in my bll (business logic layer), in this class I have a method, and in this method I have a loop. I would like to know how can I get the method to recognise the form (this custom class and form1 are in the same namespace). I have tried just Form1. but the intellisense doesn't recognise the property. Also I tried to instantialize the form using Form f1 = winSearch.Form1.ActiveForm; but this too did not help Any ideas?
When you are calling the business logic that needs to know the information pass a reference of the form to the method. Something like. ``` public class MyBLClass { public void DoSomething(Form1 theForm) { //You can use theForm.cancelSearch to get the value } } ``` then when calling it from a Form1 instance ``` MyBlClass myClassInstance = new MyBlClass; myClassInstance.DoSomething(this); ``` **HOWEVER** Really you shouldn't do this as it tightly couples the data, just make a property on your BL class that accepts the parameter and use it that way.
Your question is really not clear. You might want to edit it. ## Advice The form shouldn't pass to your business logic layer... # Solutions to your problem BUT if you really want to (BUT it's really not something to do), you need to pass the reference. You can do it by passing the reference in the constructor of your class, or by a property. ## Method with Constructor ``` public class YourClass { private Form1 youFormRef; public YourClass(Form1 youFormRef) { this.youFormRef = youFormRef; } public void ExecuteWithCancel() { //You while loop here //this.youFormRef.cancelSearch... } } ``` ## Method with Property ``` public class YourClass { private Form1 youFormRef; public int FormRef { set { this.youFormRef = value; } get { return this.youFormRef; } } public void ExecuteWithCancel() { //You while loop here //this.youFormRef.cancelSearch } } ```
C# Winforms: How to get a reference to Form1 design time
[ "", "c#", "winforms", "" ]
Is it possible to somehow change the look/feel of NetBeans? I know it uses Swing and that usually apps using Swing for its UI can usually have their UI scheme changed. The default appearence for OSX is vomitastic and would even settle for just some sort of barebones `default` look. The whole look is just too distracting and unnecessary.
See the answer to this question: [Force look and feel on NetBeans 6.5](https://stackoverflow.com/questions/231738/force-look-and-feel-on-netbeans-65#233855)
Looks like this might be what I was looking for: <http://wiki.netbeans.org/FaqCustomLaf>
Changing NetBeans UI Look/Feel
[ "", "java", "macos", "swing", "netbeans", "interface", "" ]
Are there any tools to give some sort of histogram of where most of the execution time of the program is spent at? This is for a project using c++ in visual studio 2008.
The name you're after is a **profiler**. Try [Find Application Bottlenecks with Visual Studio Profiler](http://msdn.microsoft.com/en-gb/magazine/cc337887.aspx?pr=blog)
You need a [profiler](http://en.wikipedia.org/wiki/Profiler_(computer_science)). Visual Studio Team edition includes a profiler (which is what you are looking for) but you may only have access to the Professional or Express editions. Take a look at these threads for alternatives: [What's your favorite profiling tool (for C++)](https://stackoverflow.com/questions/26663/whats-your-favorite-profiling-tool-for-c) [What are some good profilers for native C++ on Windows?](https://stackoverflow.com/questions/153559/what-are-some-good-profilers-for-native-c-on-windows) You really shouldn't optimize ANY parts of your application until you've measured how long they take to run. Otherwise you may be directing effort in the wrong place, and you may be making things worse, not better.
How do you find the least optimized parts of a program?
[ "", "c++", "visual-studio", "optimization", "profiler", "" ]
Does SQL Server CheckSum calculate a CRC? If not how can I get SQL Server to calculate a CRC on an arbitrary varchar column?
I apologize for the crudity of the model, but this seems to do a correct CRC32 calculation. I'm not a TSQL expert, and I'm sure that this could be improved mightily by a real SQL Server pro... @input is the variable to calculate the CRC32 on. It should be trivial to package this as a sproc or a udf, and the lookup table could be factored out to a permanent table (or even calculated on the fly). Anyway, it seems to work. I'd be interested to see any improvements, as it's always good to learn new tricks :) EDIT: I have checked my results against <http://crc32-checksum.waraxe.us/> and it seems good so far. Andrew ``` DECLARE @input VARCHAR(50) SET @input = 'test' SET NOCOUNT ON DECLARE @tblLookup TABLE (ID INT IDENTITY(0,1) NOT NULL, Value BIGINT) INSERT INTO @tblLookup VALUES (0) INSERT INTO @tblLookup VALUES (1996959894) INSERT INTO @tblLookup VALUES (3993919788) INSERT INTO @tblLookup VALUES (2567524794) INSERT INTO @tblLookup VALUES (124634137) INSERT INTO @tblLookup VALUES (1886057615) INSERT INTO @tblLookup VALUES (3915621685) INSERT INTO @tblLookup VALUES (2657392035) INSERT INTO @tblLookup VALUES (249268274) INSERT INTO @tblLookup VALUES (2044508324) INSERT INTO @tblLookup VALUES (3772115230) INSERT INTO @tblLookup VALUES (2547177864) INSERT INTO @tblLookup VALUES (162941995) INSERT INTO @tblLookup VALUES (2125561021) INSERT INTO @tblLookup VALUES (3887607047) INSERT INTO @tblLookup VALUES (2428444049) INSERT INTO @tblLookup VALUES (498536548) INSERT INTO @tblLookup VALUES (1789927666) INSERT INTO @tblLookup VALUES (4089016648) INSERT INTO @tblLookup VALUES (2227061214) INSERT INTO @tblLookup VALUES (450548861) INSERT INTO @tblLookup VALUES (1843258603) INSERT INTO @tblLookup VALUES (4107580753) INSERT INTO @tblLookup VALUES (2211677639) INSERT INTO @tblLookup VALUES (325883990) INSERT INTO @tblLookup VALUES (1684777152) INSERT INTO @tblLookup VALUES (4251122042) INSERT INTO @tblLookup VALUES (2321926636) INSERT INTO @tblLookup VALUES (335633487) INSERT INTO @tblLookup VALUES (1661365465) INSERT INTO @tblLookup VALUES (4195302755) INSERT INTO @tblLookup VALUES (2366115317) INSERT INTO @tblLookup VALUES (997073096) INSERT INTO @tblLookup VALUES (1281953886) INSERT INTO @tblLookup VALUES (3579855332) INSERT INTO @tblLookup VALUES (2724688242) INSERT INTO @tblLookup VALUES (1006888145) INSERT INTO @tblLookup VALUES (1258607687) INSERT INTO @tblLookup VALUES (3524101629) INSERT INTO @tblLookup VALUES (2768942443) INSERT INTO @tblLookup VALUES (901097722) INSERT INTO @tblLookup VALUES (1119000684) INSERT INTO @tblLookup VALUES (3686517206) INSERT INTO @tblLookup VALUES (2898065728) INSERT INTO @tblLookup VALUES (853044451) INSERT INTO @tblLookup VALUES (1172266101) INSERT INTO @tblLookup VALUES (3705015759) INSERT INTO @tblLookup VALUES (2882616665) INSERT INTO @tblLookup VALUES (651767980) INSERT INTO @tblLookup VALUES (1373503546) INSERT INTO @tblLookup VALUES (3369554304) INSERT INTO @tblLookup VALUES (3218104598) INSERT INTO @tblLookup VALUES (565507253) INSERT INTO @tblLookup VALUES (1454621731) INSERT INTO @tblLookup VALUES (3485111705) INSERT INTO @tblLookup VALUES (3099436303) INSERT INTO @tblLookup VALUES (671266974) INSERT INTO @tblLookup VALUES (1594198024) INSERT INTO @tblLookup VALUES (3322730930) INSERT INTO @tblLookup VALUES (2970347812) INSERT INTO @tblLookup VALUES (795835527) INSERT INTO @tblLookup VALUES (1483230225) INSERT INTO @tblLookup VALUES (3244367275) INSERT INTO @tblLookup VALUES (3060149565) INSERT INTO @tblLookup VALUES (1994146192) INSERT INTO @tblLookup VALUES (31158534) INSERT INTO @tblLookup VALUES (2563907772) INSERT INTO @tblLookup VALUES (4023717930) INSERT INTO @tblLookup VALUES (1907459465) INSERT INTO @tblLookup VALUES (112637215) INSERT INTO @tblLookup VALUES (2680153253) INSERT INTO @tblLookup VALUES (3904427059) INSERT INTO @tblLookup VALUES (2013776290) INSERT INTO @tblLookup VALUES (251722036) INSERT INTO @tblLookup VALUES (2517215374) INSERT INTO @tblLookup VALUES (3775830040) INSERT INTO @tblLookup VALUES (2137656763) INSERT INTO @tblLookup VALUES (141376813) INSERT INTO @tblLookup VALUES (2439277719) INSERT INTO @tblLookup VALUES (3865271297) INSERT INTO @tblLookup VALUES (1802195444) INSERT INTO @tblLookup VALUES (476864866) INSERT INTO @tblLookup VALUES (2238001368) INSERT INTO @tblLookup VALUES (4066508878) INSERT INTO @tblLookup VALUES (1812370925) INSERT INTO @tblLookup VALUES (453092731) INSERT INTO @tblLookup VALUES (2181625025) INSERT INTO @tblLookup VALUES (4111451223) INSERT INTO @tblLookup VALUES (1706088902) INSERT INTO @tblLookup VALUES (314042704) INSERT INTO @tblLookup VALUES (2344532202) INSERT INTO @tblLookup VALUES (4240017532) INSERT INTO @tblLookup VALUES (1658658271) INSERT INTO @tblLookup VALUES (366619977) INSERT INTO @tblLookup VALUES (2362670323) INSERT INTO @tblLookup VALUES (4224994405) INSERT INTO @tblLookup VALUES (1303535960) INSERT INTO @tblLookup VALUES (984961486) INSERT INTO @tblLookup VALUES (2747007092) INSERT INTO @tblLookup VALUES (3569037538) INSERT INTO @tblLookup VALUES (1256170817) INSERT INTO @tblLookup VALUES (1037604311) INSERT INTO @tblLookup VALUES (2765210733) INSERT INTO @tblLookup VALUES (3554079995) INSERT INTO @tblLookup VALUES (1131014506) INSERT INTO @tblLookup VALUES (879679996) INSERT INTO @tblLookup VALUES (2909243462) INSERT INTO @tblLookup VALUES (3663771856) INSERT INTO @tblLookup VALUES (1141124467) INSERT INTO @tblLookup VALUES (855842277) INSERT INTO @tblLookup VALUES (2852801631) INSERT INTO @tblLookup VALUES (3708648649) INSERT INTO @tblLookup VALUES (1342533948) INSERT INTO @tblLookup VALUES (654459306) INSERT INTO @tblLookup VALUES (3188396048) INSERT INTO @tblLookup VALUES (3373015174) INSERT INTO @tblLookup VALUES (1466479909) INSERT INTO @tblLookup VALUES (544179635) INSERT INTO @tblLookup VALUES (3110523913) INSERT INTO @tblLookup VALUES (3462522015) INSERT INTO @tblLookup VALUES (1591671054) INSERT INTO @tblLookup VALUES (702138776) INSERT INTO @tblLookup VALUES (2966460450) INSERT INTO @tblLookup VALUES (3352799412) INSERT INTO @tblLookup VALUES (1504918807) INSERT INTO @tblLookup VALUES (783551873) INSERT INTO @tblLookup VALUES (3082640443) INSERT INTO @tblLookup VALUES (3233442989) INSERT INTO @tblLookup VALUES (3988292384) INSERT INTO @tblLookup VALUES (2596254646) INSERT INTO @tblLookup VALUES (62317068) INSERT INTO @tblLookup VALUES (1957810842) INSERT INTO @tblLookup VALUES (3939845945) INSERT INTO @tblLookup VALUES (2647816111) INSERT INTO @tblLookup VALUES (81470997) INSERT INTO @tblLookup VALUES (1943803523) INSERT INTO @tblLookup VALUES (3814918930) INSERT INTO @tblLookup VALUES (2489596804) INSERT INTO @tblLookup VALUES (225274430) INSERT INTO @tblLookup VALUES (2053790376) INSERT INTO @tblLookup VALUES (3826175755) INSERT INTO @tblLookup VALUES (2466906013) INSERT INTO @tblLookup VALUES (167816743) INSERT INTO @tblLookup VALUES (2097651377) INSERT INTO @tblLookup VALUES (4027552580) INSERT INTO @tblLookup VALUES (2265490386) INSERT INTO @tblLookup VALUES (503444072) INSERT INTO @tblLookup VALUES (1762050814) INSERT INTO @tblLookup VALUES (4150417245) INSERT INTO @tblLookup VALUES (2154129355) INSERT INTO @tblLookup VALUES (426522225) INSERT INTO @tblLookup VALUES (1852507879) INSERT INTO @tblLookup VALUES (4275313526) INSERT INTO @tblLookup VALUES (2312317920) INSERT INTO @tblLookup VALUES (282753626) INSERT INTO @tblLookup VALUES (1742555852) INSERT INTO @tblLookup VALUES (4189708143) INSERT INTO @tblLookup VALUES (2394877945) INSERT INTO @tblLookup VALUES (397917763) INSERT INTO @tblLookup VALUES (1622183637) INSERT INTO @tblLookup VALUES (3604390888) INSERT INTO @tblLookup VALUES (2714866558) INSERT INTO @tblLookup VALUES (953729732) INSERT INTO @tblLookup VALUES (1340076626) INSERT INTO @tblLookup VALUES (3518719985) INSERT INTO @tblLookup VALUES (2797360999) INSERT INTO @tblLookup VALUES (1068828381) INSERT INTO @tblLookup VALUES (1219638859) INSERT INTO @tblLookup VALUES (3624741850) INSERT INTO @tblLookup VALUES (2936675148) INSERT INTO @tblLookup VALUES (906185462) INSERT INTO @tblLookup VALUES (1090812512) INSERT INTO @tblLookup VALUES (3747672003) INSERT INTO @tblLookup VALUES (2825379669) INSERT INTO @tblLookup VALUES (829329135) INSERT INTO @tblLookup VALUES (1181335161) INSERT INTO @tblLookup VALUES (3412177804) INSERT INTO @tblLookup VALUES (3160834842) INSERT INTO @tblLookup VALUES (628085408) INSERT INTO @tblLookup VALUES (1382605366) INSERT INTO @tblLookup VALUES (3423369109) INSERT INTO @tblLookup VALUES (3138078467) INSERT INTO @tblLookup VALUES (570562233) INSERT INTO @tblLookup VALUES (1426400815) INSERT INTO @tblLookup VALUES (3317316542) INSERT INTO @tblLookup VALUES (2998733608) INSERT INTO @tblLookup VALUES (733239954) INSERT INTO @tblLookup VALUES (1555261956) INSERT INTO @tblLookup VALUES (3268935591) INSERT INTO @tblLookup VALUES (3050360625) INSERT INTO @tblLookup VALUES (752459403) INSERT INTO @tblLookup VALUES (1541320221) INSERT INTO @tblLookup VALUES (2607071920) INSERT INTO @tblLookup VALUES (3965973030) INSERT INTO @tblLookup VALUES (1969922972) INSERT INTO @tblLookup VALUES (40735498) INSERT INTO @tblLookup VALUES (2617837225) INSERT INTO @tblLookup VALUES (3943577151) INSERT INTO @tblLookup VALUES (1913087877) INSERT INTO @tblLookup VALUES (83908371) INSERT INTO @tblLookup VALUES (2512341634) INSERT INTO @tblLookup VALUES (3803740692) INSERT INTO @tblLookup VALUES (2075208622) INSERT INTO @tblLookup VALUES (213261112) INSERT INTO @tblLookup VALUES (2463272603) INSERT INTO @tblLookup VALUES (3855990285) INSERT INTO @tblLookup VALUES (2094854071) INSERT INTO @tblLookup VALUES (198958881) INSERT INTO @tblLookup VALUES (2262029012) INSERT INTO @tblLookup VALUES (4057260610) INSERT INTO @tblLookup VALUES (1759359992) INSERT INTO @tblLookup VALUES (534414190) INSERT INTO @tblLookup VALUES (2176718541) INSERT INTO @tblLookup VALUES (4139329115) INSERT INTO @tblLookup VALUES (1873836001) INSERT INTO @tblLookup VALUES (414664567) INSERT INTO @tblLookup VALUES (2282248934) INSERT INTO @tblLookup VALUES (4279200368) INSERT INTO @tblLookup VALUES (1711684554) INSERT INTO @tblLookup VALUES (285281116) INSERT INTO @tblLookup VALUES (2405801727) INSERT INTO @tblLookup VALUES (4167216745) INSERT INTO @tblLookup VALUES (1634467795) INSERT INTO @tblLookup VALUES (376229701) INSERT INTO @tblLookup VALUES (2685067896) INSERT INTO @tblLookup VALUES (3608007406) INSERT INTO @tblLookup VALUES (1308918612) INSERT INTO @tblLookup VALUES (956543938) INSERT INTO @tblLookup VALUES (2808555105) INSERT INTO @tblLookup VALUES (3495958263) INSERT INTO @tblLookup VALUES (1231636301) INSERT INTO @tblLookup VALUES (1047427035) INSERT INTO @tblLookup VALUES (2932959818) INSERT INTO @tblLookup VALUES (3654703836) INSERT INTO @tblLookup VALUES (1088359270) INSERT INTO @tblLookup VALUES (936918000) INSERT INTO @tblLookup VALUES (2847714899) INSERT INTO @tblLookup VALUES (3736837829) INSERT INTO @tblLookup VALUES (1202900863) INSERT INTO @tblLookup VALUES (817233897) INSERT INTO @tblLookup VALUES (3183342108) INSERT INTO @tblLookup VALUES (3401237130) INSERT INTO @tblLookup VALUES (1404277552) INSERT INTO @tblLookup VALUES (615818150) INSERT INTO @tblLookup VALUES (3134207493) INSERT INTO @tblLookup VALUES (3453421203) INSERT INTO @tblLookup VALUES (1423857449) INSERT INTO @tblLookup VALUES (601450431) INSERT INTO @tblLookup VALUES (3009837614) INSERT INTO @tblLookup VALUES (3294710456) INSERT INTO @tblLookup VALUES (1567103746) INSERT INTO @tblLookup VALUES (711928724) INSERT INTO @tblLookup VALUES (3020668471) INSERT INTO @tblLookup VALUES (3272380065) INSERT INTO @tblLookup VALUES (1510334235) INSERT INTO @tblLookup VALUES (755167117) DECLARE @crc BIGINT, @len INT, @i INT, @index INT DECLARE @tblval BIGINT SET @crc = 0xFFFFFFFF SET @len = LEN(@input) SET @i = 1 WHILE @i <= @len BEGIN SET @index = ((@crc & 0xff) ^ ASCII(SUBSTRING(@input, @i, 1))) SET @tblval = (SELECT Value FROM @tblLookup WHERE ID = @Index) SET @crc = (@crc / 256) ^ @tblval SET @i = @i + 1 END SET @crc = ~@crc SELECT @crc as CRC32, CONVERT(VARBINARY(4), @crc) as CRC32Hex ```
I shortened Andrew Rollings' script to 11 lines, so he really gets the credit. This will run in SQL 2008 or higher. If you set the variable values after the DECLARE, it will run in SQL 2005. In 2005 and up the character limit is 2048, in SQL 2000 it's something like 512 (I can't remember how many spt\_values of type P there are in SQL 2000). But this could be modified if necessary. ``` DECLARE @input VARCHAR(50) SET @input = 'test' SET NOCOUNT ON DECLARE @crc bigint = 0xFFFFFFFF, @Lookup varbinary(2048) = 0x0000000077073096EE0E612C990951BA076DC419706AF48FE963A5359E6495A30EDB883279DCB8A4E0D5E91E97D2D98809B64C2B7EB17CBDE7B82D0790BF1D911DB710646AB020F2F3B9714884BE41DE1ADAD47D6DDDE4EBF4D4B55183D385C7136C9856646BA8C0FD62F97A8A65C9EC14015C4F63066CD9FA0F3D638D080DF53B6E20C84C69105ED56041E4A26771723C03E4D14B04D447D20D85FDA50AB56B35B5A8FA42B2986CDBBBC9D6ACBCF94032D86CE345DF5C75DCD60DCFABD13D5926D930AC51DE003AC8D75180BFD0611621B4F4B556B3C423CFBA9599B8BDA50F2802B89E5F058808C60CD9B2B10BE9242F6F7C8758684C11C1611DABB6662D3D76DC419001DB710698D220BCEFD5102A71B1858906B6B51F9FBFE4A5E8B8D4337807C9A20F00F9349609A88EE10E98187F6A0DBB086D3D2D91646C97E6635C016B6B51F41C6C6162856530D8F262004E6C0695ED1B01A57B8208F4C1F50FC45765B0D9C612B7E9508BBEB8EAFCB9887C62DD1DDF15DA2D498CD37CF3FBD44C654DB261583AB551CEA3BC0074D4BB30E24ADFA5413DD895D7A4D1C46DD3D6F4FB4369E96A346ED9FCAD678846DA60B8D044042D7333031DE5AA0A4C5FDD0D7CC95005713C270241AABE0B1010C90C20865768B525206F85B3B966D409CE61E49F5EDEF90E29D9C998B0D09822C7D7A8B459B33D172EB40D81B7BD5C3BC0BA6CADEDB883209ABFB3B603B6E20C74B1D29AEAD547399DD277AF04DB261573DC1683E3630B1294643B840D6D6A3E7A6A5AA8E40ECF0B9309FF9D0A00AE277D079EB1F00F93448708A3D21E01F2686906C2FEF762575D806567CB196C36716E6B06E7FED41B7689D32BE010DA7A5A67DD4ACCF9B9DF6F8EBEEFF917B7BE4360B08ED5D6D6A3E8A1D1937E38D8C2C44FDFF252D1BB67F1A6BC57673FB506DD48B2364BD80D2BDAAF0A1B4C36034AF641047A60DF60EFC3A867DF55316E8EEF4669BE79CB61B38CBC66831A256FD2A05268E236CC0C7795BB0B4703220216B95505262FC5BA3BBEB2BD0B282BB45A925CB36A04C2D7FFA7B5D0CF312CD99E8B5BDEAE1D9B64C2B0EC63F226756AA39C026D930A9C0906A9EB0E363F720767850500571395BF4A82E2B87A147BB12BAE0CB61B3892D28E9BE5D5BE0D7CDCEFB70BDBDF2186D3D2D4F1D4E24268DDB3F81FDA836E81BE16CDF6B9265B6FB077E118B7477788085AE6FF0F6A7066063BCA11010B5C8F659EFFF862AE69616BFFD3166CCF45A00AE278D70DD2EE4E0483543903B3C2A7672661D06016F74969474D3E6E77DBAED16A4AD9D65ADC40DF0B6637D83BF0A9BCAE53DEBB9EC547B2CF7F30B5FFE9BDBDF21CCABAC28A53B3933024B4A3A6BAD03605CDD7069354DE572923D967BFB3667A2EC4614AB85D681B022A6F2B94B40BBE37C30C8EA15A05DF1B2D02EF8D; SELECT @crc = (@crc / 256) ^ Substring(@Lookup, ((@crc & 0xFF) ^ Ascii(Substring(@input, V.Number, 1))) * 4 + 1, 4) FROM master.dbo.spt_values V WHERE V.type = 'P' AND V.number BETWEEN 1 AND Len(@input) SET @crc = ~@crc; SELECT @crc CRC32, Convert(VARBINARY(4), @crc) CRC32Hex; ```
Does SQL Server CheckSum calculate a CRC? If not how can I get MS SQL to calculate a CRC on an arbitrary varchar column?
[ "", "sql", "sql-server", "" ]
I typically use the below function to return the root URL if I ever need this, but thought to ask if jQuery had a "one liner" way to do this ... ``` function getRootURL() { var baseURL = location.href; var rootURL = baseURL.substring(0, baseURL.indexOf('/', 7)); // if the root url is localhost, don't add the directory as cassani doesn't use it if (baseURL.indexOf('localhost') == -1) { return rootURL + "/AppName/"; } else { return rootURL + "/"; } } ```
What about ``` document.location.hostname ```
You can just do: `alert(location.host)` With **location.hostname**, you don't get the port (if there's a special port like :8080).
Does jQuery have a built in function to return the rootURL?
[ "", "javascript", "jquery", "" ]
I need to store some values in the database, distance, weight etc. In my model, I have field that contains quantity of something and `IntegerField` with choices option, that determines what this quantity means (length, time duration etc). Should I create a model for units and physical quantity or should I use `IntegerField` that contains the type of unit?
By `field(enum)`" do you mean you are using the [choices](http://docs.djangoproject.com/en/dev/ref/models/fields/#choices) option on a field? A simple set of choices works out reasonably well for small lists of conversions. It allows you to make simplifying assumptions that helps your users (and you) get something that works. Creating a formal model for units should only be done if you have (a) a LOT of units involved, (b) your need to extend it, AND (c) there's some rational expectation that the DB lookups will be of some value. Units don't change all that often. There seems little reason to use the database for this. It seems a lot simpler to hard-code the list of choices. **Choices** You can, for example, use something like this to keep track of conversions. ``` UNIT_CHOICES = ( ('m', 'meters'), ('f', 'feet' ), ('i', 'inches'), ('pt', 'points') ) unit_conversions = { ('m','f'): 3.xyz, ('m','i'): 39.xyz, ('m','pt'): 29.xyz*72, ('f','m'): 1/3.xyz, ('f','i'): 12.0, ('f','pt'): 12.0*72, etc. } ``` Given this mapping, you can get a conversion factor in your conversion method function, do the math, and return the converted unit. ``` class WithUnit( Model ): ... def toUnit( self, someUnit ): if someUnit == self.unit: return self.value elif (someUnit,self.unit) in unit_conversions: return self.value * unit_conversions[(someUnit,self.unit)] else: raise Exception( "Can't convert" ) ``` **Model**. If you want to create a formal model for units, you have to carry around the kind of dimension (length, volume, mass, weight/force, pressure, temperature, etc.) and the various unit conversion factors. This works for everything but temperature, where you have a constant term in addition to a factor. You have to pick a "baseline" set of units (e.g., [MKS](http://www.unc.edu/~rowlett/units/cgsmks.html)) and carry all the multipliers among the various units. You also have to choose how many of the Imperial units to load into your table (fluid ounces, teaspoons, tablespoons, cups, pints, quarts, etc.)
It depends on how you want to use it. Let's say you have length value and two possible units, cm and mm. If you want only to print the value later, you can always print it as `[value]&nbsp;[unit]`. However, if you want to do some calculations with the value, for instance, calculate the area, you need to convert the values to the same units. So you have to define unit conversion table anyway. I would convert the units to the same internal unit *before* I store them in the database, rather than converting them every time I use them. I would add a model for units and physical quantities only if there are too many of them and the conversion is really tricky. Such a model could work as a converter. But for simple cases, like mm⇒cm or inch⇒cm, a static conversion table would suffice.
Django and units conversion
[ "", "python", "django", "" ]
When I'm moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like "file.seek(0)". Is there anything like that for the csv module? Thanks ahead of time ;)
You can seek the file directly. For example: ``` >>> f = open("csv.txt") >>> c = csv.reader(f) >>> for row in c: print row ['1', '2', '3'] ['4', '5', '6'] >>> f.seek(0) >>> for row in c: print row # again ['1', '2', '3'] ['4', '5', '6'] ```
You can still use file.seek(0). For instance, look at the following: ``` import csv file_handle = open("somefile.csv", "r") reader = csv.reader(file_handle) # Do stuff with reader file_handle.seek(0) # Do more stuff with reader as it is back at the beginning now ``` This should work since csv.reader is working with the same.
Python csv.reader: How do I return to the top of the file?
[ "", "python", "csv", "" ]
I'd like to know if there is any .Net class that allows me to know the SSID of the wireless network I'm connected to. So far I only found the library linked below. Is the best I can get or should I use something else? [Managed WiFi](http://www.codeplex.com/managedwifi) (<http://www.codeplex.com/managedwifi>) The method that exploits **WMI** works for Windows XP but is it not working anymore with Windows Vista.
I resolved using the library. It resulted to be quite easy to work with the classes provided: First I had to create a WlanClient object ``` wlan = new WlanClient(); ``` And then I can get the list of the SSIDs the PC is connected to with this code: ``` Collection<String> connectedSsids = new Collection<string>(); foreach (WlanClient.WlanInterface wlanInterface in wlan.Interfaces) { Wlan.Dot11Ssid ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid; connectedSsids.Add(new String(Encoding.ASCII.GetChars(ssid.SSID,0, (int)ssid.SSIDLength))); } ```
We were using the managed wifi library, but it throws exceptions if the network is disconnected during a query. Try: ``` var process = new Process { StartInfo = { FileName = "netsh.exe", Arguments = "wlan show interfaces", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); var output = process.StandardOutput.ReadToEnd(); var line = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(l => l.Contains("SSID") && !l.Contains("BSSID")); if (line == null) { return string.Empty; } var ssid = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries)[1].TrimStart(); return ssid; ```
Get SSID of the wireless network I am connected to with C# .Net on Windows Vista
[ "", "c#", "wifi", "windows-vista", "ssid", "" ]
I have a master page with one form on it. It is a search form which must always be visible. When the button of that form is clicked I want the form data to be sent to search.aspx. The problem is, I don't know how. I cannot set the form action to search.aspx, because all my other pages which use the master form will go to search.aspx. This I don't want. Hope someone can help me out :) Thnx.
In order to pass the values of the control "txtSearch", when Server.Transfer is executed, you could do many things, including passing it via a querystring variable or setting up a session variable, and then check either of those in the Page\_Load event of Search.aspx, and if it's populated, call the event that is fired when the user would hit the submit button on the Search.aspx page. Also, if the Search.aspx file is using the same masterpage, then you can use this.Master.FindControl("txtSearch") to get the control (it you look a the source of the file after it is generated in the browser, you'll notice that controls in the master page aren't really called by their ID, rather that have something appended to them (i.e. it would now possibly be called "ctl00\_txtSearch")
You could create your search form in a separate form, and get it to use GET instead of POST. Either that, or have the master form handle the search button click and use Server.Transfer to go to the search form.
Passing master page form data to another webform
[ "", "c#", "asp.net", "forms", "master-pages", "" ]
I'm working with a start-up, mostly doing system administration and I've come across a some security issues that I'm not really comfortable with. I want to judge whether my expectations are accurate, so I'm looking for some insight into what others have done in this situation, and what risks/problems came up. In particular, how critical are measures like placing admin tools behind a vpn, regular security updates (OS and tools), etc. Keep in mind that as this is a start-up, the main goal is to get as many features as possible out the door quickly, so I'll need as much justification as I can get to get the resources for security (i.e. downtime for upgrades, dev time for application security fixes). Background Info: * Application is LAMP as well as a custom java client-server. * Over the next 3 months, I project about 10k anonymous visitors to the site and up to 1000 authenticated users. * Younger audience (16-25) which is guaranteed to have an above average number of black-hats included. Thanks in advance for your responses, and I'll welcome any related advice.
If security isn't thought of and built into the application and its infrastructure from day one it will be much more difficult to retrofit it in later. Now is the time to build the processes for regular OS/tool patching, upgrades, etc. * What kind of data will users be creating/storing on the site? * What effect will a breach have on your users? * What effect will a breach have on your company? * Will you be able to regain the users' trust after a breach? Since your company is dependent on keeping existing users and attracting new ones, you should present your concerns along the lines of how the users would react to a breach. The higher-ups will understand that the users are your bread and butter.
Also, don't forget you need to have your server secured from current (that is, soon-to-be-past) employees. Several startups were totally wiped due to employee sabotage, e.g. <http://www.geek.com/articles/news/disgruntled-employee-kills-journalspace-with-data-wipe-2009015/>
What are the minimum security precautions to put in place for a startup?
[ "", "java", "security", "lamp", "infrastructure", "" ]
What's the simplest way to get XmlSerializer to also serialize private and "public const" properties of a class or struct? Right not all it will output for me is things that are only public. Making it private or adding const is causing the values to not be serialized.
`XmlSerializer` only looks at public fields and properties. If you need more control, you can implement [IXmlSerializable](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx) and serialize whatever you would like. Of course, serializing a constant doesn't make much sense since you can't deserialize to a constant.
Even though it's not possible to serialize private properties, you can serialize properties with an internal setter, like this one : ``` public string Foo { get; internal set; } ``` To do that, you need to pre-generate the serialization assembly with sgen.exe, and declare this assembly as friend : ``` [assembly:InternalsVisibleTo("MyAssembly.XmlSerializers")] ```
Using XmlSerializer with private and public const properties
[ "", "c#", "xml-serialization", "" ]
When I submit a form in HTML, I can pass a parameter multiple times, e.g. ``` <input type="hidden" name="id" value="2"> <input type="hidden" name="id" value="4"> ``` Then in struts I can have a bean with property String[] id, and it'll populate the array correctly. My question is, how can I do that in Javascript? When I have an array, and I set form.id.value = myArray, it just sets the value to a comma-separated list. So then on the Struts end, I just get one-element array, i.e. the String "2,4". I should add, I need to submit this in a form, so I can't just generate a GET request, e.g. id=2&id=4.
Is this what you're looking for? It generates a hidden form field for each element of a JavaScript array: ``` var el; for (var i = 0; i < myArray.length) { el = document.createElement("input"); el.type = "hidden"; el.name = "id"; el.value = myArray[i]; // Optional: give each input an id so they can easily be accessed individually: el.id = "hidden-myArray-" + i; // Optional: give all inputs a class so they can easily be accessed as a group: el.className = "hidden-myArray"; form.appendChild(el); } ```
Not positive what you're trying to do but here's a go: ``` var inputs = document.getElementsByName('id'); for(var i=0; i<inputs.length; i++) { var input = inputs[i]; input.value = myArray[i]; } ``` That iterates over all the inputs with name '`id`' and assigns the corresponding value from myArray. You better be sure `myArray.length == document.getElementsByName('id').length`
Setting a multi-valued parameter in javascript
[ "", "javascript", "html", "struts", "" ]
This causes a compile-time exception: ``` public sealed class ValidatesAttribute<T> : Attribute { } [Validates<string>] public static class StringValidation { } ``` I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason. Does anyone know why generic types cannot derive from `Attribute`? Any theories?
Well, I can't answer why it's not available, but I *can* confirm that it's not a CLI issue. The CLI spec doesn't mention it (as far as I can see) and if you use IL directly you can create a generic attribute. The part of the C# 3 spec that bans it - section 10.1.4 "Class base specification" doesn't give any justification. The annotated ECMA C# 2 spec doesn't give any helpful information either, although it does provide an example of what's not allowed. My copy of the annotated C# 3 spec should arrive tomorrow... I'll see if that gives any more information. Anyway, it's definitely a language decision rather than a runtime one. EDIT: Answer from Eric Lippert (paraphrased): no particular reason, except to avoid complexity in both the language and compiler for a use case which doesn't add much value.
An attribute decorates a class at compile-time, but a generic class does not receive its final type information until runtime. Since the attribute can affect compilation, it has to be "complete" at compile time. See this [MSDN article](http://msdn.microsoft.com/en-us/library/ms379564.aspx) for more information.
Why does C# forbid generic attribute types?
[ "", "c#", "generics", ".net-attributes", "" ]
I'm a little lost (still working with Ron Jeffries's book). Here's a simple class: ``` public class Model{ private String[] lines; public void myMethod(){ String[] newLines = new String[lines.length + 2]; for (i = 0, i <= lines.length, i++) { newLines[i] = lines[i]; } } } ``` I have another class that initializes `Model`, and an empty array, by setting `myModel = new String[0]`. When I invoke `myModel.myMethod()`, I get a subscript out of range error. Looking at the debugger, what I see is that `myModel.lines` has zero dimensions and zero length. Shouldn't it have a dimension and length of 1? Granted the value of `lines[0]` is `null`, but the array itself shouldn't be, should it? Any thoughts truly appreciated. Randy
I think your example is probably not the same as your actual code based on your description. I think the problem is that arrays are zero-based and thus an array initialized as: string[] lines = new string[0]; has no elements. You need to change your loop so that you check that the index is strictly less than the length of the array. As others have indicated you also need to make sure that the array itself is not null before trying to reference it. My take on your code: ``` public class Model{ private String[] lines = new string[0]; public Model( string[] lines ) { this.lines = lines; } public void myMethod(){ int len = 2; if (lines != null) { len = len + lines.length; } String[] newLines = new String[len]; for (i = 0, i < lines.length, i++) { newLines[i] = lines[i]; } } } ```
lines will be null, so lines.length will throw an exception. I believe your other class initializing "Model" won't help since Lines itself is private. In fact, whatever you are doing to Model is probably illegal in at least 30 states.
How many dimensions in an array with no value
[ "", "java", "arrays", "" ]
I am using Carbide (just upgraded to 2.0) to develop an S60 3rd Edition application. I would like to know the easiest way to change the icon (both the application icon on the device menu **and** the icon at the top left of the main view) because I have the need to skin my application in many different ways as easily as possible. All my efforts with messing around with .mif files have so far failed. I have a 44x44 .svg icon I made with Illustrator, could someone please help me in the right direction? Thanks!
To change the app icon when you run your app use (in the status bar): ``` CEikStatusPane* sp=iEikonEnv->AppUiFactory()->StatusPane(); CAknContextPane* cp=(CAknContextPane *)sp->ControlL(TUid::Uid(EEikStatusPaneUidContext)); _LIT(KContextBitMapFile, "my_bitmap_file.mbm"); CFbsBitmap* bitmap = iEikonEnv->CreateBitmapL(KContextBitMapFile, EMbmBitmap); CleanupStack::PushL(bitmap); CFbsBitmap* bitmapmask = iEikonEnv->CreateBitmapL(KContextBitMapFile, EMbmBitmapMask); CleanupStack::PushL(bitmapmask); cp->SetPicture(bitmap, bitmapmask); CleanupStack::Pop(); // bitmapmask CleanupStack::Pop(); // bitmap DrawNow(); ``` I'm not aware of any possibility of changing the app icon in the menu list programmatically, other than reinstalling the app with different mif file.
<http://wiki.forum.nokia.com/index.php/CS000808_-_Creating_and_adding_an_icon_to_an_S60_3rd_Edition_application>
Carbide / Symbian C++ - Change Application Icon
[ "", "c++", "symbian", "icons", "s60", "carbide", "" ]
It's been suggested that this might be a reasonable approach, in order to minimize changes to an existing server configurations, but is it actually valid/supported? I've not been able to find anything specific either way. In practice, with a JBoss Portal V2.4.2 server, there appears to be some class-loading issues, so things such as the downloadable Stripes example or a standard Wicket quickstart app don't run, but I'm not sure if the problem there is a server-specific one or a generic one - Anyone? Note: This isn't about displaying/moving an existing web-app into a portal, simply if a Portal Server should also be a valid AppServer?
The answer is that yes, it is valid, **but** the specific JBoss Portal V2.4.\* versions appear to have class-loader issues such that only the more basic web-apps will run correctly.
[JSR 286 (Portlet 2.0) spec](http://jcp.org/en/jsr/detail?id=286): > PLT.2.7 > > Relationship with Java 2 > Platform, Standard and Enterprise > Edition > > The Portlet API v2.0 is based on the > Java Platform, Standard Edition 5.0 > and Enterprise Edition v1.4. Portlet > containers should at least meet the > requirements, described in v 1.4 of > the J2EE Specification, for executing > in a J2EE environment. It is therefore not unreasonable to expect standard app-server applications to work under a portal. However, by definition, a portal is going to include more libraries in the global class space. Adding libraries to the container always introduces the risk of incompatibility and the need to manage what classes/resources are exposed to your application and how (application-first class-loading, etcetera). I've had problems in the past with third part libraries whose dependencies conflicted with a version that shipped with the portal. I wouldn't expect dependency management to get any easier. Write once, test everywhere, as they say.
Is it valid to expect a Java Portal Server to host 'standard' Java WebApps?
[ "", "java", "web-applications", "portal", "jboss-portal", "" ]