Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am writing a Django application that has a model for People, and I have hit a snag. I am assigning Role objects to people using a Many-To-Many relationship - where Roles have a name and a weight. I wish to order my list of people by their heaviest role's weight. If I do People.objects.order\_by('-roles\_\_weight'), then I get duplicates when people have multiple roles assigned to them. My initial idea was to add a denormalized field called *heaviest-role-weight* - and sort by that. This could then be updated every time a new role was added or removed from a user. However, it turns out that there is no way to perform a custom action every time a ManyToManyField is updated in Django ([yet](http://code.djangoproject.com/ticket/5390), anyway). So, I thought I could then go completely overboard and write a custom field, descriptor and manager to handle this - but that seems extremely difficult when the ManyRelatedManager is created dynamically for a ManyToManyField. I have been trying to come up with some clever SQL that could do this for me - I'm sure it's possible with a subquery (or a few), but I'd be worried about it not being compatible will all the database backends Django supports. Has anyone done this before - or have any ideas how it could be achieved?
Django 1.1 (currently beta) adds [aggregation](http://docs.djangoproject.com/en/dev/topics/db/aggregation/) support. Your query can be done with something like: ``` from django.db.models import Max People.objects.annotate(max_weight=Max('roles__weight')).order_by('-max_weight') ``` This sorts people by their heaviest roles, without returning duplicates. The generated query is: ``` SELECT people.id, people.name, MAX(role.weight) AS max_weight FROM people LEFT OUTER JOIN people_roles ON (people.id = people_roles.people_id) LEFT OUTER JOIN role ON (people_roles.role_id = role.id) GROUP BY people.id, people.name ORDER BY max_weight DESC ```
Here's a way to do it without an annotation: ``` class Role(models.Model): pass class PersonRole(models.Model): weight = models.IntegerField() person = models.ForeignKey('Person') role = models.ForeignKey(Role) class Meta: # if you have an inline configured in the admin, this will # make the roles order properly ordering = ['weight'] class Person(models.Model): roles = models.ManyToManyField('Role', through='PersonRole') def ordered_roles(self): "Return a properly ordered set of roles" return self.roles.all().order_by('personrole__weight') ``` This lets you say something like: ``` >>> person = Person.objects.get(id=1) >>> roles = person.ordered_roles() ```
Django: Order a model by a many-to-many field
[ "", "sql", "django", "database-design", "django-models", "" ]
I have a .jar file that I would like to be able to call without having to use a full file path to its location. For example, if the .jar file is located at: /some/path/to/thearchive.jar I'd like to be able to run it with: ``` java -jar thearchive.jar ``` instead of: ``` java -jar /some/path/to/thearchive.jar ``` when I'm elsewhere in the directory tree. In my specific case, I'm running a Mac with OS X 10.5.7 installed. Java version "1.5.0\_16". I tried adding "/some/path/to" to PATH, JAVA\_HOME and CLASSPATH, but that didn't work. So, how do I setup to run a .jar from the command line without having to use its full path? UPDATE: Another item to deal with would be arguments. For example: ``` java -jar /some/path/to/thearchive.jar arg1 arg2 ``` This can have an effect on the way the question is dealt with as mentioned in the answers below.
You can add a variable to hold the directory: ``` export JARDIR=/some/path/to java -jar $JARDIR/thearchive.jar ``` I'm not sure you can do it from environment variables implicitly.
No you can't. Running a jar with `-jar` does not involve any kind of classpath mechanism since the jar file *is* the classpath. Alternatively use a shell alias to launch the jar or a small script file.
Can an executable .jar file be called without having to use its full path?
[ "", "java", "command-line", "jar", "" ]
**The problem:** I have a jQuery heavy page that has a built in admin interface. The admin functions only trigger when an admin variable is set. These functions require a second library to work properly and the second file is only included if the user is an admin when the page is first created. The functions will never trigger for normal users and normal users do not get the include for the second library. Is it bad to reference a function does not exist in the files currently included even if that function can never be called? (does that make sense :) **Pseudocode:** *header:* (notice that admin.js is not included) ``` <script type="text/javascript" src="script.js"></script> <script type="text/javascript" src="user.js"></script> ``` *script.js:* (admin functions referenced but can't be executed) ``` admin = false; // Assume this $(".something").dblclick(function(){ if(admin) adminstuff(); // Implemented in admin.js (not included) else userstuff(); }); ``` **Ideas:** I suppose two separate files for users and admins could be used but I feel that would be an overly complicated solution (don't want to maintain two large files with only a few lines of difference). The only reason I include a reference to the admin function in this file is I need to attach it to page elements that get refreshed as a part of the script. When jQuery refreshes the page I need to reattach function to interactive elements. **The Question:** I want to keep things very simple and not have to include file I don't have to if they will not be used by the user. Is this a good way to do this or should I be going another route?
The code should operate without error, since the admin functions without implementation will not be called. The only thing that is really being wasted is bandwidth to transmit the admin code that is not used. However, let me caution against security through obscurity. If the user were to view this code and see that there are admin functions that they cannot access, they might get curious and try to download the "admin.js" file and see what these functions do. If your only block to keeping admin functions from being performed is to stop including the file, then some crafty user will probably quickly find a way to call the admin functions when they should not be able to. If you already do server side authentication/permissions checking for the admin function calls just ignore my previous paragraph :-)
Personally, I would bind (or re-bind) the event in admin.js: ``` $(function() { $(".something").dblclick(function(){ adminstuff(); }); }); function adminstuff() { // ... } ``` That way, the adminstuff() call and the function will not be visible to "normal" users.
A question about referencing functions in Javascript
[ "", "javascript", "jquery", "function", "" ]
Let's say I have two Tables, Lunch and Dinner. I know that both contain the DateTime property "Time". If I have a generic method GetTime, how could I return db.Lunch.Time when T is Lunch and db.Dinner.Time when T is Dinner? I'm trying to achieve this without testing for T individually using typeof, but rather generically. Pseudocode: ``` public T GetTime<T>(DateTime dt) { return MyDataContext.GetTable<T>().Where(entity => entity.Time == dt); } ``` So when I call GetTime<Dinner> it will automatically look in the Dinner Table for all dinner entities with the property time equal to my supplied parameter dt. The problem is that I can't specifiy **entity.Time** in my expression because T is a generic. My question is how to get around that, so that I can look for any T (knowing that all my entities in fact *have* the Time property) without having to create specific methods for Dinner and Lunch.
You'd have to have both classes implement an interface something like this: ``` public interface IMyInterface { DateTime Time{get;set;} } ``` And then in your generic method: ``` public void MyMethod<T>(T item) where T: IMyInterface { //here you can access item.Time } ```
You could use an interface that Lunch and Dinner implement that has a property called Time ``` public interface IMealTime { DateTime Time { get; set; } } public class Lunch : IMealTime { #region IMealTime Members public DateTime Time { get; set; } #endregion } public class Dinner : IMealTime { #region IMealTime Members public DateTime Time { get; set; } #endregion } public class GenericMeal { public DateTime GetMealTime<T>(T meal) where T: IMealTime { return meal.Time; } } ```
Reference generic property in expression
[ "", "c#", "asp.net-mvc", "generics", "lambda", "" ]
I am having difficulty doing regular expressions when there is whitespace and carriage returns in between the text. For example in this case below, how can I get the regular expression to get "`<div id="contentleft">`"? ``` <div id="content"> <div id="contentleft"> <SCRIPT language=JavaScript> ``` I tried ``` id="content">(.*?)<SCRIPT ``` but it doesn't work.
``` $s = '<div id="content"> <div id="contentleft"> <SCRIPT language=JavaScript>'; if( preg_match('/id="content">(.*?)<SCRIPT/s', $s, $matches) ) print $matches[1]."\n"; ``` Dot, by default, matches everything but newlines. `/s` makes it match everything. But really, use a DOM parser. You can walk the tree or you can use an XPath query. Think of it like regexes for XML. ``` $s = '<div id="content"> <div id="contentleft"> <SCRIPT language=JavaScript>'; // Load the HTML $doc = new DOMDocument(); $doc->loadHTML($s); // Use XPath to find the <div id="content"> tag's descendants. $xpath = new DOMXPath($doc); $entries = $xpath->query("//div[@id='content']/descendant::*"); foreach( $nodes as $node ) { // Stop when we see <script ...> if( $node->nodeName == "script" ) break; // do what you want with the content } ``` XPath is extremely powerful. [Here's some examples.](http://www.zvon.org/xxl/XPathTutorial/Output/examples.html) PS I'm sure (I hope) the above code can be tightened up some.
Take a look into the PCRE modifiers: <https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php> You can apply the s modifier, like `'/id="content">(.*?)<SCRIPT/s'` (Although, watch out, since it changes the way `^` and `$` work, too. Otherwise, you can do `'/id="content">((.|\n)*?)<SCRIPT/'` EDIT: oops, wrong modifier...
PHP Regex Difficulty
[ "", "php", "regex", "" ]
I'm rediscovering Java, and I'm a little lost about how to do this within Eclipse. I am looking sort of for Visual Studio "object browser" functionality, but I'd settle for a quick list of types that are defined within my referenced external jar files.
Add the jar to project's build path (right-click menu) It would appear as a Jar (glass one), with arrow to open it as if it was a directory. Now, open it, you'll see its contents - packages containing classes. But, I advice you to look for javadocs first. Who needs that class list when you've got javadoc!
The Package Explorer allows you to browse the contents of your project files as objects, once you expand a package you'll see the classes which you can expand a class to see its methods. Similarly projects have a "Reference Libraries" section which will expand to show the jars a project depends on and so allow browsing into their packages/classes/methods. When looking at a class/interface you can hit F4 (or use the right click menu) to see it in its type hierarchy.
From within the Eclipse IDE, how can I show a list of types that exist in a jar?
[ "", "java", "eclipse", "jar", "" ]
The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use? The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've recently decided to start on a bigger project. I'm considering creating a Magic: the Gathering booster draft simulator, but I'm not sure if it is feasible given my skill set so I'm asking around before I get started. The application would need to send data between computers about which cards are being picked/passed. Thanks!
[Twisted](http://twistedmatrix.com/) is a python event-driven networking engine licensed under MIT. Means that a single machine can communicate with one or more other machines, while doing other things between data being received and sent, all asynchronously, and running a in a single thread/process. It supports many protocols out of the box, so you can just as well using an existing one. That's better because you get support for the protocol from 3rd party software (i.e. using HTTP for communication means middleware software that uses HTTP will be compatible: proxies etc.) It also makes easy to create your own communication protocol, if that's what you want. The [documentation](https://docs.twisted.org/en/stable/) is filled with examples.
The standard library includes SocketServer (documented [here](http://docs.python.org/library/socketserver.html)), which might do what you want. However I wonder if a better solution might be to use a message queue. Lots of good implementations already exist, including Python interfaces. I've used [RabbitMQ](http://www.rabbitmq.com/) before. The idea is that the computers both subscribe to the queue, and can either post or listen for events.
Creating connection between two computers in python
[ "", "python", "networking", "" ]
There's a lot of confusion over MVC but after flicking through a Head First patterns book (As a side note I hate that brand, though this example was quite good) it claims that MVC or Model View Controller is a hybrid of multiple patterns - mediator, observer etc... In a recent prototype I did the following, it's C# but should be straightforward. ``` Person : IPerson { public Name { get; set;} public Age { get; set;} } ``` IPerson is just an interface defining the above - I've left it out for simplicity. ``` PersonController : IPersonController { public event DetailsUpdated; public void SetAge(int age); public int GetAge(); public void SetName(string name); public string GetName(); } ``` I know the above could be properties themselves - but this is just a simple example. The event is fired every time some data changes - e.g. in SetAge/SetName. ``` interface IView { void Initialize(); void SetAgeClicked(object sender, EventArgs e); void SetNameClicked(object sender, EventArgs e); } ``` Initialize wires stuff up - e.g. text boxes on the form. SetAge/SetName are the button events - so the form/page etc.. using must have these methods. ``` Form : IView { // IView is implemented. // Form is wired up // Initialize is set etc... } ``` I hear the test of MVC is when you add a new view is it easy to get stuff up and running - well yes it was. However, is this MVC? Is this something else? Any advice/input would be great. It works - it just want to know why though. Thanks.
I would say what you have there is more akin to MVP (Model-View-Presenter) than MVC. There are two main varieties of MVP...Supervising Controller and Passive View. What you have here seems closest to Passive View, which is a pretty classic MVP implementation that people use to improve and abstract WebForms. You can read more about an MVP implementation for WebForms here: <http://haacked.com/archive/2006/08/09/ASP.NETSupervisingControllerModelViewPresenterFromSchematicToUnitTestsToCode.aspx> The same general idea applies to Windows Forms too.
I'll vote something else. The reason I say this is there is a ton of debate on what MVC is. See [What's a controller anyway?](http://c2.com/cgi/wiki?WhatsaControllerAnyway)
Is this MVC? What 'design pattern' have I used?
[ "", "c#", "design-patterns", "model-view-controller", "" ]
A puzzle that hit me. In some simple test harness code, if I stream too many characters to stdout, the program fails. Strange but very reproducable. This may be a Windows only issue, but it's easy to see: ``` #include <iostream> #include <deque> using namespace std; int main() { deque<char> d; char c; while (cin.get(c)) d.push_back(c); for (deque<char>::reverse_iterator j = d.rbegin(); j != d.rend(); j++) cout << (*j); } ``` The previous code just loads a stream of chars from stdin and outputs them in reverse order. It works fine for up to 100K or so characters, but dies with "error writing stdout" message in Windows for files that are larger. It always dies with the same character. A shell command like "cat bigfile.txt | reverse.exe" is all you need to reproduce the problem. Both MSFT and Intel compilers both act similarly. I realize there may be a buffer on stdout, but shouldn't that be flushed automatically when it's filled?
Thanks for all the suggestions, especially to Michael Burr who correctly theorized that the cat command, not reverse.exe, may be failing! That's exactly what it was.. reverse.exe < bigfile.txt works fine, but cat bigfile.txt | reverse.exe fails with "error writing stdout". Now why CAT would fail is also a mystery but at least it's now not something code related.
You may try to force the buffer to flush its content this way: ``` cout << (*j) << std::flush; ``` Otherwise `std::endl` works also, but provide and end of line too (which you don't want I suppose ?)
Limit on cout stream?
[ "", "c++", "windows", "buffer", "stdout", "" ]
I'm writing a .NET wrapper around an old MFC-based library we have. It's based around a class that sends notifications using window messages; it has a function that lets the user pass in a handle to a window, and that window will receive the messages. I could just require the users of my wrapper to subclass `Control` and pass their control's handle in order to receive messages, but that's horrible. I want my wrapper class to have events which fire whenever the old library sends a message, and then I can do the decoding of the message into something sensible. But, I don't want my wrapper class to have to be a control. Is there a way for me to create a 'dummy' window handle, and receive the messages sent to that handle, without creating a window?
There is a concept of [MessageOnly Windows](http://msdn.microsoft.com/en-us/library/ms632599(VS.85).aspx#message_only) which can help you. You may create an internal message only window in your wrapper class and pass this handle to the old library.
You could try creating a thread with a message pump and sending your messages to that. The thread then raises any necessary events that you want to handle in your C# code.
Can I send / receive window messages without a window?
[ "", "c#", ".net", "mfc", "window-handles", "" ]
I'm trying to learn jQuery, but it's coming slowly as I really don't know any JavaScript. My site is in VB.NET and I'm putting jQuery code on both my actual `.ascx` `UserControl` and in a separate file (something like `myscripts.js`). This is because I'm using webforms as I still don't know MVC well enough to implement it, so I have to get the clientID's on the page. What I would like to do is the following: 1. Grab text from a textbox and make it all lowercase 2. Get the username from the login info. I've done this like so on my actual page: ``` var userName = "<%=Split(System.Web.HttpContext.Current.User.Identity.Name.ToLowerInvariant, '|')%>"; ``` 3. Check to see if the username is in the text. If it IS in the text, I want to set a variable to "false", othewise to true. How do I do this?
I am completely ignorant of the ASP.NET side of it, but as far as jQuery and Javascript.... To get the value of a text field, you use the jQuery function [`val()`](http://docs.jquery.com/Attributes/val): ``` var value = $('#mytextbox').val(); ``` To turn a string to lower case, you use the string method [`toLowerCase()`](http://www.w3schools.com/jsref/jsref_toLowerCase.asp): ``` var value = $('#mytextbox').val().toLowerCase(); ``` Since `val()` returns a string we can throw that at the end. To check if a string is within another string, you use the string method [`indexOf()`](http://www.w3schools.com/jsref/jsref_IndexOf.asp): ``` var needle = 'Hello'; var haystack = 'Hello World'; var match = haystack.indexOf(needle); // -1 if no matches, 0 in this case ```
``` var userName = "username as it comes out of your web app"; // stuff happens var $myTextbox = $('#ID_of_textbox'); var userNameIsContained = $myTextbox.val().toLowerCase().indexOf(userName) >= 0; ``` Short explanation: ``` $('#ID_of_textbox') // fetches the jQuery object corresponding to your textbox .val() // the jQuery function that gets the textbox value .toLowerCase() // self explanatory .indexOf() // returns the position of a string in a string (or -1) ``` See the [JavaScript String object reference at w3schools](http://www.w3schools.com/jsref/jsref_obj_string.asp). Alternative (to check if the textbox value *equals* the username): ``` var userNameIsEqual = $myTextbox.val().toLowerCase() == userName; ```
Locating text and performing operation based on its existence
[ "", "javascript", "jquery", "" ]
Is there a simple way of creating a std::string out of an const char[] ? I mean something simpler then: ``` std::stringstream stream; stream << const_char; std::string string = stream.str(); ```
`std::string` has multiple constructors, one of which is `string( const char* str );`. You can use it like this: ``` std::string myString(const_char); ``` You could also use assignment, if you need to set the value at some time later than when the variable is declared: ``` myString = const_char; ```
std::string has a constructor that takes a const char\*, so you can just do: ``` const char* charArray; std::string str(charArray); ```
What is the simplest way to convert a const char[] to a string in c++
[ "", "c++", "" ]
How can one get the name of the class from a static method in that class. For example ``` public class MyClass { public static String getClassName() { String name = ????; // what goes here so the string "MyClass" is returned return name; } } ``` To put it in context, I actually want to return the class name as part of a message in an exception.
In order to support refactoring correctly (rename class), then you should use either: ``` MyClass.class.getName(); // full name with package ``` or (thanks to [@James Van Huis](https://stackoverflow.com/questions/936684/getting-the-class-name-from-a-static-method-in-java/936715#936715)): ``` MyClass.class.getSimpleName(); // class name and no more ```
In Java 7+ you can do this in static method/fields: ``` MethodHandles.lookup().lookupClass() ```
Getting the class name from a static method in Java
[ "", "java", "static", "" ]
How do i declare a 2d array using new? Like, for a "normal" array I would: ``` int* ary = new int[Size] ``` but ``` int** ary = new int[sizeY][sizeX] ``` a) doesn't work/compile and b) doesn't accomplish what: ``` int ary[sizeY][sizeX] ``` does.
If your row length is a compile time constant, C++11 allows ``` auto arr2d = new int [nrows][CONSTANT]; ``` See [this answer](https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new/16239446#16239446). Compilers like gcc that allow variable-length arrays as an extension to C++ can use `new` [as shown here](https://stackoverflow.com/a/8837664/224132) to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable. Another efficient option is to do the 2d indexing manually into a big 1d array, as [another answer shows](https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new/28841507#28841507), allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap). --- Otherwise, you can use an array of *pointers to arrays* to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this: ``` int** a = new int*[rowCount]; for(int i = 0; i < rowCount; ++i) a[i] = new int[colCount]; ``` The above, for `colCount= 5` and `rowCount = 4`, would produce the following: ![enter image description here](https://i.stack.imgur.com/M75kn.png) Don't forget to `delete` each row separately with a loop, before deleting the array of pointers. Example in [another answer](https://stackoverflow.com/a/936709/224132).
``` int** ary = new int[sizeY][sizeX] ``` should be: ``` int **ary = new int*[sizeY]; for(int i = 0; i < sizeY; ++i) { ary[i] = new int[sizeX]; } ``` and then clean up would be: ``` for(int i = 0; i < sizeY; ++i) { delete [] ary[i]; } delete [] ary; ``` **EDIT:** as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory: ``` int *ary = new int[sizeX*sizeY]; // ary[i][j] is then rewritten as ary[i*sizeY+j] ```
How do I declare a 2d array in C++ using new?
[ "", "c++", "arrays", "multidimensional-array", "dynamic-allocation", "" ]
I have a WPF control that I would like to overlay onto a WinForms application. So I have dutifully created a Element Host that can show the following WPF object: ``` <UserControl x:Class="LightBoxTest.LightBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300" Background="Transparent"> <Grid Name="dialogHolder" Background="Transparent" Opacity="1"> <Rectangle Name="rectangle1" Stroke="White" Fill="Black" RadiusX="10" RadiusY="10" Opacity="0.5" /> <StackPanel Name="stackPanel1" Background="Transparent" Height="300" VerticalAlignment="Top"> <Rectangle Name="spacer" Opacity="0" Stroke="Gray" Fill="White" RadiusX="10" RadiusY="10" Height="100" Width="300" /> <Grid Height="100" Name="contentHolder" Width="250"> <Rectangle Name="dialog" Stroke="Gray" Fill="White" RadiusX="10" RadiusY="10" Height="100" Width="250" /> </Grid> </StackPanel> </Grid> </UserControl> ``` The trouble is that the Controls on the WinForm Form do not render and the WPF just obliterates them on the screen. The element host is created like: ``` dialogHost = new ElementHost(); dialogHost.Child = dialog; dialogHost.BackColorTransparent = true; dialogHost.BringToFront(); dialogHost.Show(); ``` Is there something I should be doing and Im not? Are there known issues about showing transparent WPF controls over Winforms? Any articals that may help? Note: This question is related to [this question](https://stackoverflow.com/questions/936134/c-winforms-wpf-interop)
I think you're running into an [airspace issue](http://msdn.microsoft.com/en-us/library/aa970688.aspx). AFAIK, you can't mix WPF transparency and ElementHost transparency since the ElementHost owns the airspace. There's a short blurb in the link about creating non-rectangular hwnds to host WPF content, and that may get you farther. Perhaps you can consider migrating more of the WinForms app to WPF?
You should read this :[Black background before loading a wpf controll when using ElementHost](https://stackoverflow.com/questions/2087406/black-background-before-loading-a-wpf-controll-when-using-elementhost) Just hide & show it (not cool but works)
c# WPF transparency over Winform controls
[ "", "c#", "wpf", "winforms", "controls", "transparency", "" ]
I have a table like this : ``` Alternative |Total |Male |Female a |20 |10 |10 b |50 |20 |30 c |40 |10 |30 c |30 |15 |15 ``` now I want to select all the rows and the "c" alternative to be grouped.
The following query will select all the rows that are not "c", then group all the rows that are "c", sum their value, and add a single row representing the sum of "c". I hope that's what you mean. ``` SELECT * FROM table1 WHERE Alternative != c UNION SELECT Alternative, Sum(Total) as Total, Sum(Male) as Male, Sum(Female) as Female FROM table1 WHERE Alternative = c GROUP BY Alternative ``` If you just want to group anything that has multiple "Alternative" appearances, just use: ``` SELECT Alternative, Sum(Total) as Total, Sum(Male) as Male, Sum(Female) as Female FROM table1 GROUP BY Alternative ```
``` SELECT Alternative, Sum(Total), Sum(Male), Sum(Female) FROM table1 GROUP BY Alternative ```
select to group rows
[ "", "sql", "select", "group-by", "" ]
How can I launch a URL in a NEW window using C++ (Windows only)? The straight-forward approach seems to open a new tab in an existing browser window. (Or, if tabbed browsing is disabled, the new URL hijacks the existing browser window). This is for a (large) desktop app, using MFC and Qt.
I've used this for showing locally generated html in the default browser, in my case filename is something like "c:\temp\page.html", perhaps replacing filename with the URL might work?? ``` ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); ``` **Updated:** <http://support.microsoft.com/kb/224816> How ShellExecute Determines Whether to Start a New Instance When ShellExecute looks through the registry, it looks for the shell\open subkey. If the shell\open\ddeexec key is defined, then a Dynamic Data Exchange (DDE) message with the specified application IExplore and the topic WWW\_OpenURL is broadcast to all top-level windows on the desktop. The first application to respond to this message is the application that goes to the requested URL. If no application responds to this DDE message, then ShellExecute uses the information that is contained in the shell\open\command subkey to start the application. It then re-broadcasts the DDE message to go to the requested URL. **So it looks like you have no control over opening a new window. Whatever browser currently running can handle opening it in whatever way they want.**
Here's a link to [some code that will open a URL in a new browser](http://www.programmersheaven.com/mb/Win32API/190862/190862/open-a-url-in-a-new-browser-window/?S=B20000). The code looks up the default application for handling an HTML document and then explicitly opens that application with a ShellExecute call.
Launch a URL in a NEW window using C++ (Windows)
[ "", "c++", "url", "" ]
## [example page](http://jsbin.com/ujeva) I have a floating menu that i've built to the left side (green), and i've made it start moving after 200 pixels. and now i need to to stop and not go over the footer (blue) area. any ideas how to make my JS better? this thing is, I cannot check this on the scroll event, because of the animation going on after i scroll, so it needs to be done someway else. so how to make the animation stop at the end just before the footer?
I've resolved the issue perfectly (hope so) with the help of you guys, and released a jQuery plugin for floating sticky boxes: [**http://plugins.jquery.com/project/stickyfloat**](http://plugins.jquery.com/project/stickyfloat)
``` $.fn.menuFloater = function(options) { var opts = $.extend({ startFrom: 0, offsetY: 0, attach: '', duration: 50 }, options); // opts.offsetY var $obj = this; $obj.css({ position: 'absolute' /*, opacity: opts.opacity */ }); /* get the bottom position of the parent element */ var parentBottomPoint = $obj.parent().offset().top + $obj.parent().height() ; var topMax = $obj.parent().height() - $obj.innerHeight() + parseInt($obj.parent().css('padding-top')); //get the maximum scrollTop value if ( topMax < 0 ) { topMax = 0; } console.log(topMax); $(window).scroll(function () { $obj.stop(); // stop all calculations on scroll event // console.log($(document).scrollTop() + " : " + $obj.offset().top); /* get to bottom position of the floating element */ var isAnimated = true; var objTop= $obj.offset().top; var objBottomPoint = objTop + $obj.outerHeight(); if ( ( $(document).scrollTop() > opts.startFrom || (objTop - $(document).scrollTop()) > opts.startFrom ) && ( $obj.outerHeight() < $(window).height() ) ){ var adjust; ( $(document).scrollTop() < opts.startFrom ) ? adjust = opts.offsetY : adjust = -opts.startFrom + opts.offsetY; // and changed here to take acount the maximum scroll top value var newpos = ($(document).scrollTop() + adjust ); if ( newpos > topMax ) { newpos = topMax; } $obj.animate({ top: newpos }, opts.duration, function(){ isAnimated = false } ); } else { $obj.stop(); } }); }; ```
floating side menu, make it stop at bottom
[ "", "javascript", "jquery", "animation", "" ]
We have a javascript function that should "move" a page to a certain position using anchors. This function just does `window.location.href = "#" + hashName`. This works in FF, but not in IE. I tested this code using IE7 under Windows XP. I have tried `using window.location.href`, `window.location.hash`, `window.location.replace` and all these ways, but using `document` object. Does anyone know how to deal with this issue?
IE and most other browsers will scroll to an anchor with anchor.focus(), or to any element with an id with element.scrollIntoView(true)
I justed tested this in IE7 under Vista, maybe the issue only exsists in IE7 under XP? Because this works fine for me in IE7, Chrome and Firefox: ``` window.location.hash = hashName; ``` If this really doesn't work then we could use scrollIntoView as Kennebec suggests. ``` function scrollToAnchor(anchorName){ //set the hash so people can bookmark window.location.hash = anchorName; //scroll the anchor into view document.getElementsByName(anchorName)[0].scrollIntoView(true); } ``` Use like this: ``` <script type='text/javascript'>scrollIToAnchor('foo');</script> <a name='foo'></a> <p>I will be scrolled into view</p> ```
window.location.hash issue in IE7
[ "", "javascript", "internet-explorer", "internet-explorer-7", "" ]
I have an entity like: ``` public class Employee { public int ID { get; set; } public IAccountManager AccountManager { get; set; } ... } ``` I also have a mapping defined for "DefaultAccountManager" - a concrete implementation of IAccountManager. When mapping the above "Employee" entity, how do I tell NHibernate to persist/load the AccountManager property using the mapping defined in "DefaultAccountManager"? **Edit:** Actually if I could setup a mapping for IAccountManager so that NHibernate could just infer which implementer to load/persist that would be even better. I'd rather not have to break polymorphism by forcing all implementers to use the same mapping.
I did find an answer to this one. I'm a little hazy on the details, as it was a few months ago, but the following was the jist of the solution: * Create a table for each implementation of IAccountManager that has mappings. * Make sure your DB is setup to use the HiLo id algorithm. * Use union-subclasses in your mappings Union-subclasses would look something like this: ``` <class name="IAccountManager" abstract="true"> <id name="ID" column="ID" type="Int32"> <generator class="hilo"/> </id> <union-subclass name="DefaultAccountManager" table="DefaultAccountManager" proxy="IAccountManager"> <property name="FirstName" type="String"/> <property name="LastName" type="String"/> </union-subclass> ... more implementations </class> ``` Note the attribute "name" on union-subclass. This should be unique for (and match) each implementation of IAccountManager. Also, the ID, instead of being unique to each table, will be unique to all IAccountManagers (by leveraging hilo). When NHibernate sees an IAccountManager entity, it will use the instance's concrete type and the union-subclass definitions to figure out the correct table. Hope this helps!
Just thought I would share a way that I managed to achieve this using Fluent NHibernate rather than the hbm files. This method is a little hacky but the hacks are isolated and easily removed once Fluent NH gains proper support for Union-Subclass. To use your example, the context of my scenario is this - the Employee class is in one project with the AccountManager property specified as an interface, because the concrete AccountManager is in a different project which we don't want to create a dependency to. First I create a 'Helper' class that does most of the Employee mapping and looks like this. ``` public abstract class EmployeeMapperBase { protected abstract Type GetAccountManagerType(); public void DoMapping(ClassMap<Employee> classMap) { classMap.Id(x => x.Id); classMap.Maps(..... etc.... classMap.References(x => x.AccountManager) .Class(GetAccountManagerType()); } } ``` Next, in the project with the concrete AccountManager class, I complete the mapping: ``` public class EmployeeClassMap : ClassMap<Employee> { public EmployeeClassMap { new ConcreteEmployeeMapper().DoMapping(this); } private class ConcreteEmployeeMapper : EmployeeMapperBase { public override Type GetAccountManagerType() { return typeof(DefaultAccountManager); } } } ```
Fluent nhibernate: How do I map an entity with a property who's type is an interface?
[ "", "c#", "nhibernate", "fluent-nhibernate", "interface", "nhibernate-mapping", "" ]
I have this query: ``` SELECT Items.Name, tblBooks.AuthorLastName, tblBooks.AuthorFirstName FROM Items WHERE Items.ProductCode IN ( SELECT TOP 10 Recommended.ProductCode FROM Recommended INNER JOIN Stock ON Recomended.ProductCode = Stock.ProductCode AND Stock.StatusCode = 1 WHERE (Recommended.Type = 'TOPICAL') ORDER BY CHECKSUM(NEWID())); ``` It is fine for my data, except that the Recommended table has a SKU field I need also however I cannot put it next to Recommended.ProductCode and have the query still work. I have used JOINS for this query and these work - but this query runs faster I just need the ProductCode and SKU from the Recommended table - how can this be done without needing yet another sub query? Database: MS SQL Server 2000
The subquery seems to be picking 10 random recommendations. I think you can do that without a subquery: ``` SELECT TOP 10 Items.*, Recommended.*, Stock.* FROM Items INNER JOIN Recommended ON Items.ProductCode = Recommended.ProductCode AND Recommended.Type = 'TOPICAL' INNER JOIN Stock ON Recomended.ProductCode = Stock.ProductCode AND Stock.StatusCode = 1 ORDER BY CHECKSUM(NEWID()) ``` This gives you access to all columns, without having to pass them up from the subquery.
You can only return one value with the subselect, so you have to obtain the fields from the Recommended table by a join - which I presume is what you have already: ``` SELECT Items.Name, tblBooks.AuthorLastName, tblBooks.AuthorFirstName, Recommended.SKU FROM Items INNER JOIN Recommended ON Recommended.ProductCode = Items.ProductCode WHERE Items.ProductCode IN ( SELECT TOP 10 Recommended.ProductCode FROM Recommended INNER JOIN Stock ON Recomended.ProductCode = Stock.ProductCode AND Stock.StatusCode = 1 WHERE (Recommended.Type = 'TOPICAL') ORDER BY CHECKSUM(NEWID())); ``` Most likely the Join in reality is an outer too I guess. This really shouldn't have any performance issues so long as you have both the Items and and Recommended tables indexed on ProductCode.
Can SQL Sub-query return two/more values but still compare against one of them?
[ "", "sql", "sql-server", "database", "sql-server-2000", "" ]
What does the C++ standard say about using dollar signs in identifiers, such as `Hello$World`? Are they legal?
A c++ identifier can be composed of any of the following: \_ (underscore), the digits 0-9, the letters a-z (both upper and lower case) and cannot start with a number. There are a number of exceptions as C99 allows extensions to the standard (e.g. [visual studio](http://msdn.microsoft.com/en-us/library/565w213d.aspx)).
They are illegal. The only legal characters in identifiers are letters, numbers, and \_. Identifiers also cannot start with numbers.
Are dollar-signs allowed in identifiers in C++03?
[ "", "c++", "identifier", "" ]
i have three checkboxs in my application. If the user ticks a combination of the boxes i want to return matches for the boxes ticked and in the case where a box is not checked i just want to return everything . Can i do this with single SQL command?
You can build a SQL statement with a dynamic where clause: ``` string query = "SELECT * FROM TheTable WHERE 1=1 "; if (checkBlackOnly.Checked) query += "AND Color = 'Black' "; if (checkWhiteOnly.Checked) query += "AND Color = 'White' "; ``` Or you can create a stored procedure with variables to do this: ``` CREATE PROCEDURE dbo.GetList @CheckBlackOnly bit , @CheckWhiteOnly bit AS SELECT * FROM TheTable WHERE (@CheckBlackOnly = 0 or (@CheckBlackOnly = 1 AND Color = 'Black')) AND (@CheckWhiteOnly = 0 or (@CheckWhiteOnly = 1 AND Color = 'White')) .... ```
I recommend doing the following in the WHERE clause; ``` ... AND (@OnlyNotApproved = 0 OR ApprovedDate IS NULL) ``` It is not one SQL command, but works very well for me. Basically the first part checks if the switch is set (checkbox selected). The second is the filter given the checkbox is selected. Here you can do whatever you would normally do.
creating SQL command to return match or else everything else
[ "", "sql", "" ]
I'm looking for a way to do two-way communication between a PB object and a .NET (C#) object. In looking at Brad's .NET version of his GUI controls, I see how to give the .NET object a reference to the PB object. But in that example, it's cast as a PowerObject (basically). That C# code only calls TriggerEvent() on the PB object. I want to create a custom class in C# called foo1. I want to create a method on foo1 called bar1(). I want to create a custom class in PB called foo2. I want to create a method on foo2 called bar2(). I want to be able to create an instance of foo1 within foo2. I want to be able to call foo1.bar1() from within foo2. (I'm good up until here.) I want to be able to reference foo2 from within foo1. I want to be able to call foo2.bar2() from within foo1.
I am sure there is a more eligent way to do this, but using COM might be the easiest. * [Using COM in PowerBuilder](http://www.techno-kitten.com/Changes_to_PowerBuilder/New_In_PowerBuilder_7/PB7_New_-_Building_COM_MTS_com/pb7_new_-_building_com_mts_com.html) * [Using COM in .NET](http://www.codeproject.com/KB/COM/cominterop.aspx) Some people would say that COM is never the right answer, but I say use the right tool for the right job.
I used the idea from here to create my C# control and it worked with it being called from PB and Qt. [Exposing Windows Form as ActiveX control](http://www.codeproject.com/KB/miscctrl/exposingdotnetcontrols.aspx) You may also want to look at P/Invoke
.NET interop in PowerBuilder
[ "", "c#", ".net", "interop", "powerbuilder", "" ]
is there a good and free implementation of CSV parser available under some liberal licence? Some counterpart of [SuperCSV](http://supercsv.sourceforge.net/) for Java, perhaps a port?
[FileHelpers Open Source Library](http://www.filehelpers.net/).
There's a nice implementation on [CodeProject](http://www.codeproject.com/KB/database/CsvReader.aspx): > To give more down to earth numbers, with a 45 MB CSV file containing 145 fields and 50,000 records, the reader was processing about 30 MB/sec. So all in all, it took 1.5 seconds! The machine specs were P4 3.0 GHz, 1024 MB.
CSV parser/reader for C#?
[ "", "c#", "csv", "" ]
I have a class that uses XML and reflection to return `Object`s to another class. Normally these objects are sub fields of an external object, but occasionally it's something I want to generate on the fly. I've tried something like this but to no avail. I believe that's because Java won't allow you to access `private` methods for reflection. ``` Element node = outerNode.item(0); String methodName = node.getAttribute("method"); String objectName = node.getAttribute("object"); if ("SomeObject".equals(objectName)) object = someObject; else object = this; method = object.getClass().getMethod(methodName, (Class[]) null); ``` If the method provided is `private`, it fails with a `NoSuchMethodException`. I could solve it by making the method `public`, or making another class to derive it from. Long story short, I was just wondering if there was a way to access a `private` method via reflection.
You can invoke private method with reflection. Modifying the last bit of the posted code: ``` Method method = object.getClass().getDeclaredMethod(methodName); method.setAccessible(true); Object r = method.invoke(object); ``` There are a couple of caveats. First, `getDeclaredMethod` will only find method declared in the current `Class`, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a `SecurityManager` can prevent use of the `setAccessible` method. So, it may need to run as a `PrivilegedAction` (using `AccessController` or `Subject`).
Use `getDeclaredMethod()` to get a private Method object and then use `method.setAccessible()` to allow to actually call it.
Any way to Invoke a private method?
[ "", "java", "reflection", "private", "" ]
I've got code like this: ``` Logger logger = new Logger(); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); logger.LogInformation("Calling SomeObject.SomeMethod at " + DateTime.Now.ToString()); stopWatch.Start(); // This is the method I'm interested in. SomeResponse response = someObject.SomeMethod(someParam); stopWatch.Stop(); logger.LogInformation("SomeObject.SomeMethod returned at " + DateTime.Now.ToString()); logger.LogInformation("SomeObject.SomeMethod took " + stopWatch.ElapsedMilliseconds + " milliseconds."); ``` I need to wrap similar code around a lot more objects and their methods to do some performance profiling. I'm not allowed to use 3rd party plugins or software, etc. I'd really rather not write this same code around all of these method calls this all of this logging code. How would you refactor this to eliminate some of my coding effort? If I'm not being very clear, please ask questions in the comments and I will try to clarify. Thanks for any help!!
You can refactor the code to accept a method pointer instance (aka [System.Action](http://msdn.microsoft.com/en-us/library/system.action.aspx)). ``` public void CallWithLogTiming (Action theAction) { Logger logger = new Logger(); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); logger.LogInformation("Calling SomeObject.SomeMethod at " + DateTime.Now.ToString()); stopWatch.Start(); // This is the method I'm interested in. theAction(); stopWatch.Stop(); logger.LogInformation("SomeObject.SomeMethod returned at " + DateTime.Now.ToString()); logger.LogInformation("SomeObject.SomeMethod took " + stopWatch.ElapsedMilliseconds + " milliseconds."); } ``` Then you can call it by creating a lambda expression. Since myResponse is a captured variable, it will be populated when this Action is run and myResponse will be available for use later in this scope. ``` SomeResponse myResponse = null; CallWithLogTiming( () => myResponse = someObject.SomeMethod(someParam) ); ```
For simplicity sake, you could use generics, like so (off the top of my head): ``` public T MyLogMethod<T,S>(Func<S, T> someFunction, S someParameter) {} ``` Func(S,T) where S is the parameter type of the method, and T is the return type.
How would you refactor this smelly code? (Logging, Copy and Paste, .Net 3.5)
[ "", "c#", ".net", ".net-3.5", "refactoring", "" ]
I have the following but it's not working, I read somewhere on the stackoverflow that it works like this but I can't seem to get it to work.. it errors... am I doing something wrong? If I do pass data like this - it works -- so I know my service is working ``` //THIS WORKS data: "{one : 'test',two: 'test2' }" // BUT SETTING UP OBJECT doesn't work.. var saveData = {}; saveData.one = "test"; saveData.two = "tes2"; $.ajax({ type: "POST", url: "MyService.aspx/GetDate", data: saveData, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { alert(msg.d); }, error: function(msg) { alert('error'); } }); ```
I believe that code is going to call .value or .toString() on your object and then pass over the wire. You want to pass JSON. So, include the json javascript library <http://www.json.org/js.html> And then pass... ``` var saveData = {}; saveData.one = "test"; saveData.two = "tes2"; $.ajax({ type: "POST", url: "MyService.aspx/GetDate", data: JSON.stringify(saveData), // NOTE CHANGE HERE contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { alert(msg.d); }, error: function(msg) { alert('error'); } }); ```
According to [this blog post](http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/ "3 mistakes to avoid when using jQuery with ASP.NET Ajax"), the reason it doesn't work when you try to pass the object is that jQuery attempts to serialize it. From the post: > Instead of passing that JSON object through to the web service, jQuery will automatically serialize and send it as: > > > ``` > > fname=dave&lname=ward > > ``` > > > > To which, the server will respond with: > > > > ``` > > Invalid JSON primitive: fname. > > ``` > > This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter[...] Which is what you're doing in the example that works.
Passing js object as json to jquery?
[ "", "javascript", "jquery", "ajax", "json", "object", "" ]
How do I write a function that formats a string with decimals digits, without trailing 0's or unnecessary 9's? Given that decimals is 2, here's what I expect: ``` 0.999 -> 1.0 0.99 -> 0.99 1.01 -> 1.01 1.001 -> 1.0 123 -> 123.0 0 -> 0.0 0.1 -> 0.1 ``` (negatives as you'd expect) Here's what I have so far, but it's pretty ugly code. Is there a nicer way to do this? ``` string toStrMaxDecimals(double value, uint decimals) { value *= pow(10, decimals); value = round(value); value *= pow(0.1, decimals); string temp = boost::lexical_cast<string>(value); size_t dot = temp.find('.'); if (dot != string::npos) { if (temp.size() > dot + decimals + 1) temp.erase(dot + decimals + 1); if (*temp.rbegin() == '0') temp.erase(temp.find_last_not_of("0") + 1); if (*temp.rbegin() == '.') temp.append("0"); } else { temp.append(".0"); } return temp; } ```
``` std::string toStrMaxDecimals(double value, int decimals) { std::ostringstream ss; ss << std::fixed << std::setprecision(decimals) << value; std::string s = ss.str(); if(decimals > 0 && s[s.find_last_not_of('0')] == '.') { s.erase(s.size() - decimals + 1); } return s; } ```
sprintf is going to be far easier, more readable and more performance than C++ streams. You don't need to do any rounding or trimming yourself. Sprintf has flags for that. You probably want something like ``` sprintf(targetBuffer, "%.2g", floatingPointValue); ``` Sprintf does the rounding in Java, and I'm pretty sure it will in C++ as well. EDIT: Sorry, the example code I wrote is for your example. For your original question, change the %.2g to %.6g EDIT: Changed f to g to suppress trailing zeroes.
how do I elegantly format string in C++ so that it is rounded to 6 decimal places and has extra '0's or '9's trimmed
[ "", "c++", "string", "formatting", "string-formatting", "" ]
I have a console application I'm using to run scheduled jobs through windows scheduler. All the communication to/from the application is in email, event logging, database logs. Is there any way I can suppress the console window from coming up?
Sure. Build it as a winforms app and never show your form. Just be careful, because then it's not really a console app anymore, and there are some environments where you won't be able to use it.
Borrowed from MSDN ([link text](http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/ea8b0fd5-a660-46f9-9dcb-d525cc22dcbd/)): ``` using System.Runtime.InteropServices; ... [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName,string lpWindowName); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); ... //Sometimes System.Windows.Forms.Application.ExecutablePath works for the caption depending on the system you are running under. IntPtr hWnd = FindWindow(null, "Your console windows caption"); //put your console window caption here if(hWnd != IntPtr.Zero) { //Hide the window ShowWindow(hWnd, 0); // 0 = SW_HIDE } if(hWnd != IntPtr.Zero) { //Show window again ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA } ```
.Net Console Application that Doesn't Bring up a Console
[ "", "c#", ".net", "vb.net", "console", "console-application", "" ]
Analogous to the `$?` in Linux, is there a way to get the exit status of a program in a Windows batch file (`.bat`)? Say for example the program has a `System.exit(0)` upon successful execution, and a `System.exit(1)` upon a failure, how do I trap these exit values in a `.bat` file?
Use [%ERRORLEVEL%](http://vlaurie.com/computers2/Articles/environment.htm). Don't you love how batch files are clear and concise? :)
Something like: ``` java Foo set exitcode=%ERRORLEVEL% echo %exitcode% ``` It's important to make this the absolute next line of the batch file, to avoid the error level being overwritten :) Note that if you use the ``` IF ERRORLEVEL number ``` "feature" of batch files, it means "if the error level is greater than or equal to `number`" - it's not based on equality. I've been bitten by that before now :)
How to get the exit status of a Java program in Windows batch file
[ "", "java", "windows", "batch-file", "exit-code", "" ]
I'm looking for a simple Password Strength Visualizer (like gmail's when you create a new account). I want to show the user how good their password is visually. Does anyone have some source code they'd like to share? :)
i found this <https://jsfiddle.net/umesh1990/hxjf74cz/35/#> i have implement using javascript ``` function password_validate(txt) { var val1 = 0; var val2 = 0; var val3 = 0; var val4 = 0; var val5 = 0; var counter, color, result; var flag = false; if (txt.value.length <= 0) { counter = 0; color = "transparent"; result = ""; } if (txt.value.length < 8 & txt.value.length > 0) { counter = 20; color = "red"; result = "Short"; } else { document.getElementById(txt.id + "error").innerHTML = " "; txt.style.borderColor = "grey"; var regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/; // document.getElementById("pass_veri").style.display="block"; var fletter = /[a-z]/; if (fletter.test(txt.value)) { val1 = 20; } else { val1 = 0; } //macth special character var special_char = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/; if (special_char.test(txt.value)) { val2 = 30; } else { val = 0; } /*capital_letter*/ var cap_lett = /[A-Z]/; if (cap_lett.test(txt.value)) { val3 = 20; } else { val = 0; } /*one numeric*/ var num = /[0-9]/; if (num.test(txt.value)) { val4 = 20; } else { val4 = 0; } /* 8-15 character*/ var range = /^.{8,50}$/; if (range.test(txt.value)) { val5 = 10; } else { val5 = 0; } counter = val1 + val2 + val3 + val4 + val5; if (counter >= 30) { color = "skyblue"; result = "Fair"; } if (counter >= 50) { color = "gold"; result = "Good"; } if (counter >= 80) { color = "green"; result = "Strong"; } if (counter >= 90) { color = "green"; result = "Very Strong"; } } document.getElementById("prog").style.width = counter + "%"; document.getElementById("prog").style.backgroundColor = color; document.getElementById("result").innerHTML = result; document.getElementById("result").style.color = color; } ``` ``` body { font-family: 'Rajdhani', sans-serif; background-color: #E4E4E4; } /* tooltip*/ .hint { width: 258px; background: red; position: relative; -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px; position: absolute; left: 0px; border: 1px solid #CC9933; background-color: #FFFFCC; display: none; padding: 20px; font-size: 11px; } .hint:before { content: ""; position: absolute; left: 100%; top: 24px; width: 0; height: 0; border-top: 17px solid transparent; border-bottom: 1px solid transparent; border-left: 22px solid #CC9933; } .hint:after { content: ""; position: absolute; left: 100%; top: 26px; width: 0; height: 0; border-top: 14px solid transparent; border-bottom: 1px solid transparent; border-left: 20px solid #FFFFCC; } .parent { position: relative; } .progress { height: 7px; } #progres { display: block; } p { margin: 0px; font-weight: normal; } .form-control { width: none; margin-left: 260px; margin-top: 25px; width: 200px; } ``` ``` <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <div class="form-group col-lg-12 parent "> <label class="hint" id="pass-hint"> Password Strength:<span id="result"></span> <br> <div class="progress" id="progres"> <div class="progress-bar progress-bar-danger" role="progressbar" id="prog"> </div> </div> <p> passowrd must have atleast 8 charatcer</p> </label> <input type="password" class="form-control" data-toggle="tooltip" data-placement="left" id="pass" onfocus="document.getElementById('pass-hint').style.display='block'" onblur="document.getElementById('pass-hint').style.display='none'" placeholder="**********" oninput="password_validate(this);document.getElementById('progres').style.display='block';"> <i class=" form-control-feedback" id="passsuccess" aria-hidden="true"></i> <span id="passerror" class="help-block error"></span> </div> ```
Choose the one you like most: [10 Password Strength Meter Scripts For A Better Registration Interface](http://www.webresourcesdepot.com/10-password-strength-meter-scripts-for-a-better-registration-interface/)
Password Strength Visualizer - Html & Javascript/Ajax
[ "", "javascript", "html", "ajax", "" ]
Can anybody recommend a good (ideally open source) C++ spell checker library. We are currenly using Talo, which isn't very good, so we are looking to change. One which includes a grammar checker would also be good. Thanks
I have heard good things about [hunspell](http://hunspell.sourceforge.net/). I have used and integrated [aspell](http://aspell.net/), which has some nice features and some which I did not like.
If you've got internet access, you can always use on online service like [SpellCheck.net](http://www.spellcheck.net) which has a CGI interface that you can query.
C++ SpellChecker Library
[ "", "c++", "open-source", "spell-checking", "" ]
I would like my build script to act properly for release and development environments. For this I would like to define a property in ant, call it (e.g.) `fileTargetName` `fileTargetName` will get it's value from the environment variable `RELEASE_VER` if it's available, if it is not available it will get the default value of **dev** Help with ant `<condition><value></condition>` & `<property>` to get it working is appreciated.
An example from the [Ant documentation](http://ant.apache.org/manual/Tasks/property.html#notes-env) of how to get an environment variable into a property: ``` <property environment="env"/> <echo message="Number of Processors = ${env.NUMBER_OF_PROCESSORS}"/> <echo message="ANT_HOME is set to = ${env.ANT_HOME}"/> ``` In your case, you would use `${env.RELEASE_VER}`. Then for the conditional part, the documentation [here](http://ant.apache.org/manual/Tasks/condition.html) says that there are three possible attributes: ``` Attribute Description Required property The name of the property to set. Yes value The value to set the property to. Defaults to "true". No else The value to set the property to if the condition No evaluates to false. By default the property will remain unset. Since Ant 1.6.3 ``` Putting it together: ``` <property environment="env"/> <condition property="fileTargetName" value="${env.RELEASE_VER}" else="dev"> <isset property="env.RELEASE_VER" /> </condition> ```
You don't need to use a `<condition>` for this. Properties in Ant are [immutable](http://ant.apache.org/manual/Tasks/property.html), so you can just use this: ``` <property environment="env"/> <property name="env.RELEASE_VER" value="dev"/> ``` If the `RELEASE_VER` environment variable is set, then the property will get its value from the environment and the second `<property>` statement will have no effect. Otherwise, the property will be unset after the first statement, and the second statement will set its value to `"dev"`.
define ant property from environment with default value
[ "", "java", "ant", "environment-variables", "release", "packaging", "" ]
I'm working on a large c++ built library that has grown by a significant amount recently. Due to it's size, it is not obvious what has caused this size increase. Do you have any suggestions of tools (msvc or gcc) that could help determine where the growth has come from. *edit* Things i've tried: Dumpbin the final dll, the obj files, creating a map file and ripping through it. *edit again* So objdump along with a python script seems to have done what I want.
If gcc, [objdump](http://en.wikipedia.org/wiki/Objdump). If visual studio, [dumpbin](http://msdn.microsoft.com/en-us/library/c1h23y6c(VS.71).aspx). I'd suggest doing a diff of the output of the tool for the old (small) library, vs. the new (large) library.
keysersoze's answer (compare the output of `objdump` or `dumpbin`) is correct. Another approach is to tell the linker to produce a map file, and compare the map files for the old and new versions of the DLL. * MSVC: `link.exe` [`/MAP`](http://msdn.microsoft.com/en-us/library/k7xkk3e2.aspx) * GCC and binutils: `ld` [`-M`](http://sourceware.org/binutils/docs-2.19/ld/Options.html#index-g_t_002d_002dprint_002dmap-62) (or `gcc -Wl,-M`)
Determining what object files have caused .dll size increase [C++]
[ "", "c++", "size", "" ]
I am trying to load an XML file from a different domain name as a string. All I want is an array of the text within the < title >< /title > tags of the xml file, so I am thinking since I am using php4 the easiest way would be to do a regex on it to get them. Can someone explain how to load the XML as a string? Thanks!
You could use cURL like the example below. I should add that regex-based XML parsing is generally not a good idea, and you may be better off using a real parser, especially if it gets any more complicated. You may also want to add some regex modifiers to make it work across multiple lines etc., but I assume the question is more about fetching the content into a string. ``` <?php $curl = curl_init('http://www.example.com'); //make content be returned by curl_exec rather than being printed immediately curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); if ($result !== false) { if (preg_match('|<title>(.*)</title>|i', $result, $matches)) { echo "Title is '{$matches[1]}'"; } else { //did not find the title } } else { //request failed die (curl_error($curl)); } ```
first use file\_get\_contents('<http://www.example.com/>'); to get the file, insert in to var. after parse the xml the link is <http://php.net/manual/en/function.xml-parse.php> have example in the comments
PHP: how to load file from different server as string?
[ "", "php", "regex", "php4", "" ]
I am wondering, since a lot of things can be done using reflection, can I change a private readonly field after the constructor completed its execution? (note: just curiosity) ``` public class Foo { private readonly int bar; public Foo(int num) { bar = num; } public int GetBar() { return bar; } } Foo foo = new Foo(123); Console.WriteLine(foo.GetBar()); // display 123 // reflection code here... Console.WriteLine(foo.GetBar()); // display 456 ```
You can: ``` typeof(Foo) .GetField("bar",BindingFlags.Instance|BindingFlags.NonPublic) .SetValue(foo,567); ```
The obvious thing is to try it: ``` using System; using System.Reflection; public class Test { private readonly string foo = "Foo"; public static void Main() { Test test = new Test(); FieldInfo field = typeof(Test).GetField ("foo", BindingFlags.Instance | BindingFlags.NonPublic); field.SetValue(test, "Hello"); Console.WriteLine(test.foo); } } ``` This works fine. (Java has different rules, interestingly - you have to explicitly set the `Field` to be accessible, and it will only work for instance fields anyway.)
Can I change a private readonly field in C# using reflection?
[ "", "c#", "reflection", "field", "readonly", "" ]
The following bit of C# code does not seem to do anything: ``` String str = "{3}"; str.Replace("{", String.Empty); str.Replace("}", String.Empty); Console.WriteLine(str); ``` This ends up spitting out: {3}. I have no idea why this is. I do this sort of thing in Java all the time. Is there some nuance of .NET string handling that eludes me?
The String class is [immutable](http://en.wikipedia.org/wiki/Immutable_object); `str.Replace` will not alter `str`, it will return a new string with the result. Try this one instead: ``` String str = "{3}"; str = str.Replace("{", String.Empty); str = str.Replace("}", String.Empty); Console.WriteLine(str); ```
String is immutable; you can't change an instance of a string. Your two Replace() calls do nothing to the original string; they return a modified string. You want this instead: ``` String str = "{3}"; str = str.Replace("{", String.Empty); str = str.Replace("}", String.Empty); Console.WriteLine(str); ``` It works this way in Java as well.
String.Replace does not seem to replace brackets with empty string
[ "", "c#", "string", "" ]
I am getting a formatexception with the following code. Any one know how to make BooleanConverter convert from 0/1 to true/false. ``` bool bVal=true; string sVal = "0"; Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal)); ``` Thanks for the help!
If you're going to use Int32.Parse, use Int32.TryParse instead. It doesn't throw if the conversion fails, instead returning true or false. This means that it's more performant if all you're doing is checking to see if your input is a value. Example: ``` public static bool ConvertToBool(string value) { int val = 0; return (int.TryParse(value, out val) && val == 0) ? false : true; } ``` I have a tendency to go overboard on the ternary operator (x ? y : z), so here's a slightly easier-to-read version: ``` public static bool ConvertToBool(string value) { int val = 0; if (int.TryParse(value, out val)) { return val == 0 ? false : true; } return false; } ``` (I tested them both. "1" returns true, "0" returns false.)
Try the following ``` public static bool ConvertToBasedOnIntValue(string value) { // error checking omitted for brevity var i = Int32.Parse(value); return value == 0 ? false : true; } ``` Or you could use the following which won't throw exceptions but it will consider everything that is quite literally not 0 to be true ``` public static bool ConvertToBasedOnIntValue(string value) { if ( 0 == StringComparer.CompareOrdinal(value, "0") ) { return false; } return true; } ```
FormatException 0 is not a valid value for Boolean
[ "", "c#", ".net", "" ]
If my C++ app crashes on Windows I want to send useful debugging information to our server. On Linux I would use the GNU `backtrace()` function - is there an equivalent for Windows? Is there a way to extract useful debugging information after a program has crashed? Or only from within the process? (Advice along the lines of "test you app so it doesn't crash" is not helpful! - all non-trivial programs will have bugs)
The function [Stackwalk64](http://msdn.microsoft.com/en-us/library/ms680650.aspx) can be used to snap a stack trace on Windows. If you intend to use this function, you should be sure to compile your code with FPO disabled - without symbols, StackWalk64 won't be able to properly walk FPO'd frames. You can get some code running in process at the time of the crash via a top-level `__try/__except` block by calling SetUnhandledExceptionFilter. This is a bit unreliable since it requires you to have code running inside a crashed process. Alternatively, you can just the built-in Windows Error Reporting to collect crash data. This is more reliable, since it doesn't require you to add code running inside the compromised, crashed process. The only cost is to get a code-signing certificate, since you must submit a signed binary to the service. <https://sysdev.microsoft.com/en-US/Hardware/signup/> has more details.
You can use the Windows API call [MiniDumpWriteDump](http://msdn.microsoft.com/en-us/library/ms680360.aspx) if you wish to roll your own code. Both Windows XP and Vist automate this process and you can sign up at <https://winqual.microsoft.com> to gain access to the error reports. Also check out <http://kb.mozillazine.org/Breakpad> and <http://www.codeproject.com/KB/debug/crash_report.aspx> for other solutions.
How to extract debugging information from a crash
[ "", "c++", "windows", "crash", "stack-trace", "backtrace", "" ]
I've got city, state, country strings like: ``` NEW YORK, NY, US REDMOND, WA, US US HONG KONG CALGARY, CA E. SYRACUSE, NY, US ``` I'd like to transform them to their proper case (New York, NY, US; etc). Whats a quick way to do this in PHP?
``` function title_case($val) { return mb_convert_case($val[0], MB_CASE_TITLE, "UTF-8"); } $locs = array( 'NEW YORK, NY, US', 'REDMOND, WA, US', 'US', 'HONG KONG', 'CALGARY, CA', 'E. SYRACUSE, NY, US', ); foreach ($locs as &$loc) { $loc = preg_replace_callback( '/\b\w{3,}\b/', "title_case", $loc); } print_r($locs); // Array // ( // [0] => New York, NY, US // [1] => Redmond, WA, US // [2] => US // [3] => Hong Kong // [4] => Calgary, CA // [5] => E. Syracuse, NY, US // ) ```
``` $locs = array( 'NEW YORK, NY, US', 'REDMOND, WA, US', 'US', 'HONG KONG', 'CALGARY, CA', 'E. SYRACUSE, NY, US', ); foreach ($locs as &$loc) { $items = explode(',', $loc); if (strlen($items[0]) > 2) { $items[0] = ucwords($items[0]); } $loc = implode(',', $items); } ```
PHP: Transform a city, state, country string to proper title case
[ "", "php", "string", "" ]
Given this class: ``` class Tacobell{ public function order_taco(){ echo "3 Tacos, thank you."; } public function order_burrito(){ echo "Cheesy bean and rice, please"; } } $lunch = new Tacobell; $lunch->order_burrito(); $lunch->order_taco(); ``` How would I do something like this? ``` $myOrder = 'burrito'; $lunch->order_.$myOrder; ``` Obviously that code is bunk--but shows what I'm attempting to do better than trying to explain it away. And maybe I'm going about this all wrong. I thought about a method with a switch statement, pass in burrito or taco, then call the right method from there. But then I have to know the end from the beginning, and I may potentially have lots of methods and I'd rather not have to update the switch statement everytime. Thanks!
How about something like this? ``` class Tacobell { public function order_burrito() { echo "Bladibla.\n"; } public function order($item) { if (method_exists($this, "order_$item")) { $this->{'order_' . $item}(); } else { echo "Go away, we don't serve $item here.\n"; } } } ``` You would call it using $lunch->order('burrito');, which looks much cleaner to me. It puts all the uglyness in the method Tacobell::order.
``` $lunch->{'order_' . $myOrder}(); ``` I do agree the design is a little iffy, but that's how to do it at least.
How would I call a method from a class with a variable?
[ "", "php", "oop", "variable-variables", "" ]
I have two functions, makeKey() and keyExists(). makeKey() simply generates a 5 digit random alphanumeric key, keyExists() accepts this key as its only argument, and looks up in a table, returning true/false depending on whether it exists. I need to do something very simple but I cannot figure out the quickest way of doing it. I just need to make a key, and if it exists in the table, make a key again, and so on until a unique one is returned. I think a while loop will suffice? Thanks and please forgive the rather basic question, I think I cooked my brain in the sun yesterday.
I’d use a `do`-`while` loop: ``` do { $newKey = makeKey(); } while (keyExists($newKey)); ``` This will generate a new key on every iteration until the key does not exist yet.
Any solution that relies on creating, then checking is going to have awful performance as the key space fills up. You'd be better off generating a unique key using an autogenerated column (identity or guid). If it needs to be alphanumeric, use a mapping function to transform it into the alphabet of your choice by selecting groups of bits and using them as an index into your alphabet. Pseudo-code ``` alphabet = "ABCDE...789"; key = insert new row, get autogenerated key alphaKey = ""; while (get n bits from key) alphaKey += alphabet[bits] done echo alphaKey ```
creating a unique key - most efficient way
[ "", "php", "while-loop", "" ]
I have read in some blog some time ago (sorry for being vague) that i could use a linq like the following ``` var list = from c in xml select new { foreach(XElement el in c.Elements()) { } } ``` Does anyone know is it possible or is it just my imagination?? Thanks.
You can use the ToList() function to convert the elements to a list of List then you can use the ForEach Method on it. FYI when using LinqToXml I find the Descendants() more useful as it will do a full dive into the object model. ``` xml.Elements().ToList().ForEach(ele => DoSomething(ele)); ```
You can't use a `foreach` loop directly in an anonymous type initialization expression, no. If you could tell us what you're trying to achieve, we could probably help you find the best way of doing it.
how to use foreach in linq
[ "", "c#", "linq", "foreach", "anonymous-types", "" ]
I was just bitten by the following scenario: ``` >>> -1 ** 2 -1 ``` Now, digging through the Python docs, [it's clear that this is intended behavior](http://docs.python.org/reference/expressions.html#the-power-operator), but *why?* I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me. Is there a reason it was done this way? Do other languages with power operators behave similarly?
That behaviour is the same as in math formulas, so I am not sure what the problem is, or why it is counter-intuitive. Can you explain where have you seen something different? "\*\*" always bind more than "-": -x^2 is not the same as (-x)^2 Just use (-1) \*\* 2, exactly as you'd do in math.
Short answer: it's the standard way precedence works in math. Let's say I want to evaluate the polynomial 3x**3 - x**2 + 5. ``` def polynomial(x): return 3*x**3 - x**2 + 5 ``` It looks better than... ``` def polynomial return 3*x**3 - (x**2) + 5 ``` And the first way is the way mathematicians do it. Other languages with exponentiation work the same way. Note that the negation operator also binds more loosely than multiplication, so ``` -x*y === -(x*y) ``` Which is also the way they do it in math.
Why does "**" bind more tightly than negation?
[ "", "python", "operator-precedence", "" ]
I'm trying to add another restriction on a method within a generic class. Is this possible? Pseudocode: ``` public class MyBaseClass<T> where T: class { public IQueryable<T> ShowThisMethod where T: class, IMyInterface { // stuff. } } ``` ShowThisMethod should only be available when T is IMyInterface. Also IMyInterface should then give information back (about T) so that I can access properties defined in IMyInterface inside of the method. Help :) **By the way, this compiles** (and seems "almost right"): ``` public class MyBaseClass<T> where T: class { public IQueryable<T> ShowThisMethod<T>() where T: class, IMyInterface { String X = T.MyInterfaceStringProperty; } } ``` **More Information about my goal**: I'm using a generic base class to access a common property (DateTime "Time" property on LINQ object *Dinner* which is also on *Lunch*). Both objects are implementing **ITimeable** which exposes the DateTime property. In my base class I'd like to have a method Select() which works on IQueryable&ltT> and can automatically filter based on the Time property. Because I'm working off the generic T, the time property is not visible to the base class, unless I tell it that T is implementing **ITimeable**. I do want the same base class to work for other non-ITimeable objects too, that's why I need the interface restriction on the Select method, and I also need it in order to access the Time property using generics. Hope that clears the goal :) **P.S. My main concern is not visibility of the method in IntelliSense etc.**. I'd just like to keep my base class working, while being able to access an interface-specified property through generics in it.
It depends on what you want. Since the class is compiled once, and the magic with generics also relies on the runtime, there's no way to make a class that has some methods in some cases, and other methods in other cases. Either the methods are there, or they aren't. So basically, there's no way to declare MyBaseClass so that the following happens: ``` MyBaseClass<Int32> bc; bc. <-- intellisense does not show ShowThisMethod here MyBaseClass<SomeTypeImplementingIMyInterface> bc2; bc2. <-- intellisense DOES show ShowThisMethod here ``` ... that is... by itself. You can "trick" the compiler and intellisense into giving you what you're asking for, but know that this gives you other limitations and challenges that might need to be solved. Basically, by adding an extension method to a static class declared alongside MyBaseClass, you can make intellisense, and the compiler, behave as if the method is only present for MyBaseClass when T has some specific rules, as you're asking for. However, since the method in question will be a static method, defined outside of MyBaseClass, there's limits to how much of the internals of MyBaseClass you can access, and you can't access the method inside MyBaseClass, so it depends on what you want to accomplish and whether you can live with the limitations or not. Anyway, here's the extension method. Note that you remove it completely from MyBaseClass at the same time: ``` public static class MyBaseClassExtensions { public static IQueryable<T> ShowThisMethod<T>(this MyBaseClass<T> mbc) where T: class, IMyInterface { ... } } ```
Also note that ShowThisMethod is *redefining* T in the context of ShowThisMethod. It is not the same T as defined by the class. Specifying a different Type parameter where the new one inherits from the one defined by the class would be the best approach, though that ends up requring the caller to have to specify the generic Type twice.
C#: Add conditional generic method (different generic restriction) within generic class
[ "", "c#", "linq", "" ]
What is a good way to return success or one or more error codes from a C++ function? I have this member function called save(), which saves to each of the member variables, there are at least ten of these member variables that are saved-to, for the call to save(), I want to find out if the call failed, and if so, on which member variable (some are hard failures, some are soft).
You can either return an object that has multiple error fields or you can use 'out'parameters. How you do this depends on your design and what exactly you are trying to return back. A common scenario is when you need to report back a status code along with a message of sorts. This is sometimes done where the function returns the status code as the return value and then returns the message status via an 'out' parameter. If you are simply returning a set of 'codes', it might make more sense to construct a struct type and return that. In that case, I would be prone to pass it in as an out parameter and have the method internally update it instead of allocating a new one each time. Are you planning on doing this once or many times?
I know this doesn't really answer your question, but... In C++ you should use exceptions instead of returning error codes. Error codes are most commonly used by libraries which don't want to force the library user to use a particular error handling convention, but in C++, we already have stdexcept. Of course, there might be reasons you don't use exceptions, such as if you're writing embedded code or kernel extensions.
how to return multiple error codes from C++ function
[ "", "c++", "" ]
I have an application that needs to support a multilingual interface, five languages to be exact. For the main part of the interface the standard ResourceBundle approach can be used to handle this. However, the database contains numerous tables whose elements contain human readable names, descriptions, abstracts etc. It needs to be possible to enter each of these in all five languages. While I suppose I could simply have fields on each table like ``` NameLang1 NameLang2 ... ``` I feel that that leads to a significant amount of largely identical code when writing the beans the represent each table. From a purely object oriented point of view the solution is however simple. Each class simply has a Text object that contains the relevant text in each of the languages. This is further helpful in that only one of the language is mandated, the others have fallback rules (e.g. if language 4 is missing return language 2 which fall back to language 1 which is mandatory). Unfortunately, mapping this back to a relational database, means that I wind up with a single table that some 10-12 other tables FK to (some tables have more than one FK to it in fact). This approach seems to work and I've been able to map the data to POJOs with Hibernate. About the only thing you cant do is map from a Text object to its parent (since you have no way of knowing which table you should link to), but then there is hardly any need to do that. So, overall this seems to work but it just feels wrong to have multiple tables reference one table like this. Anyone got a better idea? If it matters I'm using MySQL...
I had to do that once... multilingual text for some tables... I don't know if I found the best solution but what I did was have the table with the language-agnostic info and then a child table with all the multilingual fields. At least one record was required in the child table, for the default language; more languages could be added later. On Hibernate you can map the info from the child tables as a Map, and get the info for the language you want, implementing the fallback on your POJO like you said. You can have different getters for the multilingual fields, that internally call the fallback method to get the appropiate child object for the needed language and then just return the required field. This approach uses more table (one extra table for every table that needs multilingual info) but the performance is much better, as well as the maintenance I think...
The standard translation approach as used, for example, in [gettext](http://www.gnu.org/software/hello/manual/gettext/Java.html) is to use a single string to describe the concept and make a call to a translate method which translates to the destination language. This way you only need to store in the database a single string (the canonical representation) and then make a call in your application to the translate method to get the translated string. No FKs and total flexibility at the cost of a little of runtime performance (and maybe a bit more of maintenance trouble, but with some thought there's no need to make maintenance a problem in this scenario).
Multilingual fields in DB tables
[ "", "java", "mysql", "hibernate", "database-design", "internationalization", "" ]
I'm using Java and XStream to parse a google geocode request over http. My idea is to have an Address class with all the geocode attr's (ie. lat/long, city, provice/state etc) but I'm having problems parsing the xml with xstream. The google response is similar to this: ``` <?xml version="1.0" encoding="UTF-8" ?> <kml xmlns="http://earth.google.com/kml/2.0"><Response> <name>98 St. Patrick St, Toronto</name> <Status> <code>200</code> <request>geocode</request> </Status> <Placemark id="p1"> <address>98 St Patrick St, Toronto, ON, Canada</address> <AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"> <Country><CountryNameCode>CA</CountryNameCode><CountryName>Canada</CountryName><AdministrativeArea><AdministrativeAreaName>ON</AdministrativeAreaName><Locality><LocalityName>Toronto</LocalityName><Thoroughfare><ThoroughfareName>98 St Patrick St</ThoroughfareName></Thoroughfare><PostalCode><PostalCodeNumber>M5T</PostalCodeNumber></PostalCode></Locality></AdministrativeArea></Country></AddressDetails> <ExtendedData> <LatLonBox north="43.6560378" south="43.6497426" east="-79.3864912" west="-79.3927864" /> </ExtendedData> <Point><coordinates>-79.3896388,43.6528902,0</coordinates></Point> </Placemark> </Response></kml> ``` That doesn't show up very well, but the meat of the code is in the AddressDetails tag. Anyway, I'm new to Java and XStream so the API terminology is a bit confusing for me. I just need to be able to write some mapper that maps all these tags (ie. CountryName) to an attribute within my Address object, (ie. address.country = blah) The address object will be pretty simple, mainly just strings for country name etc and floats for lat/long. The docs and example just show straight mapping where each xml tag maps directly to the attribute of the same name of the object. In my case however, the tags are named different than the object attr's. A quick point in the right direction is all I'm looking for really.
I've used XStream in several projects. Unfortunately, your problem isn't really what XStream is designed to solve. You might be able to use its converter mechanism to achieve your immediate goal, but you'll run into limitations. In a nutshell, XStream isn't designed to do conversion of Tree Structure A into Tree Structure B -- it's purpose is to convert from a Java domain model into some reasonable XML. XStream is a great tool when you don't care much about the details of the XML produced. If you care more about the XML than the Java objects, look at XMLBeans -- the Java is ugly, but it's incredibly schema-compliant. For your project, I'd run the Google XML schema through XML beans, generate some Java that will give you a more literate way of hand-coding a converter. You could use a raw DOM tree, but you'd have code like myAddress.setStreet(root.getFirstChild().getAttribute("addr1"))). With XML beans, you say things like myAddress.setStreet(googleResult.getAddress().getStreetName(); I'd ignore JAXB as it's attempt to separate interface from implementation adds needless complexity. Castor might be a good tool to consider as well, but I haven't used it in years. In a nutshell, there aren't a lot of good Object-to-Object or XML-to-Object converters that handle structure conversion well. Of those I've seen that attempt declarative solutions, all of them seemed much more complicated (and no more maintainable) than using XStream/XmlBeans along with hand-coded structure conversions.
Would it be possible to define a separate class specifically for dealing with XStream's mapping? You could then simply populate your `AddressDetails` object by querying values out of this other object.
parse google geocode with xstream
[ "", "java", "geocoding", "xstream", "" ]
I have data used primarily in one table in a database and referenced in several different tables. I need to correct the data. Is it possible to write a "where-used" statement that will search every table in the database and return all tables where the data is referenced? I am using SQL 2005. Thanks.
I've found this sql statement [here](http://blog.sqlauthority.com/2007/09/16/sql-server-2005-list-all-the-constraint-of-database-find-primary-key-and-foreign-key-constraint-in-database/): ``` SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint, SCHEMA_NAME(schema_id) AS SchemaName, OBJECT_NAME(parent_object_id) AS TableName, type_desc AS ConstraintType FROM sys.objects WHERE type_desc LIKE '%CONSTRAINT' AND OBJECT_NAME(OBJECT_ID) LIKE 'FK_%' ``` NOTE:- I name all foreign key constraints starting with *FK\_* so it is easy to filter them.
Try adding a diagram to the database, and drop all of the tables onto it. If I've interpreted your question correctly you're trying to understand a database schema that already exists? IF you use the diagram it will draw on the references for you which will allow you to see where the data is linked in your table structure. As for SQL you can use joins, or where conditions to link data from different tables. What are you trying to "correct"?
Where Used Statements in SQL
[ "", "sql", "sql-server-2005", "" ]
How do I remove a module from Sitefinity?
**Edit:** This only applies to Sitefinity 3.x It depends on how far you want to go with the clean up. If you want to simply disabled a module this can be done through the web.config look for the section: ``` <telerik><framework><modules> ``` Simply remove the module from there and Sitefinity won't load the module. **Optional** The next steps are completely optional, but will fully remove a module. Then to go further you could delete the dlls from the Bin folder that represent the modules eg Telerik.Blogs and Telerik.Blogs.Data are for the Blogs module and all the module are named in this manner. Search for any references to the module in the web.config: eg in the sections * SectionGroups * Telerik * ToolBox * MetaFields Then as a further clean up depending on what version of Sitefinity you are using and what module you are using. **Some modules can't be removed though like Images and Documents and Generic Content as they are integral in the CMS Pages** I just found also that Telerik have a [knowledgebase article](http://www.sitefinity.com/support/knowledge-base/kb-article/b1154K-bbgc-b1154T-cgh.aspx) on this.
I don't know a lot about Sitefinity but i am sure you can find what you are looking for on their **[support pages](http://www.sitefinity.com/support/get-support.aspx)**, you will find videos, forums, blog post. Also you can Submit a Support Ticket there if you didn't find a good answer.
Remove a module from Sitefinity
[ "", "c#", "asp.net", "sitefinity", "" ]
G'day folks. I'm trying to introduce Ruby at work, and a few people are interested. However, I've been asked to present the benefits of Ruby over Python and PHP. I've broken this down into 2 parts: 1) show Python and Ruby's advantages over PHP; 2) show Ruby's advantages over Python. The first is easy. I'll explain things like: * Everything's an object. * Python and Ruby are easier to read and write. For the second, I'm thinking of: * Ruby has many conveniences, which makes it easier to read and write. Eg: Optional brackets, and being able to open built-ins, allows for things like 2.days.from\_now * RSpec is miles ahead of Python's TDD and BDD frameworks. * GitHub and RubyForge are fantastic resources for finding, releasing, and collaborating on software. Do you have any suggestions? I'm all ears!
Don't get sucked into comparative arguments - unless you're experienced in all three languages, you'll just be revealing your ignorance - especially when claiming "X can't do Y". The true fans will take you down. Instead, show off what ruby can do. It's a great language, but that has nothing to do with how well people talk about it. What matters is the code. So show off. Demonstrate your productivity, reliability, and flexibility with the language. Make it the easiest thing to follow at the code review. Have suites and suites of tests. Read up on sneaky techniques from [RedHanded](http://redhanded.hobix.com/) if you have to. Win your coworkers with your code -- it'll be far more convincing than your words ever could be.
If your goal is to show why language X is **better** than language Y, you're stuck in subjective-land where there are no right answers. No, Ruby is not **better** than PHP or Python. It might be more suited for a given purpose, and for that you can give specific examples. PHP is a poor choice for writing an SMTP server; Ruby and Python will serve you better (in fact, in Python it can be done in just a few lines, can't speak for Ruby though). On the other hand, PHP is better suited than Ruby for writing a one-off, short backend for an email submission form. The code is short, easy to maintain, quick to write, etc. PHP has an absolutely huge developer base, making programmers easy to find, which comes in handy if you ever want to out-source any aspect of the development chain. On the other hand, it's also terrifically easy to write horrible code in PHP, and there is more than enough of that going around. Python has a much larger user base than Ruby, and indeed is the primary language that RedHat uses for developing system tools. So if you're on a RedHat derived server (and statistically, chances are pretty good that you are if you're using Linux) then Python is guaranteed to be already in-place and working properly, etc. In short, weigh the benefits, make a decision, but don't assume that people will agree with you; after all it's just an opinion. --- **Edit** It just occurred to me that I failed to state the whole point: you shouldn't be trying to **convince** other people that they should use Ruby over Python/PHP. Instead you should be trying to **determine** whether you should use Ruby over Python/PHP. You can't go fact-finding like this having already determined what the answer will be -- that's not helpful. Instead you should be gathering information on the benefits and drawbacks of each language and weighing that against the requirements of your company. Once you come to a conclusion, you'll already have a preponderance of evidence showing it was the correct one.
Convincing others of Ruby over Python and PHP
[ "", "python", "ruby", "" ]
I have a Windows Template Library CListViewCtrl in report mode (so there is a header with 2 columns) with owner data set. This control displays search results. If no results are returned I want to display a message in the listbox area that indicates that there were no results. Is there an easy way to do this? Do you know of any existing controls/sample code (I couldn't find anything). Otherwise, if I subclass the control to provide this functionality what would be a good approach?
I ended up subclassing the control and handling OnPaint like this: ``` class MsgListViewCtrl : public CWindowImpl< MsgListViewCtrl, WTL::CListViewCtrl > { std::wstring m_message; public: MsgListViewCtrl(void) {} BEGIN_MSG_MAP(MsgListViewCtrl) MSG_WM_PAINT( OnPaint ) END_MSG_MAP() void Attach( HWND hwnd ) { SubclassWindow( hwnd ); } void SetStatusMessage( const std::wstring& msg ) { m_message = msg; } void OnPaint( HDC hDc ) { SetMsgHandled( FALSE ); if( GetItemCount() == 0 ) { if( !m_message.empty() ) { CRect cRect, hdrRect; GetClientRect( &cRect ); this->GetHeader().GetClientRect( &hdrRect ); cRect.top += hdrRect.Height() + 5; PAINTSTRUCT ps; SIZE size; WTL::CDCHandle handle = this->BeginPaint( &ps ); handle.SelectFont( this->GetFont() ); handle.GetTextExtent( m_message.c_str(), (int)m_message.length(), &size ); cRect.bottom = cRect.top + size.cy; handle.DrawText( m_message.c_str(), -1, &cRect, DT_CENTER | DT_SINGLELINE | DT_VCENTER ); this->EndPaint( &ps ); SetMsgHandled( TRUE ); } } } }; ``` After the search runs, if there are no results, I call SetStatusMessage and the message is displayed centered under the header. That's what I wanted. I'm kind of a newbie at subclassing controls so I'm not sure if this is the best solution.
If you're on Vista or later, handle the `LVN_GETEMPTYMARKUP` notification. For pre-Vista, you'll need to paint the message yourself.
WTL CListViewCtrl with status text
[ "", "c++", "wtl", "" ]
I have code like this: ``` class MapIndex { private: typedef std::map<std::string, MapIndex*> Container; Container mapM; public: void add(std::list<std::string>& values) { if (values.empty()) // sanity check return; std::string s(*(values.begin())); values.erase(values.begin()); if (values.empty()) return; MapIndex *&mi = mapM[s]; // <- question about this line if (!mi) mi = new MapIndex(); mi->add(values); } } ``` The main concern I have is whether the mapM[s] expression would return reference to NULL pointer if new item is added to the map? The [SGI docs](http://www.sgi.com/tech/stl/Map.html) say this: *data\_type& operator[](const key\_type& k) Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data\_type().* So, my question is whether the insertion of **default object data\_type()** will create a NULL pointer, or it could create an invalid pointer pointing somewhere in the memory?
It'll create a `NULL` (0) pointer, which is an invalid pointer anyway :)
Yes it should be a zero (NULL) pointer as stl containers will default initialise objects when they aren't explicitly stored (ie accessing a non-existant key in a map as you are doing or resizing a vector to a larger size). C++ Standard, 8.5 paragraph 5 states: > To default-initialize an object of > type T means: > > * If T is a non-POD class type (clause class), the default > constructor for T is called (and the > initialization is ill-formed if T has > no accessible default constructor) > * If T is an array type, each element is default-initialized > * Otherwise, the storage for the object iszero-initialized. You should also note that default initialisation is different to simply ommiting the constructor. When you omit the constructor and simply declare a simple type you will get an indeterminate value. ``` int a; // not default constructed, will have random data int b = int(); // will be initialised to zero ```
What is the default constructor for C++ pointer?
[ "", "c++", "dictionary", "pointers", "constructor", "" ]
I need to add some validations before the user navigates away via an ASP.NET Menu. I noticed that the items are rendered to use a javascript function called Menu\_Key ``` <td id="ctl00_MainMenun1" onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)"> ``` I there a way to override that function and have the menu execute one of mine, from which I could validate what I need and then call the original?
Redefine the function after it was initially defined, but keep track of it in a var so that you can call it later. You would effectively be renaming the original Menu\_Key function. ``` var originalMenu_Key = Menu_Key; Menu_Key = function(t) { // do your validations here if ( /* everything validated */ ) { originalMenu_Key (t); } }; ```
Above solution is a valid one, but in common case redefinition can be done in a bit more flexible way ``` var originalMenu_Key = Menu_Key; Menu_Key = function(t) { // do your validations here if ( /* everything validated */ ) { return originalMenu_Key.apply(this,argumets); } }; ``` In such case , any changes in function signature , will not break wrapping logic.
'overriding' javascript function
[ "", "asp.net", "javascript", "menu", "" ]
I'm fairly new to Python and recursive functions as a whole, so pardon my ignorance. I am trying to implement a binary search tree in Python and have the following insert method (taken out of a class): ``` def insert(self, key, root=None): '''Inserts a node in the tree''' if root == None: root = self.root if root.key == None: self._update(root, key) return 0 else: tmp = root if key > tmp.key: # we work with the right subtree self.insert(key, root=tmp.right) elif key < tmp.key: # we work with the left subtree self.insert(key, root=tmp.left) else: # key already exists return 0 ``` I'm not sure if this is legible, but it traverses the tree until it gets to a None value and updates the node with the key to insert. Now, the method works nicely and correctly creates a BST from scratch. But there's a problem with the return statements, as it only returns 0 if there is no recursion performed. ``` >>> bst.insert(10) 0 >>> bst.insert(15) >>> bst.root.right.key 15 >>> ``` "Inserting" the root key again returns 0 (from line 15) the way it should. ``` >>> bst.insert(10) 0 ``` I can't figure out why this happens. If I put a print statement in line 6, it executes correctly, yet it just won't return anything past the first insertion. Why is this? (I'm pretty sure I'm missing some basic information regarding Python and recursion) Thanks for your help, Ivan P.S.: I've read that recursion is not the best way to implement a BST, so I'll look into other solutions, but I'd like to know the answer to this before moving on.
On your recursive lines, you do not return anything. If you want it to return 0, you should replace them with lines like: ``` return self.insert(key, root=tmp.left) ``` instead of just ``` self.insert(key, root=tmp.left) ```
You are inside a function and want to return a value, what do you do? You write ``` def function(): return value ``` In your case you want to return the value returned by a function call, so you have to do. ``` def function(): return another_function() ``` However you do ``` def function(): another_function() ``` Why do you think that should work? Of course you use recursion but in such a case you should remember the Zen of Python which simply says: > Special cases aren't special enough to break the rules.
Recursion and return statements
[ "", "python", "recursion", "" ]
I have a method that requires a `const char` pointer as input (not null terminated). This is a requirement of a library (TinyXML) I'm using in my project. I get the input for this method from a `string.c_str()` method call. Does this `char` pointer need to be deleted? The string goes out of scope immediately after the call completes; so the string should delete it with its destructor call, correct?
The char array returned by `string.c_str()` is null terminated. If tinyXML's function takes a not null terminated char\* buffer, then your probably gonna get some unexpected behaviour. > `const char* c_str ( ) const;` > > Get C string equivalent > > Generates a null-terminated sequence > of characters (c-string) with the same > content as the string object and > returns it as a pointer to an array of > characters. > > A terminating null character is > automatically appended. No, it does not need to be released. String's destructor does that for you. > The returned array points to an > internal location with the required > storage space for this sequence of > characters plus its terminating > null-character, but the values in this > array should not be modified in the > program and are only granted to remain > unchanged until the next call to a > non-constant member function of the > string object. [Source](http://www.cplusplus.com/reference/string/string/c_str/)
Do not delete the memory you get from std::string::c\_str. The string is responsible for that (and it is entirely possible it gave you a pointer to its internal buffer, so if you deleted it, that would be a bad thing (tm)).
c++ char array out of scope or not?
[ "", "c++", "string", "memory-management", "stl", "" ]
I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple file.write() and file.writelines() do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) converting the individual values? I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!
``` m = [[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]] file.write(str(m)) ``` If you want more control over the format of each value: ``` def format(value): return "%.3f" % value formatted = [[format(v) for v in r] for r in m] file.write(str(formatted)) ```
the following works for me: ``` with open(fname, 'w') as f: f.writelines(','.join(str(j) for j in i) + '\n' for i in matrix) ```
How do I write a float list of lists to file in Python
[ "", "python", "file-io", "" ]
What is the the best practice for SQL connections? Currently I am using the following: ``` using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING)) { sqlConn.Open(); // DB CODE GOES HERE } ``` I have read that this is a very effective way of doing SQL connections. By default the SQL pooling is active, so how I understand it is that when the `using` code ends the `SqlConnection` object is closed and disposed but the actual connection to the DB is put in the SQL connection pool. Am i wrong about this?
That's most of it. Some additional points to consider: * Where do you get your connection string? You don't want that hard-coded all over the place and you may need to secure it. * You often have other objects to create as well before your really use the connection (`SqlCommand`, `SqlParameter`, `DataSet`, `SqlDataAdapter`), and *you want to wait as long as possible to open the connection*. The full pattern needs to account for that. * You want to make sure your database access is forced into it's own data layer class or assembly. So a common thing to do is express this as a private function call: . ``` private static string connectionString = "load from encrypted config file"; private SqlConnection getConnection() { return new SqlConnection(connectionString); } ``` And then write your sample like this: ``` using (SqlConnection sqlConn = getConnection()) { // create command and add parameters // open the connection sqlConn.Open(); // run the command } ``` That sample can only exist in your data access class. An alternative is to mark it `internal` and spread the data layer over an entire assembly. The main thing is that a clean separation of your database code is strictly enforced. A real implementation might look like this: ``` public IEnumerable<IDataRecord> GetSomeData(string filter) { string sql = "SELECT * FROM [SomeTable] WHERE [SomeColumn] LIKE @Filter + '%'"; using (SqlConnection cn = getConnection()) using (SqlCommand cmd = new SqlCommand(sql, cn)) { cmd.Parameters.Add("@Filter", SqlDbType.NVarChar, 255).Value = filter; cn.Open(); using (IDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { yield return (IDataRecord)rdr; } } } } ``` Notice that I was also able to "stack" the creation of the `cn` and `cmd` objects, and thus reduce nesting and only create one scope block. Finally, a word of caution about using the `yield return` code in this specific sample. If you call the method and don't complete your `DataBinding` or other use right away it could hold the connection open for a long time. An example of this is using it to set a data source in the `Load` event of an ASP.NET page. Since the actual data binding event won't occur until later you could hold the connection open much longer than needed.
Microsoft's [Patterns and Practices](http://msdn.microsoft.com/en-us/practices/default.aspx) libraries are an excellent approach to handling database connectivity. The libraries encapsulate most of the mechanisms involved with opening a connection, which in turn will make your life easier.
Managing SQL Server Connections
[ "", "c#", ".net", "sql-server", "connection-pooling", "sqlconnection", "" ]
Let's say we're having an application which should be able to store all kind of products. Each product has at least an `ID` and a `Name` but all other attributes can be defined by the user himself. 1. E.g. He could create a productgroup *Ipods* which would contain attributes *capacity* and *generation* 2. E.g. He could create a productgroup *TShirts* with the attributes *size* and *color* 3. We need to store the definition of a product and the concrete products itself. 4. We want to ensure that it is easily possible to aggregate (GROUP BY) by product attributes. E.g. select the total sum of capacity for each generation of ipods 5. The solution must not require schema changes (added requirement due to input from Bill Karwin - see his answer as well!) How would you model your schema in respect to the above requirements? **Note:** Requirment 4. is important! Thanks everyone for contributing and discussing the approach. I have seen some solutions to this problem in the past but none of them made grouping easy for me :(
The grouping is not going to be easy because what aggregate operator are you going to use on "color"? Note that it is not possible to use your requirement 4 on case 2. In any case, the aggregating is only difficult because of the variation in data types and can be mitigated by approaching it in a more typesafe way - knowing that it never makes sense to add apples and oranges. This is the classic EAV model and it has a place in databases where carefully designed. In order to make it a bit more typesafe, I've seen cases where the values are stored in type-safe tables instead of in a single free form varchar column. Instead of Values: ``` EntityID int ,AttributeID int ,Value varchar(255) ``` You have multiple tables: ``` EntityID int ,AttributeID int ,ValueMoney money EntityID int ,AttributeID int ,ValueInt int etc. ``` Then to get your iPod capacity per generation: ``` SELECT vG.ValueVarChar AS Generation, SUM(vC.ValueDecimal) AS TotalCapacity FROM Products AS p INNER JOIN Attributes AS aG ON aG.AttributeName = 'generation' INNER JOIN ValueVarChar AS vG ON vG.EntityID = p.ProductID AND vG.AttributeID = aG.AttributeID INNER JOIN Attributes AS aC ON aC.AttributeName = 'capacity' INNER JOIN ValueDecimal AS vC ON vC.EntityID = p.ProductID AND vC.AttributeID = aC.AttributeID GROUP BY vG.ValueVarChar ```
I'd recommend either the [Concrete Table Inheritance](http://martinfowler.com/eaaCatalog/concreteTableInheritance.html) or the [Class Table Inheritance](http://martinfowler.com/eaaCatalog/classTableInheritance.html) designs. Both designs satisfy all four of your criteria. In Concrete Table Inheritance: 1. Ipods are stored in table `product_ipods` with columns `ID`, `Name`, `Capacity`, `Generation`. 2. Tshirts are stored in table `product_tshirts` with columns `ID`, `Name`, `Size`, `Color`. 3. The definition of the concrete product types are in the metadata (table definitions) of `product_ipods` and `product_tshirts`. 4. `SELECT SUM(Capacity) FROM product_ipods GROUP BY Generation`; In Class Table Inheritance: 1. Generic product attributes are stored in table `Products` with columns `ID`, `Name`. Ipods are stored in table `product_ipods` with columns `product_id` (foreign key to `Products.ID`), `Capacity`, `Generation`. 2. Tshirts are stored in table `product_tshirts` with columns `product_id` (foreign key to `Products.ID`), `Size`, `Color`. 3. The definition of the concrete product types are in the metadata (table definitions) of `products`, `product_ipods`, and `product_tshirts`. 4. `SELECT SUM(Capacity) FROM product_ipods GROUP BY Generation`; --- See also my answer to "[Product table, many kinds of product, each product has many parameters](https://stackoverflow.com/questions/695752/product-table-many-kinds-of-product-each-product-has-many-parameters/695860#695860)" where I describe several solutions for the type of problem you're describing. I also go into detail on exactly **why EAV is a broken design.** --- Re comment from @dcolumbus: > With CTI, would each row of the product\_ipods be a variation with it's own price? I'd expect the price column to appear in the `products` table, if every type of product has a price. With CTI, the product type tables typically just have columns for attributes that pertain only to that type of product. Any attributes common to all product types get columns in the parent table. > Also, when storing order line items, would you then store the row from product\_ipods as the line item? In a line-items table, store the product id, which should be the same value in both the `products` table and the `product_ipods` table. --- Re comments from @dcolumbus: > That seems so redundant to me ... in that scenario, I don't see the point of the sub-table. But even if the sub-table does make sense, what's the connecting `id`? The point of the sub-table is to store columns that are not needed by all other product types. The connecting id may be an auto-increment number. The sub-type table doesn't need to auto-increment its own id, because it can just use the value generated by the super-table. ``` CREATE TABLE products ( product_id INT AUTO_INCREMENT PRIMARY KEY, sku VARCHAR(30) NOT NULL, name VARCHAR(100) NOT NULL, price NUMERIC(9,2) NOT NULL ); CREATE TABLE product_ipods ( product_id INT PRIMARY KEY, size TINYINT DEFAULT 16, color VARCHAR(10) DEFAULT 'silver', FOREIGN KEY (product_id) REFERENCES products(product_id) ); INSERT INTO products (sku, name, price) VALUES ('IPODS1C1', 'iPod Touch', 229.00); INSERT INTO product_ipods VALUES (LAST_INSERT_ID(), 16, 'silver'); INSERT INTO products (sku, name, price) VALUES ('IPODS1C2', 'iPod Touch', 229.00); INSERT INTO product_ipods VALUES (LAST_INSERT_ID(), 16, 'black'); INSERT INTO products (sku, name, price) VALUES ('IPODS1C3', 'iPod Touch', 229.00); INSERT INTO product_ipods VALUES (LAST_INSERT_ID(), 16, 'red'); INSERT INTO products (sku, name, price) VALUES ('IPODS2C1', 'iPod Touch', 299.00); INSERT INTO product_ipods VALUES (LAST_INSERT_ID(), 32, 'silver'); INSERT INTO products (sku, name, price) VALUES ('IPODS2C2', 'iPod Touch', 299.00); INSERT INTO product_ipods VALUES (LAST_INSERT_ID(), 32, 'silver'); INSERT INTO products (sku, name, price) VALUES ('IPODS2C3', 'iPod Touch', 299.00); INSERT INTO product_ipods VALUES (LAST_INSERT_ID(), 32, 'red'); ```
How do you model custom attributes of entities?
[ "", "sql", "sql-server", "database-design", "schema", "entity-attribute-value", "" ]
Is there a way of preserving the natural size of a JButton in the center of a BorderLayout? Right now, it expands in all directions to fill it up, but I want it normal size. If it isn't possible, how can I get a button to be in the center of a panel with its normal size?
I suggest going straight for `GridBagLayout`. Although it has some odd behaviour and a bad interface, it's a standard layout that does pretty much everything. You are going to need it, so you might as well consistently use the same layout manager even when it is not strictly necessary.
The component in the center of a BorderLayout is always stretched, you can get round this by adding the button to a JPanel with a FlowLayout and then adding that into the CENTER. ``` JPanel borderPanel = new JPanel(new BorderLayout()); JButton theButton = new JButton("Click Me"); JPanel flowPanel = new JPanel(new FlowLayout()); flowPanel.add(theButton); borderPanel.add(BorderLayout.CENTER, flowPanel); ```
Preserving the size of a JButton in BorderLayout.CENTER
[ "", "java", "swing", "" ]
My previous understanding of the decorator pattern was that you inherit `Window` with `WindowDecorator`, then in the overridden methods, do some additional work before calling the `Window`'s implementation of said methods. Similar to the following: ``` public class Window { public virtual void Open() { // Open the window } } public class LockableWindow : Window // Decorator { public virtual void Open() { // Unlock the window base.Open(); } } ``` However this essentially hardcodes the decoration, so how would this be refactored to use composition instead of inheritance?
Sorry, my C# is a a bit (OK, very) rusty, so there may be a few syntax errors, but the basic idea is right. ``` public interface IWindow { void Open(); } public class Window : IWindow { public virtual void Open() { // Open the window } } public class LockableWindow : IWindow { private IWindow _wrappedWindow; public LockableWindow(IWindow wrappedWindow) { _wrappedWindow = wrappedWindow; } public virtual void Open() { // TODO Unlock window if necessary _wrappedWindow.open(); } } ``` The key thing to notice is the new `IWindow` interface; that's what allows you to keep using polymorphism.
The point of the Decorator pattern is to enhance an object with some functionality (e.g. adding buffering to a stream) in a way that's transparent to the caller. In order to use it most effectively, you want to be able to swap in the decorated implementation without refactoring code, which basically implies that you need to maintain the inheritance hierarchy. What's your actual concern, i.e. what does "this hard-codes the decoration" really mean? What kind of problems do you envision wanting to solve? It may be that decoration is not quite the right approach...
Decorator Pattern Using Composition Instead of Inheritance
[ "", "c#", "design-patterns", "decorator", "composition", "" ]
I am having comment reply (only till one level) functionality. All comments can have as many as replies but no replies can have their further replies. So my database table structure is like below ``` Id ParentId Comment 1 0 this is come sample comment text 2 0 this is come sample comment text 3 0 this is come sample comment text 4 1 this is come sample comment text 5 0 this is come sample comment text 6 3 this is come sample comment text 7 1 this is come sample comment text ``` In the above structures, commentid, 1 (has 2 replies) and 3 (1 reply) has replies. So to fetch the comments and their replies, one simple method is first I fetch all the comments having ParentId as 0 and then by running a while loop fetch all the replies of that particular commentId. But that seems to be running hundreds of queries if I'll have around 200 comments on a particular record. So I want to make a query which will fetch Comments with their replies sequentially as following; ``` Id ParentId Comment 1 0 this is come sample comment text 4 1 this is come sample comment text 7 1 this is come sample comment text 2 0 this is come sample comment text 3 0 this is come sample comment text 6 3 this is come sample comment text 5 0 this is come sample comment text ``` I also have a comment date column in my comment table, if anyone wants to use this with comment query. So finally I want to fetch all the comments and their replies by using one single mysql query. Please tell me how I can do that? Thanks
You can use an expression in an ORDER BY. Try this: ``` SELECT * FROM comments ORDER BY IF(ParentId = 0, Id, ParentId), Id ``` This will first sort by Id, if ParentId = 0, or by ParentId otherwise. The second sort criterion is the Id, to assure that replies are returned in order.
I highly recommend that you restructure your database schema. The main problem is that you are trying to treat comments and replies as the same thing, and they simple aren't the same thing. This is forcing you to make some difficult queries. Imagine having two tables: [COMMENTS:(id, text)], and replies to comments in another table [REPLIES(id, commentid, text)]. The problem seems much, much easier when thought of in this way.
How to make comment reply query in MYSQL?
[ "", "sql", "mysql", "comments", "" ]
Given a handle to a Windows Registry Key, such as the ones that are set by ::RegOpenKeyEx(), is it possible to determine the full path to that key? I realize that in a simple application all you have to do is look up 5 or 10 lines and read... but in a complex app like the one I'm debugging, the key I'm interested in can be opened from a series of calls.
Use `LoadLibrary` and `NtQueryKey` exported function as in the following code snippet. ``` #include <windows.h> #include <string> typedef LONG NTSTATUS; #ifndef STATUS_SUCCESS #define STATUS_SUCCESS ((NTSTATUS)0x00000000L) #endif #ifndef STATUS_BUFFER_TOO_SMALL #define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L) #endif std::wstring GetKeyPathFromKKEY(HKEY key) { std::wstring keyPath; if (key != NULL) { HMODULE dll = LoadLibrary(L"ntdll.dll"); if (dll != NULL) { typedef DWORD (__stdcall *NtQueryKeyType)( HANDLE KeyHandle, int KeyInformationClass, PVOID KeyInformation, ULONG Length, PULONG ResultLength); NtQueryKeyType func = reinterpret_cast<NtQueryKeyType>(::GetProcAddress(dll, "NtQueryKey")); if (func != NULL) { DWORD size = 0; DWORD result = 0; result = func(key, 3, 0, 0, &size); if (result == STATUS_BUFFER_TOO_SMALL) { size = size + 2; wchar_t* buffer = new (std::nothrow) wchar_t[size/sizeof(wchar_t)]; // size is in bytes if (buffer != NULL) { result = func(key, 3, buffer, size, &size); if (result == STATUS_SUCCESS) { buffer[size / sizeof(wchar_t)] = L'\0'; keyPath = std::wstring(buffer + 2); } delete[] buffer; } } } FreeLibrary(dll); } } return keyPath; } int _tmain(int argc, _TCHAR* argv[]) { HKEY key = NULL; LONG ret = ERROR_SUCCESS; ret = RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft", &key); if (ret == ERROR_SUCCESS) { wprintf_s(L"Key path for %p is '%s'.", key, GetKeyPathFromKKEY(key).c_str()); RegCloseKey(key); } return 0; } ``` This will print the key path on the console: > Key path for 00000FDC is > '\REGISTRY\MACHINE\SOFTWARE\Microsoft'.
I was excited to find this article and its well liked solution. Until I found that my system's NTDLL.DLL did not have NtQueryKeyType. After some hunting around, I ran across ZwQueryKey in the DDK forums. It is in C#, but here is the solution that works for me: ``` enum KEY_INFORMATION_CLASS { KeyBasicInformation, // A KEY_BASIC_INFORMATION structure is supplied. KeyNodeInformation, // A KEY_NODE_INFORMATION structure is supplied. KeyFullInformation, // A KEY_FULL_INFORMATION structure is supplied. KeyNameInformation, // A KEY_NAME_INFORMATION structure is supplied. KeyCachedInformation, // A KEY_CACHED_INFORMATION structure is supplied. KeyFlagsInformation, // Reserved for system use. KeyVirtualizationInformation, // A KEY_VIRTUALIZATION_INFORMATION structure is supplied. KeyHandleTagsInformation, // Reserved for system use. MaxKeyInfoClass // The maximum value in this enumeration type. } [StructLayout(LayoutKind.Sequential)] public struct KEY_NAME_INFORMATION { public UInt32 NameLength; // The size, in bytes, of the key name string in the Name array. public char[] Name; // An array of wide characters that contains the name of the key. // This character string is not null-terminated. // Only the first element in this array is included in the // KEY_NAME_INFORMATION structure definition. // The storage for the remaining elements in the array immediately // follows this element. } [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern int ZwQueryKey(IntPtr hKey, KEY_INFORMATION_CLASS KeyInformationClass, IntPtr lpKeyInformation, int Length, out int ResultLength); public static String GetHKeyName(IntPtr hKey) { String result = String.Empty; IntPtr pKNI = IntPtr.Zero; int needed = 0; int status = ZwQueryKey(hKey, KEY_INFORMATION_CLASS.KeyNameInformation, IntPtr.Zero, 0, out needed); if ((UInt32)status == 0xC0000023) // STATUS_BUFFER_TOO_SMALL { pKNI = Marshal.AllocHGlobal(sizeof(UInt32) + needed + 4 /*paranoia*/); status = ZwQueryKey(hKey, KEY_INFORMATION_CLASS.KeyNameInformation, pKNI, needed, out needed); if (status == 0) // STATUS_SUCCESS { char[] bytes = new char[2 + needed + 2]; Marshal.Copy(pKNI, bytes, 0, needed); // startIndex == 2 skips the NameLength field of the structure (2 chars == 4 bytes) // needed/2 reduces value from bytes to chars // needed/2 - 2 reduces length to not include the NameLength result = new String(bytes, 2, (needed/2)-2); } } Marshal.FreeHGlobal(pKNI); return result; } ``` I've only ever tried it while running as Administrator, which may be required. The result is a bit oddly formatted: `\REGISTRY\MACHINE\SOFTWARE\company\product` for example, instead of `HKEY_LOCAL_MACHINE\SOFTWARE\company\product`.
Determine path to registry key from HKEY handle in C++
[ "", "c++", "registry", "handle", "" ]
I need to build a system of workers (represented as threads) and (multiple) queues. Individual jobs are waiting in one of the queues and waits for a worker thread to process them. Each worker can process jobs only from some of the queues. No spin-waiting. C/C++, pthreads, standard POSIX. The problem for me is the "multiple queues" thing. I know how to implement this with a single queue. The workers need to wait on all the queues that they can process (wait for ANY of them). On Windows I would use WaitForMultipleObjects, but this needs to be multi-platform. I don't want any particular code for this, only a hint or a description of the model which I should use. Thanks in advance.
What you can do is use a [condition variable](https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables). Have your worker threads wait on a condition variable. When a job gets added to any of the job queues, signal the condition variable. Then, when the worker thread wakes up, it checks the queues it's waiting on. If any of them have a job, it takes that job off the queue. Otherwise, it goes back to waiting on the condition variable. Waiting on a condition variable puts the thread to sleep, so it does not consume CPU time. Of course, it goes without saying that you should protect all accesses to the job queues with a mutex (e.g. `pthread_mutex_t`).
How about: * all worker threads wait on a semaphore * when anything is added to the queue, the semaphore is incremented, which wakes a single thread * the thread checks the queues it is interested in, processes one of them and goes back to waiting on the semaphore You will need additional mutex(es) to control actual read & writes to the queues.
C++ - threads and multiple queues
[ "", "c++", "multithreading", "queue", "posix", "pthreads", "" ]
I've been developing an application in C# (using VS2008) for quite sometime now and about a week ago, 'Edit and Continue' has stopped working for me. I can edit the code while debugging, but any little change that I make to the code now forces me to stop the project and restart it. The message that I get is this: `Modifying a 'method' which contains a lambda expression will prevent the debug session from continuing while edit and continue is enabled.` Oddly, I'm not even using lambda's when this happens. Modifying the same chunk of code last week while in debug mode allowed me to continue with no problems. I've done various searches on the internet to find out what I could have done to cause this change in behavior. The only help I can find on the web is directly related to debugging ASP.NET web projects. However, this portion of my solution is a Windows Forms project. What could the problem be? Is there a way to fix this? I would greatly appreciate any help.
"Edit and Continue is not supported when you start debugging using Attach to Process. Edit and Continue is not supported for mixed-mode, combined managed and native, debugging, SQL debugging, Compact Framework (Smart Device) projects, debugging on Windows 98, or 64-bit debugging." <http://msdn.microsoft.com/en-us/library/ba77s56w.aspx> **edit** -- That link says VB, but I'm sure I've had the same problem with mixed native and managed code and 64 bit debugging when using c#.
Just a guess, but perhaps the method you are debugging contains a Type captured from a lambda. Below is a quote from [here](http://social.msdn.microsoft.com/Forums/en-US/vcsharp2008prerelease/thread/9b6cb03d-9a0a-42e0-938b-37beff246a27). > ... EnC [EditAndContinue] can modify > IL, but not types--that is, it can't > add fields or methods to a type, > remove a type, or create a new one. > Lambda expressions that capture local > variables can result in the creation > of hidden types under the hood. > Modifying a method containing a lambda > expression could change the locals > that are captured, which would require > changing the hidden type. The same > limitation has existed with anonymous > methods since C# 2.0 and VS 2005.
Edit and Continue quit working for me at some point
[ "", "c#", "visual-studio-2008", "debugging", "" ]
I am trying to implement a feature similar to the "Related Questions" on Stackoverflow. How do I go about writing the SQL statement that will search the Title and Summary field of my database for similar questions? If my questions is: "What is the SQL used to do a search similar to "Related Questions" on Stackoverflow". Steps that I can think of are; 1. Strip the quotation marks 2. Split the sentence into an array of words and run a SQL search on each word. If I do it this way, I am guessing that I wouldn't get any meaningful results. I am not sure if Full Text Search is enabled on the server, so I am not using that. Will there be an advantage of using Full Text Search? I found a similar question but there was no answer: [similar question](https://stackoverflow.com/questions/39240/similar-posts-like-functionality-using-ms-sql-server) Using SQL 2005
After enabling Full Text search on my SQL 2005 server, I am using the following stored procedure to search for text. ``` ALTER PROCEDURE [dbo].[GetSimilarIssues] ( @InputSearch varchar(255) ) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @SearchText varchar(500); SELECT @SearchText = '"' + @InputSearch + '*"' SELECT PostId, Summary, [Description], Created FROM Issue WHERE FREETEXT (Summary, @SearchText); END ```
Check out this [podcast](https://blog.stackoverflow.com/2008/12/podcast-32/). > One of our major performance > optimizations for the “related > questions” query is removing the top > 10,000 most common English dictionary > words (as determined by Google search) > before submitting the query to the SQL > Server 2008 full text engine. It’s > shocking how little is left of most > posts once you remove the top 10k > English dictionary words. This helps > limit and narrow the returned results, > which makes the query dramatically > faster.
What is the SQL used to do a search similar to "Related Questions" on Stackoverflow
[ "", "sql", "search", "text", "" ]
I need a javascript function that can take in a string and an array, and return true if that string is in the array.. ``` function inArray(str, arr){ ... } ``` caveat: it can't use any javascript frameworks.
you can use arr.indexOf() <http://www.w3schools.com/jsref/jsref_indexof_array.asp>
You could just make an array prototype function ala: ``` Array.prototype.hasValue = function(value) { var i; for (i=0; i<this.length; i++) { if (this[i] === value) return true; } return false; } if (['test'].hasValue('test')) alert('Yay!'); ``` Note the use of '===' instead of '==' you could change that if you need less specific matching... Otherwise [3].hasValue('3') will return false.
javascript function inArray
[ "", "javascript", "arrays", "" ]
I have MS SQL Management Studio for editing table data, and it is doesn't have a good usability. I need to edit some hundred rows like in Excel, being able to order columns to easy editing process (SQL Mgmt only has 'Open table' feature, without ordering columns, updates diferent than that is only possible using UPDATE SQL code). LinqPad is wonderful, but only for queries. I would like to edit table results. I installed Acqua Studio and it has everything, but trial expired. Do you know any software free alternatives which can do that? **EDIT**: I really need to alter and input data, of course I can do it by SQL code, but it is not fast when you have to update manually tons of rows. I need an **editable ordered grid**. I'll try MSManager Lite. Thanks
I have this tool permanently on a USB stick - really, really good for a free "lite" edition (a pro version is available too) <http://sqlmanager.net/products/mssql/manager> It is a single monolithic exe, so great for portability.
I would suggest learning the necessary SQL to update the appropriate data in the tables. You can use SELECT statements with ORDER BY clauses to view the data in the order that you wish to view it, and then build a query to update that data. You can use transactions to make sure what your updating is correct as you go (if you are still learning the SQL and don't want to mess up the database). ``` BEGIN TRANSACTION -- starts a transaction ROLLBACK -- stops the transaction and rolls back all changes to the tables COMMIT -- stops the transaction and commits all changes to the tables ``` What are you trying to accomplish/update, maybe we can help you with that? **EDIT** You mentioned that you wanted to edit some product names that are stored inside of a table. and that this would be a one-time task. I've set up a small demo below that I hope will help guide you towards a solution that may work for your situation. copy and paste this into a SQL Management Studio session. Also if you wanted, you can export your current data to say excel, edit that data in excel, import it as a new temporary table and run a SQL update script to update the original table. ``` /* Products Before Update Products After Update =========================== ============================================= ID ProductName ID ProductName --------------------------- --------------------------------------------- 1 MSFT 1 Microsoft Corp. 2 APPL 2 Apple Inc. 3 Cisco Systems, Inc. 3 Cisco Systems, Inc. 4 IBM 4 International Business Machines Corp. 5 JAVA 5 Sun Microsystems, Inc. 6 ORCL 6 Oracle Corp. */ -- Imagine that this table is a table in your database DECLARE @products TABLE ( ID INT, ProductName VARCHAR(255) ) -- And this table has some product information -- which you are trying to update with new information INSERT @products SELECT 1, 'MSFT' UNION ALL SELECT 2, 'APPL' UNION ALL SELECT 3, 'Cisco Systems, Inc.' UNION ALL SELECT 4, 'IBM' UNION ALL SELECT 5, 'JAVA' UNION ALL SELECT 6, 'ORCL' -- Either build an in-memory temporary table of the product names you wish to update -- Or do a database task to import data from excel into a temporary table in the database DECLARE @products_update TABLE ( ID INT, ProductName VARCHAR(255) ) INSERT @products_update SELECT 1, 'Microsoft Corp.' UNION ALL SELECT 2, 'Apple Inc.' UNION ALL SELECT 4, 'International Business Machines Corp.' UNION ALL SELECT 5, 'Sun Microsystems, Inc.' UNION ALL SELECT 6, 'Oracle Corp.' -- Update the table in the database with the in-memory table -- for demo purposes, we use @products to represent the database table UPDATE p1 SET ProductName = ISNULL(p2.ProductName, p1.ProductName) FROM @products p1 LEFT JOIN @products_update p2 ON p1.ID = p2.ID -- Now your products table has been updated SELECT * FROM @products ```
Good table editor for MS SQL Server?
[ "", "sql", "sql-server", "linq", "" ]
Is there a way to modify the behavior of the OpenFileDialog so that it looks inside the files in the folder it opens to and then ignores certain ones based on their content? One example would be to open to a folder full of Zip files but only show the ones that contain a certain file. From the documentation, there's the HookProc but I'm not exactly sure how I'd use it. Please note that if it is possible, I realize that it'll be a relatively slow operation. At the moment I'm not concerned about performance. Thanks!
I wouldn't dismiss the complexity of the OpenFileDialog. It's not so easy to build one that really works. When you do build your own, it's not the "normal" dialog and as a result it confuses users. This is true even if you do it well, which is difficult. So I'd suggest you stick to extending what is already there, rather than writing something new. Check [this article for an extension of OFD](http://www.codeproject.com/KB/dialog/OpenFileDialogEx.aspx) that might/could be tweaked to do exactly what you want. There's a callback that you write in C# that responds to path selection. Related: [FolderBrowserDialogEx](http://dotnetzip.codeplex.com/SourceControl/changeset/view/29832#432677) is a similar extension on FolderBrowserDialog. Despite the name, you can configure it to search for files, as well as folders. There's a callback that gets invoked when something (a folder, a file) is selected, and within that callback you can do what you need to do. For example, peek inside the files within a folder and populate the list of files to display with only those files. --- Another option you might consider is the [dialog library from Ookii](http://www.ookii.org/software/dialogs/). This is an open source implementation of the OpenFileDialog, and it includes COM wrappers for all the new dialog stuff in Vista. Using that library you can pop a Vista OpenFileDialog and receive events from the [IFileDialogEvents](http://msdn.microsoft.com/en-us/library/bb775876.aspx) interface, in C# code. One such event is OnFolderChange(). Within the handler you could call IFolder.GetFolder() which will get you an [IShellItem](http://msdn.microsoft.com/en-us/library/bb761144(VS.85).aspx), which gives you the folder the user is changing to. The next step would be to itemize and potentially filter the set of files, which is an exercise I will leave to the reader...
No, you would have to implement your own functionality for that. But to be honest, the OpenFileDialog really doesn't do a whole lot anyway. To be honest, yeah, you probably could hook into it, but you'd be doing a lot of work for nothing when the real work is to inspect the content of the files and then you can write your own simple OpenFileDialog class on top of that. You might find this question helpful regarding listing contents of zip files: [How to list the contents of a .zip folder in c#?](https://stackoverflow.com/questions/307774/how-to-list-the-contents-of-a-zip-folder-in-c) (Note, you could potentially thread it to improve performance, just don't span many threads)
Filtering the files shown in OpenFileDialog based on content?
[ "", "c#", "wpf", "openfiledialog", "" ]
I'm using a Splash Screen from [Here](http://www.codersource.net/csharp_splash_screen.aspx). I love how simple it is. But the problem with it is that the splash screen doesn't go away until I click on it. When run within the IDE it works fine. Any ideas? I'd attach the code here but its not inserting properly for some reason. ``` private System.Windows.Forms.Timer timer1; //private Splash sp=null; public Form1() { InitializeComponent(); Thread th = new Thread(new ThreadStart(DoSplash)); //th.ApartmentState = ApartmentState.STA; //th.IsBackground=true; th.Start(); Thread.Sleep(3000); th.Abort(); Thread.Sleep(1000); } private void DoSplash() { Splash sp = new Splash(); sp.ShowDialog(); } private void timer1_Tick(object sender, System.EventArgs e) { // sp.Close(); } ```
First of all, the way the splash screen on that page is done, using [Thread.Abort](http://msdn.microsoft.com/en-us/library/system.threading.thread.abort(VS.71%29.aspx), is **not** the right way to do things. Never call [Thread.Abort](http://msdn.microsoft.com/en-us/library/system.threading.thread.abort(VS.71%29.aspx), unless you're in the process of shutting down the [AppDomain](http://msdn.microsoft.com/en-us/library/system.appdomain.aspx) the thread lives in. Let me reiterate that for emphasis. **The only time you should call [Thread.Abort](http://msdn.microsoft.com/en-us/library/system.threading.thread.abort(VS.71%29.aspx) is when you know enough about [Thread.Abort](http://msdn.microsoft.com/en-us/library/system.threading.thread.abort(VS.71%29.aspx) and how it behaves to know that you should never call it.** Take a look at this other question on StackOverflow: [Multi-Threaded splash screen in c#?](https://stackoverflow.com/questions/48916/multi-threaded-splash-screen-in-c). --- If you want to keep your existing solution, a possible better way would be to drop a timer into the splash screen form, set its timer to the time you want the splash screen to stay on screen, and call [Close](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.close.aspx) in its Tick event handler. In the same venue, I would simply fire off that original thread, and remove the other lines. In other words, from the first code block on that page, I would keep these two lines: ``` Thread th = new Thread(new ThreadStart(DoSplash)); th.Start(); ``` Couple that with that timer on the form that makes the form self-closing, and you're in way better shape than trying to get to grips with Thread.Abort. Which you should not call.
The DoSplash should probably call `sp.Show()` instead of `sp.ShowDialog()` But calling Sleep(x000) form your main thread to show a splash screen isn't very efficient, and Thread.Abort() should be reserved for better use too. A better approach is to close your SplashForm with a Timer and set a minimum delay. On startup you can Show() and Update() the SplahForm and continue to load stuff. The timer event won't fire until the MainForm is finished initializing and enters the EventLoop. No threads needed, and the MainForm doesn't have to be involved either. Just to give you the main ingredients of a MessageLoop driven SplashForm: ``` public partial class SplashForm : Form { // default stuff public static void Splash() { var s = new SplashForm(); s.Show(); s.Update();// force paint } private void SplashForm_Load(object sender, EventArgs e) { Timer t = new Timer(); t.Interval = 1; // wait for EventLoop t.Tick += GoAway; t.Enabled = true; } private void GoAway(object sender, EventArgs e) { this.Close(); } } ``` and then, in Program.cs, ``` Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SplashForm.Splash(); Application.Run(new MainForm()); ```
Splash Screen that doesn't go away
[ "", "c#", "splash-screen", "" ]
I have a visitor class resembling this: ``` struct Visitor { template <typename T> void operator()(T t) { ... } void operator()(bool b) { ... } }; ``` Clearly, **`operator()(bool b)`** is intended to be a specialization of the preceding template function. However, it doesn't have the **`template<>`** syntax that I'm used to seeing before it, declaring this as a template specialization. But it does compile. Is this safe? Is this correct?
Your code is not a template specialization, but rather a non-templated function. There are some differences there. The non-templated operator() will take precedence over a templated version (for an exact match, but type conversions will not take place there) but you can still force the templated function to be called: ``` class Visitor { public: // corrected as pointed by stefanB, thanks template <typename T> void operator()( T data ) { std::cout << "generic template" << std::endl; } void operator()( bool data ) { std::cout << "regular member function" << std::endl; } }; template <> // Corrected: specialization is a new definition, not a declaration, thanks again stefanB void Visitor::operator()( int data ) { std::cout << "specialization" << std::endl; } int main() { Visitor v; v( 5 ); // specialization v( true ); // regular member function v.operator()<bool>( true ); // generic template even if there is a non-templated overload // operator() must be specified there (signature of the method) for the compiler to // detect what part is a template. You cannot use <> right after a variable name } ``` In your code there is not much of a difference, but if your code needs to pass the template parameter type it will get funnier: ``` template <typename T> T g() { return T(); } template <> int g() { return 0; } int g() { return 1; } int main() { g<double>(); // return 0.0 g<int>(); // return 0 g(); // return 1 -- non-templated functions take precedence over templated ones } ```
What you have here is function overloading; to obtain template specialization, you indeed need the `template <>` syntax. However, you should be aware that these two approaches, even if they may seem identical, are subtly different, and even the compiler might get lost when choosing the right function to call. Listing all the possible cases would be a little too long for this answer, but you might want to check [Herb Sutter GoTW #49](http://www.gotw.ca/gotw/049.htm) on the subject.
Do template specializations require template<> syntax?
[ "", "c++", "templates", "syntax", "template-specialization", "" ]
Can you recoment a book on on Unit Testing and TDD for C# with at least some treatment of Mock Objects? I have seen this [question](https://stackoverflow.com/questions/31837/best-books-about-tdd) but it does not seem to mention mocking.
*The Art of Unit Testing: With Examples in .NET* by Roy Osherove ([Amazon Page](https://rads.stackoverflow.com/amzn/click/com/1933988274), [Official Site](http://www.artofunittesting.com/)) sounds like what you're looking for. He devotes one chapter introducing the concepts of stub and mock objects (using a "roll-your-own" approach), and then a second chapter on using mock object frameworks, particularly [Rhino Mocks](http://ayende.com/projects/rhino-mocks.aspx). There is somewhat less emphasis on Test-Driven Development, but there is quite a lot of information about TDD available from other sources, and TDD isn't all that language-specific.
Have a look at [Growing Object-Oriented Software, Guided by Tests](http://www.mockobjects.com/book/) by Steve Freeman and Nat Pryce - a work in progress, but free online. The code examples are in java, which shouldn't be a problem if you're a C# developer, and does focus extensively on Mocks.
What book on TDD for C# with treatment of Mocks
[ "", "c#", ".net", "tdd", "mocking", "" ]
I need to implement some NLP in my current module. I am looking for some good library that can help me here. I came across 'LingPipe' but could not completely follow on how to use it. Basically, we need to implement a feature where the application can decipher customer instructions (delivery instructions) typed in plain english. Eg: * Will pick up at 12:00 noon tomorrow * Request delivery after 10th June * Please do not send before Wednesday * Add 10 more units of XYZ to the order
[LingPipe](http://alias-i.com/lingpipe/) is very nice and well documented. You can also take a look at: * [OpenNLP](https://opennlp.apache.org/) * [Stanford NLP](http://nlp.stanford.edu/) * [Apache UIMA](http://incubator.apache.org/uima/) * [GATE](http://gate.ac.uk/) * [CogComp-NLP](https://github.com/CogComp/cogcomp-nlp) * [FrameNet](http://framenet.icsi.berkeley.edu/) The last one specifically might be of interest to you, although I don't know whether there are any readily available Java implementations (and maybe that's too big of a gun for your problem anyway :-) Paul's idea of using a DSL is probably easier and faster to implement, and more reliable to use for your customers. I, too, would recommend looking into that first.
I think whether or not you choose to use NLP might depend on the specific requirements for your system. Is it a requirement that free-form english should be accepted, or will only a certain set of instructions be accepted? It might be easier to build a [domain specific language](http://en.wikipedia.org/wiki/Domain_specific_language) that supports what your users need to convey than to do full-on semantic analysis of free-form text. In the Java space, Groovy has some support for [building DSLs](http://docs.groovy-lang.org/docs/latest/html/documentation/core-domain-specific-languages.html).
Is there a good natural language processing library
[ "", "java", "nlp", "" ]
I want to create a virtual numpad, similar to the on-screen keyboard. How do I prevent the form from ever being activated/focused, so that when I push a button on it, the SendKeys.Send call goes to the right form? I'm certain I have to use an unmanaged API for this, but besides that I'm not even sure where to begin. Thanks for any help!
You can control the way your form is created by overriding the protected CreateParams property: ``` protected override CreateParams CreateParams { get { var cp = base.CreateParams; // Configure the CreateParams structure here return cp; } } ``` I suggest trying the following style: ``` int WS_EX_NOACTIVATE = 0x08000000; cp.ExStyle = cp.ExStyle | WS_EX_NOACTIVATE; ``` The `WS_EX_NOACTIVATE` style prevents mouse input from giving a window focus (you can use this to create tooltip-like windows, for example.) You can combine this with other styles (like `WS_EX_TOPMOST`) to get the behavior you're after.
A form that does not have focus generally does not receive keyboard input. So I am not sure how you would get this to work.
Creating a virtual numpad: stop form from being activated/focused
[ "", "c#", "winforms", "" ]
I'm embarking on a project where accessibility to WCAG 2.0 and the ability to use the web application in the JAWS screenreader are key requirements. I'm looking for insights as to how JAWS treats Javascript, is it a complete no go or is JAWS smart enough to cope!?
jaws doesn't know about javascript, it just reads screen and makes some actions. It's just a plugin for browser. I was working on a project with similar requirements not so long ago. We've used YAML css framework which is designed for accessibility. And we've used only a few ajax and javascript improvements. And I hope that [this](http://v1.boxofchocolates.ca/archives/2005/06/12/javascript-and-accessibility) and [this](http://juicystudio.com/article/improving-ajax-applications-for-jaws-users.php) link will help you too.
I'm a jaws user and the short answer is it mostly works. With out knowing your exact requirements I can't be very specific. Apps like gmail in basic html view work perfectly, gmail in normal view works although I use the jaws cursor a lot to simulate a mouse, stackoverflow works fine, google spreadsheets is completely inaccessible, google docs is mostly inaccessible, and google reader works fine although I have to use the jaws cursor to click on options like expanded or list view.
JavaScript and Jaws Screenreader
[ "", "javascript", "asp.net", ".net", "accessibility", "jaws-screen-reader", "" ]
**The question** Is there a simple way to implement the login system that stackoverflow uses using php? For a long time I have developed websites, and have used a typical web form username/password with a mysql db for login systems. I would like to have it so users can log into the system using google, yahoo, facebook, etc, and without them having to remember some long openid url (they should just click google and be able to log in using their username/password there). I would prefer not to use a service provider (such as RPX) to implement this.
If you want to implement it yourself, [here](http://remysharp.com/2007/12/21/how-to-integrate-openid-as-your-login-system/) is a great walkthrough. There's also the [PHP OpenID Library](http://openidenabled.com/php-openid/), but that's probably a lot more than you need. [Here](http://code.google.com/p/openid-selector/) is the client-side OpenID selector that SO uses on its login screen. Edit: Stack Overflow no longer uses the one that I linked to, but it still works, as far as I'm aware.
Check which pages clicking those buttons sends you to and then just redirect your users to those pages. They are all "openid" providers so you just need an open id library on your end to verify the response. I use this one in PHP <http://openidenabled.com/php-openid/>. They have some good examples in that package to get you started.
Login system just like stackoverflow's, written in php
[ "", "php", "openid", "oauth", "" ]
I am planning to begin working on my first personal project this June: a community about students. What I want to have is a wiki, full with information about universities, a forum where people can discuss and a blog with news, articles, etc, all three of them integrated to eachother. Now, the way to go seems like wordpress+mediawiki+some forum software but I have been having these thoughts about giving it a try and writing my own CMS. I have some RoR and PHP knowledge but certainly not to the point where I can write my own CMS, especially entirely from scratch. How much time do you think it would take me to achieve it? I think/estimate I can spend 3 to 5 hours daily working on it and I want the whole site up and running by the end of August (which gives me about 300 hours of work, as I am also planning to spend some time just...doing nothing! :P). The question is, is it worth it? Is it going to help me improve my programming skills?
What you shall do is up to your own discretion, but what you *should* do is implement something like Drupal. Drupal is a CMS which is intended to be used for community sites. It's not the easiest system to understand and use, but it's very customizable. Here's some references that you could use to get started learning about Drupal: <http://www.packtpub.com/drupal/book> <http://drupal.org/node/367131> Whenever you have to choose between writing something for yourself and using existing software there are four key pieces of information you need to account for. 1. How Complex will it be? 2. How closely does an existing system match my needs? 3. What would it cost to implement an existing system Vs write your own 4. How soon do I need it? If it's not very complex, nothing else really matches your needs well, it would be cheap to create (in time and money) and you don't need it immediately then go ahead and do your own thing. Otherwise, jump on board one of the existing open source CMS's and start contributing there. Not only will you get great feedback from experienced programmers, but you'll be part of some really awesome software.
Judging from your goals it seems like it'd be easily accomplished in Drupal with minimal work. www.drupal.org Forums and user blogs are built in and I'm pretty sure I saw a wiki module somewhere. However, if you're going for a learning experience - doing it yourself will be quite the learning experience. Whether you actually accomplish it or not you will understand RoR and/or PHP better by the time you're done.
Should I write my own CMS?
[ "", "php", "ruby-on-rails", "wordpress", "content-management-system", "forum", "" ]
My class has an event which external objects will subscribe to: ``` public event EventHandler<MessageReceivedEventArgs> MessageReceived; ``` However, an internal Listener object, running on it's own thread, will actually be originating the event. ``` private class Listener { public void Run() { // events raised here which should be forwarded // to parent's MessageReceived } }; ``` My inclination is to create an event with the same signature on the Listener, and subscribe to it in the main class in order to raise it on MessageReceived. This seems a little cumbersome, so I was wondering if there is a neat/idiomatic way of forwarding events like this.
You can use event [add/remove accessors](http://msdn.microsoft.com/en-us/library/cc713648.aspx) so that events wired to the external-facing event are "forwarded" to the internal listener ``` public event EventHandler<MessageReceivedEventArgs> MessageReceived { add { this.listener.MessageRecieved += value; } remove { this.listener.MessageRecieved -= value; } } ``` This means you need to create an event in the listener, but the benefit is that there is no other plumbing to wire up the event.
You could do that with an event, or you could create a method in your main class called ReceiveMessage() and call that from the listener (and then raise the event from there).
Forwarding/relaying .NET events
[ "", "c#", ".net", "events", "" ]
Duplicate of: [How to ensure an event is only subscribed to once](https://stackoverflow.com/questions/367523/how-to-ensure-an-event-is-only-subscribed-to-once) and [Has an event handler already been added?](https://stackoverflow.com/questions/136975/has-an-event-handler-already-been-added) I have a singleton that provides some service and my classes hook into some events on it, sometimes a class is hooking twice to the event and then gets called twice. I'm looking for a classical way to prevent this from happening. somehow I need to check if I've already hooked to this event...
Explicitly implement the event and check the invocation list. You'll also need to check for null: ``` using System.Linq; // Required for the .Contains call below: ... private EventHandler foo; public event EventHandler Foo { add { if (foo == null || !foo.GetInvocationList().Contains(value)) { foo += value; } } remove { foo -= value; } } ``` Using the code above, if a caller subscribes to the event multiple times, it will simply be ignored.
How about just removing the event first with `-=` , if it is not found an exception is not thrown ``` /// -= Removes the event if it has been already added, this prevents multiple firing of the event ((System.Windows.Forms.WebBrowser)sender).Document.Click -= new System.Windows.Forms.HtmlElementEventHandler(testii); ((System.Windows.Forms.WebBrowser)sender).Document.Click += new System.Windows.Forms.HtmlElementEventHandler(testii); ```
C# pattern to prevent an event handler hooked twice
[ "", "c#", "event-handling", "delegates", "" ]
Is it possible to use shared object files in a portable way like DLLs in Windows?? I'm wondering if there is a way I could provide a compiled library, ready to use, for Linux. As the same way you can compile a DLL in Windows and it can be used on any other Windows (ok, not ANY other, but on most of them it can). Is that possible in Linux? **EDIT:** I've just woke up and read the answers. There are some very good ones. I'm not trying to hide the source code. I just want to provide an already-compiled-and-ready-to-use library, so users with no experience on compilation dont need to do it themselves. Hence the idea is to provide a .so file that works on as many different Linuxes as possible. The library is written in C++, using STL and Boost libraries.
I **highly** **highly** recommend using the LSB app / library checker. Its going to tell you quickly if you: * Are using extensions that aren't available on some distros * Introduce bash-isms in your install scripts * Use syscalls that aren't available in all recent kernels * Depend on non-standard libraries (it will tell you what distros lack them) * And lots, upon lots of other very good checks You can get [more information here](http://ldn.linuxfoundation.org/lsb/check-your-app) as well as download the tool. Its easy to run .. just untar it, run a perl script and point your browser at localhost .. the rest is browser driven. Using the tool, you can easily get your library / app LSB certified (for both versions) and make the distro packager's job much easier. Beyond that, just use something like libtool (or similar) to make sure your library is installed correctly, provide a static object for people who don't want to link against the DSO (it will take time for your library to appear in most distributions, so writing a portable program, I can't count on it being present) and comment your public interface well. For libraries, I find that [Doxygen](http://www.doxygen.nl/) works the best. Documentation is very important, it surely influences my choice of library to use for any given task. Really, again, check out the app checker, its going to give you portability problem reports that would take a year of having the library out in the wild to obtain otherwise. Finally, try to make your library easy to drop 'in tree', so I don't have to statically link against it. As I said, it could take a couple of years before it becomes common in most distributions. Its much easier for me to just grab your code, drop it in src/lib and use it, until and if your library is common. And please, please .. give me unit tests, [TAP](http://ccan.ozlabs.org/info/tap.html) (test anything protocol) is a good and portable way to do that. If I hack your library, I need to know (quickly) if I broke it, especially when modifying it in tree or *en situ* (if the DSO exists).
Ideally, you'll want to use GNU [autoconf](http://www.gnu.org/software/autoconf/), [automake](http://www.gnu.org/software/automake/), and [libtool](http://www.gnu.org/software/libtool/) to create configure and make scripts, then distribute the library as source with the generated configure and Makefile.in files. Here's an [online book](http://sources.redhat.com/autobook/) about them. `./configure; make; make install` is fairly standard in Linux. The root of the problem is that Linux runs on many different processors. You can't just rely on the processor supporting x86 instructions like Windows does (for most versions: Itanium (XP and newer) and Alpha (NT 4.0) are the exceptions).
Portable shared objects?
[ "", "c++", "linux", "portability", "shared-objects", "shared-libraries", "" ]
On the development shop I work for, we have an internal MAVEN repository, to keep our libraries (proprietary & open-souce). A common problem that we face is that, sometimes, the open-source libraries in our local MAVEN repository gets obsolete. Is there an automatic way to keep all the open-source libraries I use in my MAVEN repository always updated? What do you suggest to resolve this issue?
Assuming you: * Don't want to download everything * Don't want to run another server process * Only want to track a limited number of projects You might want to create a separate pom.xml file with dependencies like this: ``` <dependency> <groupId>org.openfoo</groupId> <artifactId>jfoo</artifactId> <version>[1.0.0,2.0.0)</version> </dependency> ``` This will tell maven to use jfoo 1.0.0 up to jfoo 2.0.0 so when jfoo releases version 1.2.17, you'll be fetching that in the next build assuming your settings are set to check versions each time. This pom doesn't have to actually build anything. Just list those things you want to track. Running: ``` cd the-path-to-the-project; mvn -q -B -U package ``` Via cron once a day will update all the dependencies in that pom and only report when there is a problem BTW, this is a hack. If the number of developers is > 3 and you have the resources to run nexus, don't bother with the hack.
Archiva has been mentioned, but [nexus](http://nexus.sonatype.org/) seems more popular. Both have been designed to solve problems like the one you're having
How to keep updated libraries in MAVEN?
[ "", "java", "configuration", "maven-2", "version-control", "" ]
Is it possible to prevent deletion of the first row in table on PostgreSQL side? I have a category table and I want to prevent deletion of default category as it could break the application. Of course I could easily do it in application code, but it would be a lot better to do it in database. I think it has something to do with rules on delete statement, but I couldn't find anything remotely close to my problem in documentation.
The best way I see to accomplish this is by creating a delete trigger on this table. Basically, you'll have to write a stored procedure to make sure that this 'default' category will always exist, and then enforce it using a trigger ON DELETE event on this table. A good way to do this is create a per-row trigger that will guarantee that on DELETE events the 'default' category row will never be deleted. Please check out PostgreSQL's documentation about triggers and stored procedures: <http://www.postgresql.org/docs/8.3/interactive/trigger-definition.html> <http://www.postgresql.org/docs/8.3/interactive/plpgsql.html> There's also valuable examples in this wiki: <http://wiki.postgresql.org/wiki/A_Brief_Real-world_Trigger_Example>
You were right about thinking of the rules system. [Here](http://wiki.postgresql.org/wiki/Introduction_to_PostgreSQL_Rules_-_Making_entries_which_can%27t_be_altered) is a link to an example matching your problem. It's even simpler than the triggers: ``` create rule protect_first_entry_update as on update to your_table where old.id = your_id do instead nothing; create rule protect_first_entry_delete as on delete to your_table where old.id = your_id do instead nothing; ``` Some answers miss one point: also the updating of the protected row has to be restricted. Otherwise one can first update the protected row such that it no longer fulfills the forbidden delete criterion, and then one can delete the updated row as it is no longer protected.
How to prevent deletion of the first row in table (PostgreSQL)?
[ "", "sql", "postgresql", "rules", "" ]
To squeeze into the limited amount of filesystem storage available in an embedded system I'm currently playing with, I would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance. The \*.py, \*.pyo, and \*.pyc files in the Python library account for a sizable amount of space, I'm wondering which of these options would be most reasonable for a Python 2.6 installation in a small embedded system: 1. Keep \*.py, eliminate \*.pyc and \*.pyo (Maintain ability to debug, performance suffers?) 2. Keep \*.py and \*.pyc, eliminate \*.pyo (Does optimization really buy anything?) 3. Keep \*.pyc, eliminate \*.pyo and \*.py (Will this work?) 4. Keep \*.py, \*.pyc, and \*.pyo (All are needed?)
<http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html> > When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. > > Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only **doc** strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. My suggestion to you? Use -OO to compile only **.pyo** files if you don't need assert statements and \_\_doc\_\_ strings. Otherwise, go with **.pyc** only. **Edit** I noticed that you only mentioned the Python library. Much of the python library can be removed if you only need part of the functionality. I also suggest that you take a look at [tinypy](http://www.tinypy.org/) which is large subset of Python in about 64kb.
Number 3 should and will work. You do not need the .pyo or .py files in order to use the compiled python code.
Python *.py, *.pyo, *.pyc: Which can be eliminated for an Embedded System?
[ "", "python", "embedded", "" ]
Suppose I want to implement an application container. Not a full-on Java EE stack, but I need to provide access to JDBC resources and transactions to third party code that will be deployed in an application I'm writing. Suppose, further, that I'm looking at JBossTS for transactions. I'm not settled on it, but it seems to be the best fit for what I need to do, as far as I can tell. How do I integrate support for *providing* connection resources and JTA transactions into my Java SE application?
I've elected to use the Bitronix Transaction Manager to solve this problem, although apparently there's at least one other option that wasn't apparent to me at the time (Atomikos). Solving this ended up requiring me to use the Tomcat in-process JNDI provider as well, in order to associate the transaction with a JNDI name. Due to a limitation of that provider, I could not use the default name for a JTA UserTransaction, which isn't immediately apparent from the documentation. Thanks to all for the helpful answers anyhow!
> How do I integrate support for > providing connection resources and JTA > transactions into my J2SE application? Hi Chris There are two elements to this problem: 1) Making the JTA API, mainly UserTransaction, available to application code, so it can start and end transactions. In A Java EE environment it’s published into a well known location in JNDI. If you have a JNDI implementation that’s the way to go (Use JBossTS’ JNDIManager class to help you with the setup). Otherwise, you need some kind of factory object or injection mechanism. Of course you can also expose the implementation class direct to the end user, but that’s somewhat nasty as it limits any chance of swapping out the JTA in the future. ``` public javax.transaction.UserTransaction getUserTransaction() { return new com.arjuna.ats.internal.jta.transaction.UserTransactionImple(); } ``` That’s it – you can now begin, commit and rollback transactions. Some containers also publish the TransactionManager class to applications in similar fashion, but it’s really designed for use by the container itself and rarely needed by the application code. 2) Managing enlistment of XAResources automatically. Resource managers i.e. databases and message queues, have drivers that implement XAResource. Each time the application gets a connection to the resource manager, a corresponding XAResource needs to be handed off to the JTA implementation so it can drive the resource manager as part of the 2PC. Most app servers come with a JCA that handles this automatically. In environments without one, you need some alternative to save the application code from having to do this tedious task by hand. The TransactionalDriver bundled with JBossTS handles this for JDBC connections. XAPool may also be worth considering. JBossTS has been embedded in many environments over the years. Some of the lessons learned are documented in the Integration Guide <http://anonsvn.jboss.org/repos/labs/labs/jbosstm/trunk/atsintegration/docs/> ] and if you want a worked example you could look at the tomcat integration work <http://anonsvn.jboss.org/repos/labs/labs/jbosstm/workspace/jhalliday/tomcat-integration/> ] > JBoss's TM is horrible. At least, if > you are hoping for ACID transactions. Hi erickson I don’t think I’d go quite as far as ‘horrible’. It’s incredibly powerful and highly configurable, which can make the out of box experience a bit daunting for newcomers. Correct recovery configuration is particularly tricky, so I fully endorse your comment about rigorous testing. Beyond that I’m not aware of any documented test cases in which it currently fails to provide ACID outcomes when used with spec compliant resource managers. If you have such as case, or just more constructive suggestions for improvement, please let JBoss know so the issue can be addressed. > Don't reinvent the wheel. Use the > Spring Framework. It already provides > this functionality and much more. -1 Spring does not provide a JTA implementation, just a wrapper for various 3rd party ones. This is a common misunderstanding. > JTA supports local transactions and > global transactions. Another misconception I’m afraid. The JTA spec deals only with XA i.e. global transactions. Various well known techniques exist for making a JTA transaction manager drive local transactions. These usually involve wrapping the Connection in an XAResource. Whilst most implementations support this it’s actually outside the scope of the spec and so you must check with the vendor before choosing a JTA implementation if you need this behaviour.
What do I need to do to integrate JTA into a Java SE application?
[ "", "jndi", "jta", "java", "" ]
I store events in SQLServer 2005 where the time the event occured is important and must be stored in the datebase. What is the fastest way to write the date range check in the where clause to ensure everything on that day is selected? Currently when @DateStart and @DateEnd are passed in I set @DateStart to midnight and set @DateEnd to the last instant before midnight as the very first thing to catch every possible event on the day. ``` IF (@DateStart IS NOT NULL) BEGIN SET @DateStart = CAST ( ( CAST (DATEPART (yyyy,@DateStart) AS NVARCHAR(4)) +'/'+ CAST (DATEPART (mm,@DateStart) AS NVARCHAR(2)) +'/'+ CAST (DATEPART (dd,@DateStart) AS NVARCHAR(2)) +' '+ '00:00:00.000' ) AS DATETIME) END IF (@DateEnd IS NOT NULL) BEGIN SET @DateEnd = CAST ( ( CAST (DATEPART (yyyy,@DateEnd) AS NVARCHAR(4)) +'/'+ CAST (DATEPART (mm,@DateEnd) AS NVARCHAR(2)) +'/'+ CAST (DATEPART (dd,@DateEnd) AS NVARCHAR(2)) +' '+ '23:59:59.997' ) AS DATETIME ) END ``` So the where clause is very easy to read: WHERE ( EventDate >= @DateStart AND EventDate <= @DateEnd ) Thanks,
You could always use the alternate syntax of `WHERE EventDate BETWEEN @DateStart AND @DateEnd`
Your where clause would look like; ``` WHERE DateCol >= DATEADD(dd, DATEDIFF(dd, 0, @DateStart), 0) --Midnight on the Start date AND DateCol < DATEADD(dd, DATEDIFF(dd, 0, @DateEnd + 1), 0) --Midnight of the day after End date ``` and all your IF statement would do is handle null parameters (i.e. IF @DateEnd IS NULL THEN SET @DateEnd = @DateStart) You probably want to Index on DATEADD(dd, DATEDIFF(dd, 0, DateCol), 0) if your table is large.
Fastest way to check date range
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I am developing a GUI based application in MS Visual Studio 2005, I just want to know if it is possible to use both VB.NET and C# in the same project. Or can I include a module written in C# in my VB.NET project? I have a class written in C# which I want to use in my VB.NET based project, so if I can include and call functions from that project than I won't have to write the class again in VB.NET. So please help me as I am new to .NET programming.
I've never done it myself, but I know you can compile the C# code into a dll and then load and reference the dll in your VB project. From ["Calling C# class in VB.net"](http://forums.devx.com/archive/index.php/t-98484.html): > I think the C# code that you want to > use must be compiled as a DLL. Once > that is done, simple add a reference > to that project to your VB.Net > project, import the namespace you > need, and then you can use the C# > code. Also see [How To: Create and Use C# DLLs](http://msdn.microsoft.com/en-us/library/3707x96z(VS.80).aspx) (from MSDN, for VS2005)
> I just want to know that is it possible to use both VB and C# in the same project. No, not in the same *project*. On the other hand, you can use them in the same *solution*. > Or can i include a module written in C# in my VB.net project. I propose that you create a solution containing two projects: one in C# which forms a library that you use from your VB project. This is straightforward, easy to maintain and easy to extend.
Use VB.NET and C# in the same application?
[ "", "c#", "vb.net", "visual-studio-2005", "" ]
I was wondering: is there a way to create HTML files programmatically in C# as you can do with XML? Mine is a console application, so maybe some of the options are not available. Basically, I would like to do something smarter than just building a big string. Possible scenario: Instead of writing: ``` string html="<html><head>Blah</head><body>{0}</html>", myotherstring ``` I would like to work as in XML ``` XmlTextWriter w = new XmlTextWriter(xml_file_path + xml_file_name, System.Text.Encoding.UTF8); w.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); // construct xml XmlElement root = xmlDoc.CreateElement("element"); ... xmlDoc.Save(w); w.Close(); ``` Apologies for the naive question.
You could use NVelocity. It is a .Net port of the Java Velocity templating system. The API will not be similar to XmlWriter. Instead, you'll write a text file in a simple scripting language, put your objects into a 'context' and then merge the template and the context to generate the HTML file. [NVelocity](https://github.com/castleproject/NVelocity)
Don't forget: You can generate XHTML just as easily as plain XML using the XmlTextWriter approach.
Create HTML webpage programmatically in C#
[ "", "c#", "html", "" ]
How can I check a word template file. It can be checked using the extension .dot or .dotx. But if the user changed a .txt to .dot. How could it identified??
To check for a dotx file (which is actually a zip file), check the header: ``` 0000000: 504b 0304 1400 0000 0800 95a1 3435 4a07 PK..........45J. ``` First four bytes are 0x050 0x4b 0x03 0x04. This will demonstrate if a file is a zip file (so not necessarily a dotx), if you wanted to checked further your would need to unzip the entire buffer and parse the resulting XML. To check for a dot file (pre 2007), check the header: ``` 0000000: d0cf 11e0 a1b1 1ae1 0000 0000 0000 0000 ................ ``` First eight bytes 0xd0 0xcf 0x11 0xe0 0xa1 0xb1 0x1a 0xe1 So for either of these cases, open the file in binary mode, read the first eight bytes and compare.
According to <http://www.garykessler.net/library/file_sigs.html>, the full signature of a dot file (among others) is: D0 CF 11 E0 A1 B1 1A E1 So, below is some code to start with. It works for .dot, but if you want to check .dotx, you can implement similar code. This does not absolutely guarantee it's a valid dot, so you still need to handle errors reasonably later. ``` // Use this as a class field. private static readonly byte[] DOT_SIGNATURE = new byte[]{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}; ``` Later, when you actually have the Stream: ``` bool isDot = true; Stream dotStream = ... byte[] firstBytes = new byte[DOT_SIGNATURE.Length]; int totalRead = 0, curRead; while(totalRead < DOT_SIGNATURE.Length) { curRead = dotStream.Read(firstBytes, totalRead, DOT_SIGNATURE.Length - totalRead); if(curRead == 0) { isDot = false; break; // Premature end of stream; } totalRead += curRead; } if(isDot) { for(int i = 0; isDot && i < DOT_SIGNATURE.Length; i++) { // If isDot becomes false, arrays are not equal and we break out. isDot = (firstBytes[i] == DOT_SIGNATURE[i]); } } dotStream.Seek(0, SeekOrigin.Begin); ```
Check word template file
[ "", "c#", ".net", "ms-word", "" ]
When compiling, I always set it for Any CPU. However there are some customers that do not have a 64 bit version of a required binary, even when running on an x64 system. In these instances I have asked them to modify my binary with the corflags.exe /32BIT+ option: <http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx> I would like to make this transparent and modify the binary myself during installation time if the 64 bit version is not present. I would **prefer** not to make a call to corflags.exe myself as that would mean I would need to redistribute the application which is not allowed as part of our shipping requirements. So my question is; is there any way to modify this flag programatically myself, or alternatively to modify the binary directly (is it just setting a byte somewhere in the file itself)?
Why not just build your assemblies for both architectures (32-bit and 64-bit) specifically, include both in your installer, and then at install time, detect which version of this dependent assembly your client has and then install the appropriate architecture version of your application. This way there's no messing around modifying binaries manually or needing to include corflags in your installer.
I have not tried this however are you able to run corflags on a copy of the binary and do a binary diff to determine what offset was modified. You could do this as a build action of your install script and store the offset with the installer. At install time just alter the offset that if needed. Of course I would never endorse such actions, just sayin' ;-) As an aside, if you are continually needing to mark the assembly for 32bit you may consider just targeting that platform instead of altering it as 32bit after the fact. Cheers.
How to programatically set or clear the 32BIT flag?
[ "", "c#", ".net", "runtime", "corflags", "" ]
I recently saw a [reference to "exotic signatures"](http://pypi.python.org/pypi/decorator/) and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is ``` def exotic_signature((x, y)=(1,2)): return x+y ``` What makes this an "exotic" signature?
What's exotic is that x and y represent a single function argument that is unpacked into two values... x and y. It's equivalent to: ``` def func(n): x, y = n ... ``` Both functions require a single argument (list or tuple) that contains two elements.
More information about tuple parameter unpacking (and why it is removed) here: <http://www.python.org/dev/peps/pep-3113/>
What is an exotic function signature in Python?
[ "", "python", "" ]
This (shortened) code.. ``` for (int i = 0; i < count; i++) { object obj = propertyInfo.GetValue(Tcurrent, new object[] { i }); } ``` .. is throwing a 'TargetParameterCountException : Parameter count mismatch' exception. The underlying type of 'propertyInfo' is a Collection of some T. 'count' is the number of items in the collection. I need to iterate through the collection and perform an operation on obj. Advice appreciated.
Reflection only works on one level at a time. You're trying to index into the property, that's wrong. Instead, read the value of the property, and the object you get back, that's the object you need to index into. Here's an example: ``` using System; using System.Collections.Generic; using System.Reflection; namespace DemoApp { public class TestClass { public List<Int32> Values { get; private set; } public TestClass() { Values = new List<Int32>(); Values.Add(10); } } class Program { static void Main() { TestClass tc = new TestClass(); PropertyInfo pi1 = tc.GetType().GetProperty("Values"); Object collection = pi1.GetValue(tc, null); // note that there's no checking here that the object really // is a collection and thus really has the attribute String indexerName = ((DefaultMemberAttribute)collection.GetType() .GetCustomAttributes(typeof(DefaultMemberAttribute), true)[0]).MemberName; PropertyInfo pi2 = collection.GetType().GetProperty(indexerName); Object value = pi2.GetValue(collection, new Object[] { 0 }); Console.Out.WriteLine("tc.Values[0]: " + value); Console.In.ReadLine(); } } } ```
I was most of the way there until I saw this, and I am posting this because I didn't see it anywhere else; the key was using GetValue(collection, new Object[] { i }); in the loop rather than trying to use GetValue(collection, new Object[i]); outside the loop. (You can probably ignore the "output" in my example); ``` private static string Recursive(object o) { string output=""; Type t = o.GetType(); if (t.GetProperty("Item") != null) { System.Reflection.PropertyInfo p = t.GetProperty("Item"); int count = -1; if (t.GetProperty("Count") != null && t.GetProperty("Count").PropertyType == typeof(System.Int32)) { count = (int)t.GetProperty("Count").GetValue(o, null); } if (count > 0) { object[] index = new object[count]; for (int i = 0; i < count; i++) { object val = p.GetValue(o, new object[] { i }); output += RecursiveWorker(val, p, t); } } } return output; } ```
PropertyInfo.GetValue() - how do you index into a generic parameter using reflection in C#?
[ "", "c#", "generics", "reflection", "" ]
I'd like to adhere to the Don't-Repeat-Yourself principle, but sometimes when I write PHP together with HTML and CSS, if I re-use the same code for different situations, my code soon will have so many if-then-else that the code is not easily maintainable. This may be a bigger issue if Smarty, the templating engine is used, because most code editor won't match up {if} {else} {/if} So the programmer needs to look for the matching tag visually, and is not easy when there are 3 or 4 levels of nested {if} {else} {/if}. In such situation, is there a way to stick to DRY, but still have good maintainable code?
Short of a full framework, what I tend to do for content (even if it contains logic) is **separate it out** into files and use another logical evaluation to merge them together (mangle them) and then evaluate the templating logic after that. This chunkifies your content and makes chunks sharable / reusable on common state. This way each final template buffer is a flattened tree of discrete re-usable content nuggets that you can store on disk or a database. Even something as simple as a little parser that replaces: ``` <h1>{{insert:shared_page_header}}</h1> ``` With `shared_page_header.txt` helps keep things separate. It also forces you to look at separation on concerns even in the logic that is embedded in your templates. **Manageable, reusable chunks of anything (dynamic or not)** are always the way to go. Your templates are just strings until evaluated, so treat them as **shared components merged** into a big-dirty-string(TM) and then evaluated. **Good Luck**
Just so we have more info... What program are you using to write your code? Tips for not repeating yourself: **Use some sort of templates.** Doing this keeps you from having to repeat code for displaying content in each of your pages. I.E. If you have a site with 20 pages and you decide to change your layout, you don't want to have to go through and then change all 20 of your pages. **Use functions.** If you have code that performs a specific task, DON'T write that code multiple times throughout your program/page. Create a function and then call it in each spot where you need that task performed. That way if you need to make a change you just modify that one function and don't have to search through your code to find every place that you performed that task. If you know about classes & methods (a method is a function in a class), for many tasks, this is even better as it provides you with data encapsulation and allows you to group related functions together so that you can include the class in future projects as needed. If you are having difficulty with lots of if/else statements and code not being very readable there are a few things you can do: **1. Consider trying a new editor.** Code folding is a must. Some editors also have vertical lines that highlight and match up indented code so you know what goes with what. If you want a decent free editor, I would recommend Notepad++ as it has both these features (just google it, I can't add links here). **2. There are techniques you can use to reduce the number of nested if statements that you have...** Example (this code): ``` if (item1 == true) { if (item2 == true) { item3 = 5; } else { item3 = 10; } } else { if (item2 == true) { item3 = 15; } else { item3 = 20; } } ``` Can also be flattened out into: ``` if (item1 == true && item2 == true) { item3 = 5; } else if (item1 == true && item2 == false) { item3 = 10; } else if (item1 == false && item2 == true) { item3 = 15; } else { item3 = 20; } ``` So if you have 3 or 4 levels of nested if/elses and you want to flatten them out, you may find your code more readable to use multiple arguments such as above. It does the same thing, it's just a matter of preference for which way you do it. **Try and not mix your logic (I'm assuming PHP) and your display (I'm assuming HTML/CSS).** This is not always easy to do, but using templates and css, it is possible. Let me give you a practical example of how you can do this on a home page that displays a users name as a welcome message. Inline PHP (try to avoid): ``` <html> <body> <?php if ($logged_in == true) { echo "Welcome ",$user->name(),"!"; } else { echo "Welcome Guest!"; } ?> </body> </html> ``` Logic separate from display (better): ``` <?php if ($logged_in == true) { $greetingMessage = "Welcome ",$user->name(),"!"; } else { $greetingMessage = "Welcome Guest!"; } ?> <html> <body> <?php echo $greetingMessage; ?> </body> </html> ``` ^ Keeping your logic separate from your view (HTML) will help you not get overwhelmed when your project starts getting really complex. It's best just not to mix! :) Good luck man!
how to adhere to the Don't-Repeat-Yourself (DRY) principle when there will be too many if-then-else making the code unreadable?
[ "", "php", "dry", "code-reuse", "maintainability", "" ]
How do I allow my `CookieData` to be generic in the following code? I get an compile-time error on the declaration of `ICookieService2`. ``` public struct CookieData<T> { T Value { get; set; } DateTime Expires { get; set; } } public interface ICookieService2: IDictionary<string, CookieData<T>> { // ... } ``` My error is: > The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) I am wanting `ICookieService2` to have generic data inserted into it. Thanks! **Edit** Won't that lock me into a single `T` for the construction of any `ICookieService2`? **Edit 2** What I am trying to do is the following: ``` CookieData<int> intCookie = { Value = 27, Expires = DateTime.Now }; CookieData<string> stringCookie = { Value = "Bob", Expires = DateTime.Now }; CookieService2 cs = new CookieService2(); cs.Add(intCookie); cs.Add(stringCookie); ```
It looks like you have 3 options here Make ICookieService2 generic ``` public interface ICookieService2<T> : IDictionary<string, CookieData<T> { ... } ``` Create a non-generic base class for CookieData and use that in the interface ``` public interface ICookieData {} public class CookieData<T>: ICookieData{} public interface ICookieService2 : IDictionary<string, ICookieData> {} ``` Pick a concrete implementation ``` public interface ICookieService : IDictionary<string, CookieData<int>> {} ```
You must make ICookieService2 generic as well: ``` public interface ICookieService2<T>: IDictionary<string, CookieData<T>> { // ... } ```
Using Generics in Interfaces
[ "", "c#", "generics", "collections", "interface", "" ]
I have a Symbol LS2208 barcode scanner and works OK in my linux box (Kubuntu 8.10 Intrepid Ibex). Whenever you scan a barcode the scanner (connected to an USB port) sends the reading to wherever the text caret is. I would like to redirect all the readings from the scanner to an specific widget in my application (i.e. a text edit control). How can I do it? Though I use C++ with Qt GUI library sample code is welcome in any language or GUI library.
I don't know the answer, but here are some suggestions to find out what your options are: 1. Install an event filter on QCoreApplication::instance() (or reimplement QCoreApplication::notify()) 2. In event filter handler, output each event looking for anything useful: ``` void eventFilter(QObject *obj, QEvent *evt) { qDebug() << obj << evt; } ``` 3. Examine the debug output to determine which events are triggered by the scanner. qDebug() understands virtually every type and should give you reasonable output that will allow you to tell whether the it's coming in as keyboard events or something else.
That may be tricky in that most barcode scanners are also known as keyboard wedges. They function as a keyboard and shove keys into the event stream so as to be as indistinguishable from a keyboard as possible. This makes for the greatest compatibility. Many USB barcode scanners publish themselves as a HID endpoint and then for all intents and purposes, they ARE keyboards. There are a number of things you can try to do - many scanners are configurable to allow them to spew in a prefix and suffix around the barcode data. If you can test for that, you just send the string to the right place. This is unpalatable in that you have to metaprogram the scanner. Usually this is done with a special set of barcodes. [Here is a link to the manual](http://www.modul-bio.com/media/Symbol_LS2208_Manual.pdf) for your scanner. On page 249, there are barcodes for metaprogramming the prefix and suffix. You might want to figure out how to be a client for the HID events and redirect the scanner events where you want them. I've never tried to do this on LINUX. It's a pain on both Windows and OS 9 era Mac (the last time I played with USB extensively).
Redirect barcode scanner input to specific widget in linux
[ "", "c++", "linux", "qt", "usb", "barcode", "" ]
I love C#, I love the framework, and I also love to learn as much as possible. Today I began to read articles about LINQ in C# and I couldn't find anything good for a beginner that never worked with SQL in his life. I found [this](http://www.programmersheaven.com/2/CSharp3-4) article very helpful and I understood small parts of it, but I'd like to get more examples. After reading it couple of times, I tried to use LINQ in a function of mine, but I failed. ``` private void Filter(string filename) { using (TextWriter writer = File.CreateText(Application.StartupPath + "\\temp\\test.txt")) { using(TextReader reader = File.OpenText(filename)) { string line; while((line = reader.ReadLine()) != null) { string[] items = line.Split('\t'); int myInteger = int.Parse(items[1]); if (myInteger == 24809) writer.WriteLine(line); } } } } ``` This is what I did and it did not work, the result was always false. ``` private void Filter(string filename) { using (TextWriter writer = File.CreateText(Application.StartupPath + "\\temp\\test.txt")) { using(TextReader reader = File.OpenText(filename)) { string line; while((line = reader.ReadLine()) != null) { string[] items = line.Split('\t'); var Linqi = from item in items where int.Parse(items[1]) == 24809 select true; if (Linqi == true) writer.WriteLine(line); } } } } ``` I'm asking for two things: 1. How would the function look like using as much Linq as possible? 2. A website/book/article about Linq,but please note I'm a decent beginner in sql/linq. Thank you in advance!
Well one thing that would make your sample more "LINQy" is an `IEnumerable<string>` for reading lines from a file. Here's a somewhat simplified version of my `LineReader` class from [MiscUtil](http://pobox.com/~skeet/csharp/miscutil): ``` using System; using System.Collections; using System.Collections.Generic; using System.IO; public sealed class LineReader : IEnumerable<string> { readonly Func<TextReader> dataSource; public LineReader(string filename) : this(() => File.OpenText(filename)) { } public LineReader(Func<TextReader> dataSource) { this.dataSource = dataSource; } public IEnumerator<string> GetEnumerator() { using (TextReader reader = dataSource()) { string line; while ((line = reader.ReadLine()) != null) { yield return line; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } ``` Now you can use that: ``` var query = from line in new LineReader(filename) let items = line.Split('\t') let myInteger int.Parse(items[1]); where myInteger == 24809 select line; using (TextWriter writer = File.CreateText(Application.StartupPath + "\\temp\\test.txt")) { foreach (string line in query) { writer.WriteLine(line); } } ``` Note that it would probably be more efficient to not have the `let` clauses: ``` var query = from line in new LineReader(filename) where int.Parse(line.Split('\t')[1]) == 24809 select line; ``` at which point you could reasonably do it all in "dot notation": ``` var query = new LineReader(filename) .Where(line => int.Parse(line.Split('\t')[1]) == 24809); ``` However, I far prefer the readability of the original query :)
[101 LINQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx) is certainly a good collection of examples. Also [LINQPad](http://www.linqpad.net/) might be a good way to play around with LINQ.
LINQ for beginners
[ "", "c#", "linq", "" ]
What would be the best way to implement a customizable tree data structure (meaning, a tree structure with an unknown number of level) in a database? I've done this once before using a table with a foreign key to itself. What other implementations could you see, and does this implementation make sense?
You mention the most commonly implemented, which is Adjacency List: <https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets> There are other models as well, including materialized path and nested sets: <http://communities.bmc.com/communities/docs/DOC-9902> Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above). Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying". The main things to consider when choosing a model are: 1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left. 2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure. 3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.
Have a look at [Managing Hierarchical Data in MySQL](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/). It discusses two approaches for storing and managing hierarchical (tree-like) data in a relational database. The first approach is the adjacency list model, which is what you essentially describe: having a foreign key that refers to the table itself. While this approach is simple, it can be very inefficient for certain queries, like building the whole tree. The second approach discussed in the article is the nested set model. This approach is far more efficient and flexible. Refer to the article for detailed explanation and example queries.
Database Structure for Tree Data Structure
[ "", "sql", "database-design", "tree", "" ]
I'd like to create a simple singleton commandline application (a service?) in C# that when it was run, it checked to see if it was already running, and if so, it passed the command-line args to the already running instance and closed itself. Now in the already running instance it would receive the command-line args through an event like "delegate void Command(string[] args);" or something like that, so I can manage command-line through one application via events. For instance in photoshop, when you open a picture for the first time, it loads a new instance photoshop, but when you open a second picture, it checks to see if an instance of photoshop is already running, and if it is, it passes the picture to the already loaded instance of photoshop so it can avoid the costly load-time of photoshop all over again... Or in the web browser, you can set it so if you open a new .html file, it opens it up in a new tab, not a new window instance. or many text editors have settings to only allow one instance of the text editor open and when a new file is opened, it's loaded in a new tab, not a new window... many music players like winamp do this too... I am going to eventually be setting this up as a service, so it should be constantly listening for command-line args later, but for now it's mostly so that I can manage the opening of files of a specific type together in one singleton application, or have other applications pass command-line arguments of files they want to be opened... Also, if you know a better way or an api in .Net to re-rout all command-line args passed, to an event of a service that is always running, I can work with that... but I'd also like to keep this cross-platform so it can run in Linux/Mac on Mono if that's possible, without having to manage two or more code-bases...
This is the article i used to implement the exact functionality that you are looking for, it allows you to transfer command line arguments as well. [Single-Instance C# Application - for .NET 2.0](http://www.codeproject.com/KB/cs/CSSIApp.aspx)
We did something simillar using although for a very different purpose using .net remoting on 1.0 / 1.1 framework. Basically we'd use a semaphore to ensure we were the only running instance. You'll want to target the global namespace, if you want to have only one instance per machine or the local if you want one per user session (In terminal service and fast user switching scenarios). If you can lock the semphore, you will setup remoting and start listening for events, and then continue on with your code. if you can't lock then you can asssume you have another running instance in which case you'll open up a remoting channel to the other instance pass the args and shutdown.
.Net/Mono Singleton (Service/Server?) in C# - detect if my .net app is already running and pass command-line args to it
[ "", "c#", ".net", "mono", "" ]
easy\_install python extension allows to install python eggs from console like: ``` easy_install py2app ``` But is it possible to access easy\_install functionality inside a python script? I means, without calling os.system( "easy\_install py2app" ) but instead importing easy\_install as a python module and using it's native methods?
When I look at the setup tools source, it looks like you can try the following. ``` from setuptools.command import easy_install easy_install.main( ["-U","py2app"] ) ```
``` from setuptools.command import easy_install def install_with_easyinstall(package): easy_install.main(["-U", package]). install_with_easyinstall('py2app') ```
Using easy_install inside a python script?
[ "", "python", "setuptools", "" ]
I have a WPF ListBox that typically shows 4 or 5 items. For my application that means I almost never have to display a scrollbar (there is enough space). However, in case there are more items in the list, I need to show the vertical scroll bar, but as a result my content has less space and doesn't look nice anymore on a "backdrop" I've created behind the listbox. I like to "reserve" room in my layout for the scrollbar to appear. Is there a way to do that? (maybe having the scrollbar overlayed on the content)
Alright, found a solution. I've created a new default style for the ScrollViewer by following [this MSDN article](http://msdn.microsoft.com/en-us/library/ms771748.aspx). Then I've changed the part where the scrollbars are placed. *Original behaviour* ``` <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Border Grid.Row="0" Grid.Column="1"> <ScrollContentPresenter CanContentScroll="True" Content="{TemplateBinding ScrollViewer.Content}" /> </Border> <ScrollBar Orientation="Vertical" Grid.Row="0" Grid.Column="0" Minimum="0" Maximum="{TemplateBinding ScrollViewer.ScrollableHeight}" Value="{TemplateBinding ScrollViewer.VerticalOffset}" ViewportSize="{TemplateBinding ScrollViewer.ViewportHeight}" Name="PART_VerticalScrollBar" Visibility="{TemplateBinding ScrollViewer.ComputedVerticalScrollBarVisibility}" /> <ScrollBar Orientation="Horizontal" Grid.Row="1" Grid.Column="1" Minimum="0" Maximum="{TemplateBinding ScrollViewer.ScrollableWidth}" Value="{TemplateBinding ScrollViewer.HorizontalOffset}" ViewportSize="{TemplateBinding ScrollViewer.ViewportWidth}" Name="PART_HorizontalScrollBar" Visibility="{TemplateBinding ScrollViewer.ComputedHorizontalScrollBarVisibility}"/> </Grid> ``` *New behaviour* ``` <Grid> <!-- Presentation below is different from the default: the scrollbar is overlayed on the content. --> <ScrollContentPresenter CanContentScroll="True" Content="{TemplateBinding ScrollViewer.Content}" /> <ScrollBar Orientation="Vertical" HorizontalAlignment="Right" Minimum="0" Maximum="{TemplateBinding ScrollViewer.ScrollableHeight}" Value="{TemplateBinding ScrollViewer.VerticalOffset}" ViewportSize="{TemplateBinding ScrollViewer.ViewportHeight}" Name="PART_VerticalScrollBar" Visibility="{TemplateBinding ScrollViewer.ComputedVerticalScrollBarVisibility}" /> <ScrollBar Orientation="Horizontal" VerticalAlignment="Bottom" Minimum="0" Maximum="{TemplateBinding ScrollViewer.ScrollableWidth}" Value="{TemplateBinding ScrollViewer.HorizontalOffset}" ViewportSize="{TemplateBinding ScrollViewer.ViewportWidth}" Name="PART_HorizontalScrollBar" Visibility="{TemplateBinding ScrollViewer.ComputedHorizontalScrollBarVisibility}"/> </Grid> ``` Now the scrollbars are overlayed on the content so they don't take additional space when visible. Of course the content should now reserve space for the content.
What about wrapping it with a ScrollViewr? ``` <ScrollViewer VerticalScrollBarVisibility="Auto"> <!-- your ListBoxHere --> </ScrollViewer> ```
ListView scrollbar messes up my layout
[ "", "c#", ".net", "wpf", "xaml", "" ]