Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is it possible to embed a windows form within another windows form? I have created a windows form in Visual Studio along with all its associated behaviour. I now want to create another windows form containing a tab view, and I want to embed the first windows form into the tab view. Is this possible?
Not directly. You can create a usercontrol, move all of the code from your form to the usercontrol and use this in both forms. You might need to change some of the code from your form but probably not much.
## Disclaimer This will work as I am using it in my application extensively. That being said I would pursue the User Control route as depending on how *far* you carry the embedding things start to *flake out*. FYI --- Yes this is possible. This is how: ``` public static void ShowFormInContainerControl(Control ctl, ...
Embedding a winform within a winform (c#)
[ "", "c#", "winforms", "" ]
I want to create a delegate type in C# inside a method for the purpose of creating Anonymous methods. For example: ``` public void MyMethod(){ delegate int Sum(int a, int b); Sum mySumImplementation=delegate (int a, int b) {return a+b;} Console.WriteLine(mySumImplementation(1,1).ToString()); } ``` Unfortu...
Why do you want to create the delegate type within the method? What's wrong with declaring it outside the method? Basically, you can't do this - you can't declare a *type* (any kind of type) within a method. One alternative would be to declare all the Func/Action generic delegates which are present in .NET 3.5 - then ...
The delegate *type* has to be defined outside the function. The actual delegate can be created inside the method as you do. ``` class MyClass { delegate int Sum(int a, int b); public void MyMethod(){ Sum mySumImplementation=delegate (int a, int b) {return a+b;} Console.WriteLine(mySumImplementation...
Creating a delegate type inside a method
[ "", "c#", ".net-2.0", "delegates", "" ]
**Dup of [Some Basic PHP Questions](https://stackoverflow.com/questions/330709/some-basic-php-questions#330829)** Hello, I have a heap of tinyint fields in a mysql database I need to show with PHP. At the moment I am doing something like this: ``` if ($row['PAYPAL_ACCEPT'] == "1"){ $paypal = "Yes"; else $paypal =...
Building on what's already been suggested: ``` // $columns = string array of column names // $columns = array('PAYPAL_ACCEPT' ... ); foreach($columns as $column) { $$column = $row[$column] ? 'YES' : 'NO'; } ``` then you can access variables using the column names as variable names: ``` print $PAYPAL_ACCEPT; ```
Try if you want: ``` $paypal = $row['PAYPAL_ACCEPT'] ? 'YES' : 'NO'; ```
booleans with PHP
[ "", "php", "" ]
Is there any code coverage tool available for PHP? I wish to check the code coverage of my code and API's written in PHP, but have not been able to lay my hands on any code coverage tool for PHP, as it is more of a server side language and dynamic in nature. Does anyone know of a method by which code coverage for PHP ...
[xdebug](http://www.xdebug.org/) has [Code Coverage Analysis](http://www.xdebug.org/docs/code_coverage). Check [this chapter](https://phpunit.de/manual/current/en/code-coverage-analysis.html) of the PHPUnit Manual
See our PHP Test Coverage tool from Semantic Designs: <http://www.semanticdesigns.com/Products/TestCoverage/PHPTestCoverage.html> Very low overhead, handles huge systems of files, intuitive GUI showing coverage on specific files, and generated report with coverage breakdown at method, class and package levels. Best ...
Code Coverage tools for PHP
[ "", "php", "code-coverage", "" ]
For a web application, I would like to create a simple but effective licensing system. In C#, this is a little difficult, since my decryption method could be viewed by anyone with Reflector installed. What are some methods for encrypting files in C# that are fairly tamper-proof?
It sounds like you want to be using Public/Private cryptography to sign a license token (an XML Fragment or file for example) so you can detect tampering. The simplest way to handle it is to do the following steps: 1) Generate a keypair for your company. You can do this in the Visual Studio command line using the SN t...
Use a signed XML file. Sign it with the private key part of a keypair and check it with the public key part in your software. This gives you the oppertunity to check whether the license has been altered and also to check if the license file is valid. Signing and checking of a signed XML file is documented in the MSDN....
An effective method for encrypting a license file?
[ "", "c#", "encryption", "cryptography", "" ]
I would like to execute multiple commands in a row: i.e. (just to illustrate my need): `cmd` (the shell) then `cd dir` and `ls` and read the result of the `ls`. Any idea with `subprocess` module? **Update:** `cd dir` and `ls` are just an example. I need to run complex commands (following a particular order, w...
There is an easy way to execute a sequence of commands. Use the following in `subprocess.Popen` ``` "command1; command2; command3" ``` Or, if you're stuck with windows, you have several choices. * Create a temporary ".BAT" file, and provide this to `subprocess.Popen` * Create a sequence of commands with "\n" separa...
To do that, you would have to: * supply the `shell=True` argument in the `subprocess.Popen` call, and * separate the commands with: + `;` if running under a \*nix shell (bash, ash, sh, ksh, csh, tcsh, zsh etc) + `&` if running under the `cmd.exe` of Windows
Execute Commands Sequentially in Python?
[ "", "python", "windows", "subprocess", "" ]
I feel like this is a stupid question because it seems like common sense . . . but no google search I can put together seems to be able to give me the answer! I know how to get data OUT of a sqlite3 database using the .dump command. But now that I have this ASCII file titled export.sqlite3.sql . . . I can't seem to ge...
``` cat dumpfile.sql | sqlite3 my_database.sqlite ``` [This is modified from the sqlite3 getting started guide.](http://www.sqlite.org/sqlite.html)
You didn't specify your operating system and while ``` sqlite3 my_database.sqlite < export.sqlite3.sql ``` will work for the unix flavors, it will not work for windows. The inverse of the .dump command is the .read command. The syntax would be ``` sqlite3> .read export.sqlite3.sql ```
Importing a SQLite3 dump back into the database
[ "", "sql", "database", "sqlite", "import", "" ]
In my web app, when a user logs in, I add his Id to a vector of valid Ids in the servlet, when he logs out, I remove his Id from the vector, so I can see how many current users are active, if a user forgets to log out, my servelt generated html has : ``` <meta http-equiv="Refresh" content="30; url=My_Servlet?User_Acti...
There is no way to know on the server-side (unless you are using some JavaScript to send a message to the server) that the browser has closed. How could there be? Think of how HTTP works - everything is request and response. However, the application server will track when Sessions are active and will even tell you whe...
I suggest you remove the ID when the Servlet engine destroys the session. Register a [`HttpSessionListener`](http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpSessionListener.html) that removes the user's ID when `sessionDestroyed()` is called. [Diodeus](https://stackoverflow.com/questions/299679/java-servl...
How to detect browser closing?
[ "", "javascript", "servlets", "" ]
I'm pretty green with web services and WCF, and I'm using Windows integrated authentication - how do I get the username on the server-side interface? I believe that I'm supposed to implement a custom Behavior, or perhaps something with WCF Sessions? Any clues would be super-handy.
Here is a snippet of service code that shows how you could retrieve and use the WindowsIdentity associated with the caller of a WCF service. This code is assuming that you are accepting most of the defaults with your configuration. It should work without any problems with the Named Pipe or the Net TCP binding. the p....
Try looking at ServiceSecurityContext.Current.WindowsIdentity
Get Windows Username from WCF server side
[ "", "c#", "wcf", "" ]
I have a List< int[] > myList, where I know that all the int[] arrays are the same length - for the sake of argument, let us say I have 500 arrays, each is 2048 elements long. I'd like to sum all 500 of these arrays, to give me a single array, 2048 elements long, where each element is the sum of all the same positions ...
Edit: Ouch...This became a bit harder while I wasn't looking. Changing requirements can be a real PITA. Okay, so take each position in the array, and sum it: ``` var sums = Enumerable.Range(0, myList[0].Length) .Select(i => myList.Select( nums => nums[i] ).Sum() ...
EDIT: I've left this here for the sake of interest, but the accepted answer is much nicer. EDIT: Okay, my previous attempt (see edit history) was basically completely wrong... You *can* do this with a single line of LINQ, but it's horrible: ``` var results = myList.SelectMany(array => array.Select( ...
How do I sum a list<> of arrays
[ "", "c#", "linq", "" ]
I have a large .NET web application. The system has projects for different intentions (e.g. CMS, Forum, eCommerce), and I have noticed a (naive) pattern of calling on another project's class. For example, the ecommerce module needs functionality to generate a file on the fly for products, and I call and reference a met...
It sounds like you have a layering problem. Your assemblies should have a single dependency cycle - from least stable to most stable. That allows you to version sensibly. Generally, that cycle would be something like UI (least stable) -> Domain Core (stable) -> Data Access (most stable). You can throw in a Utilities or...
You should expose web services in those projects who will be needed by other projects. This is kind of the base level idea behind SOA. So, I would just create web services and consume them, which will decouple you quite a bit from how you have it now. Hope this helps.
Simple tips to reduce coupling
[ "", "c#", "" ]
I have a question similar to the one here: [Event handlers inside a Javascript loop - need a closure?](https://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure#341759) but I'm using jQuery and the solution given seems to fire the event when it's bound rather than on click. Here...
You're missing a function. The .click function needs a function as a parameter so you need to do this: ``` .click( function(indGroup,indValue) { return function() { jQuery(".IndicatorImage").removeClass("active"); _this.Indicator.TrueImage = DisplayGlobals.Indicators[ind...
Solution by **Greg** is still valid, but you can do it without creating additional closure now, by utilizing `eventData` parameter of jQuery [click](http://api.jquery.com/click/) method (or [bind](http://api.jquery.com/bind/) or any other event-binding method, for that matter). ``` .click({indGroup: i, indValue : j}, ...
jQuery Closures, Loops and Events
[ "", "javascript", "jquery", "loops", "closures", "" ]
I know you can use the `<jsp:useBean>` tag to instantiate objects within JSPs without resorting to scriptlet code. However I'd like to instantiate an Integer who value is the result of an EL expression, something like: ``` <jsp:useBean id="total" class="java.lang.Integer"> <jsp:setProperty name="amount" value="${p...
**`<c:set var="amount" value="${param1 + param2}" scope="page" />`**
Primitive wrappers also have no default constructor so you can't even initialize one that way. I'm not sure that EL is supposed to be used in that way. It is more of a template language. It isn't clear what advantage what you are trying to do has over something like: ``` <% Integer total = new Integer(param1 + para...
creating immutable objects in JSPs
[ "", "java", "jsp", "jsp-tags", "" ]
Well I am querying my DB, a table called bookBilling, to get a value under the column of billingID. In my first query I get the customer ID from a table based on what value the cookie holds. In my second query I take that custID value and am looking to get the billingID associated with it. ``` query = "SELECT custID ...
Hey, is it a typo that you don't have this? > query = "SELECT billingID FROM bookBilling WHERE custID="&custID&"" > > ***objRS =*** objConn.Execute(query) To reload the recordset with the data and definition of the second query..... Just a thought, try Setting/Instantiating the ObjRS to a Recordset first, then apply...
Running two separate queries is slow anyway. It's almost always faster to combine them into one statement: ``` SELECT billingID FROM bookBilling bb INNER JOIN bookSession bs ON bs.custID=bb.custID WHERE bs.session= @theCookie ``` Also: cookies are just text files, and anyone can edit a text file. If you substitute a ...
Classic ASP Database error
[ "", "sql", "asp-classic", "odbc", "" ]
I have a web app that is heavily loaded in javascript and css. First time users log in it takes some time to load once it is downloading js etc. Then the caching will make everything faster. I want my users to be aware of this loading time. How can I add some code to "show" some loading information while js and css ar...
You could show an overlay saying "loading..." and hide this the moment the downloads are complete. ``` <html> <head> ... a bunch of CSS and JS files ... <script type="text/javascript" src="clear-load.js"></script> </head> <body> <div style="position: absolute; left: 50...
Please do yourself a favor and try YSlow, available at [http://developer.yahoo.com/yslow](http://developer.yahoo.com "YSlow"). It's a Firebug plugin (yes, a plugin for a plugin) that will analyze your site and recommend strategies for fixing it.
Show loading information while js and css are downloaded
[ "", "javascript", "" ]
I have a mouseenter and mouseleave event for a Panel control that changes the backcolor when the mouse enters and goes back to white when it leaves. I have Label control within this panel as well but when the mouse enters the Label control, the mouseleave event for the panel fires. This makes sense but how do I keep ...
You can use GetChildAtPoint() to determine if the mouse is over a child control. ``` private void panel1_MouseLeave(object sender, EventArgs e) { if (panel1.GetChildAtPoint(panel1.PointToClient(MousePosition)) == null) { panel1.BackColor = Color.Gray; } } ``` If the control isn't actually a child ...
I found a simple solution. I just set the enabled property to false on the label and it's fine.
Custom controls in C# Windows Forms mouse event question
[ "", "c#", "winforms", "events", "" ]
I'm using [JSLint](http://en.wikipedia.org/wiki/JSLint) to go through JavaScript, and it's returning many suggestions to replace `==` (two equals signs) with `===` (three equals signs) when doing things like comparing `idSele_UNVEHtype.value.length == 0` inside of an `if` statement. Is there a performance benefit to r...
The strict equality operator (`===`) behaves identically to the abstract equality operator (`==`) except no type conversion is done, and the types must be the same to be considered equal. Reference: [JavaScript Tutorial: Comparison Operators](https://www.c-point.com/javascript_tutorial/jsgrpComparison.htm) The `==` o...
### Using the `==` operator (*Equality*) ``` true == 1; //true, because 'true' is converted to 1 and then compared "2" == 2; //true, because "2" is converted to 2 and then compared ``` ### Using the `===` operator (*Identity*) ``` true === 1; //false "2" === 2; //false ``` This is because the **equality operator ...
Which equals operator (== vs ===) should be used in JavaScript comparisons?
[ "", "javascript", "operators", "equality", "equality-operator", "identity-operator", "" ]
Why are the lists `list1Instance` and `p` in the `Main` method of the below code pointing to the same collection? ``` class Person { public string FirstName = string.Empty; public string LastName = string.Empty; public Person(string firstName, string lastName) { this.FirstName ...
In fact, `IEnumerable<T>` **is already readonly**. It means you cannot replace any items in the underlying collection with different items. That is, you cannot alter the *references* to the `Person` objects that are held in the collection. The type `Person` is not read only, however, and since it's a reference type (i....
Return a new instance of Person that is a copy of `p` instead of `p` itself in Get(). You'll need a method to make a deep-copy of a Person object to do this. This won't make them read only, but they will be different than those in the original list. ``` public IEnumerable<Person> Get() { foreach (Person p in l1) ...
How to make IEnumerable<T> readonly?
[ "", "c#", ".net", "generics", "ienumerable", "" ]
I'm using ctypes to load a DLL in Python. This works great. Now we'd like to be able to reload that DLL at runtime. The straightforward approach would seem to be: 1. Unload DLL 2. Load DLL Unfortunately I'm not sure what the correct way to unload the DLL is. \_ctypes.FreeLibrary is available, but private. Is there...
you should be able to do it by disposing the object ``` mydll = ctypes.CDLL('...') del mydll mydll = ctypes.CDLL('...') ``` **EDIT:** Hop's comment is right, this unbinds the name, but garbage collection doesn't happen that quickly, in fact I even doubt it even releases the loaded library. Ctypes doesn't seem to pro...
It is helpful to be able to unload the DLL so that you can rebuild the DLL without having to restart the session if you are using iPython or similar work flow. Working in windows I have only attempted to work with the windows DLL related methods. ``` REBUILD = True if REBUILD: from subprocess import call call('g++...
How can I unload a DLL using ctypes in Python?
[ "", "python", "dll", "ctypes", "" ]
I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this: ``` void erase(std::vector<int>& myNumbers_in, int number_in) { ...
Since C++20, there are freestanding [`std::erase` and `std::erase_if`](https://en.cppreference.com/w/cpp/container/vector/erase2) functions that work on containers and simplify things considerably: ``` std::erase(myNumbers, number_in); // or std::erase_if(myNumbers, [&](int x) { return x == number_in; }); ``` Prior t...
Calling erase will invalidate iterators, you could use: ``` void erase(std::vector<int>& myNumbers_in, int number_in) { std::vector<int>::iterator iter = myNumbers_in.begin(); while (iter != myNumbers_in.end()) { if (*iter == number_in) { iter = myNumbers_in.erase(iter); ...
How can you erase elements from a vector while iterating?
[ "", "c++", "vector", "stl", "stdvector", "erase", "" ]
I have a problem and i would like to learn the correct way to solve this. I have a Data Objeckt ``` class LinkHolder { public string Text; public string Link; } ``` I would like to present to the user a RadioButton list that uses the LinkHolder.Text value as descriptive text. Then on the postback, i would li...
You need to set DataTextField and DataValueField on your RadioButtonList. Then the correct values should show up. You can try to cast the selectedItem into a LinkHolder.
Your method should work. I think you should use accessors in your class though ``` class LinkHolder { public string Text { get; set;} public string Link { get; set;} } ``` Bind your RadioButtonList to a f.ex. `List<LinkHolder>` Why would you use a radiobuttonlist instead of just listing out your Links as Hyp...
Best design for RadioButtonList usage
[ "", "c#", "asp.net", "radiobuttonlist", "correctness", "" ]
What options do you have to communicate between the WARs in an EAR? We have several WARs providing different webservices deployed within one EAR. For their tasks they need to communicate with the other WARs. Of course they could communicate using webservices. What other, perhaps more efficient, options are there? EDIT...
First, you should be clear about what is that you are sharing. You should differentiate between the service and a library. Library lets you share the common functionality, this is what you achieve when you use log4j library for example. In that case, you setup log4j in each project that is using it. On the other hand, ...
Since your edit seems to imply that the communications are not actually required between WARS, but both need to access the same shared resources. The simplest solution would be to put the jars for this resource in the EAR and add the dependency for those jars to both web projects so they are using the shared resource. ...
Options to communicate between WARs in the same EAR
[ "", "java", "web-services", "deployment", "jakarta-ee", "" ]
I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or...
You've actually got a lot going on in this example. 1. You've "over-processed" the Beautiful Soup Tag objects to make lists. Leave them as Tags. 2. All of these kinds of merge algorithms are hard. It helps to treat the two things being merged symmetrically. Here's a version that should work directly with the Beautifu...
Here is a modified version of your algorithm. *zip* is used to iterate over **short** lengths and headers and a *class object* is used to count and iterate the **long** items, as well as combine the headers. *while* is more appropriate for the inner loop. (forgive the too short names). ``` class collector(object): ...
Is there a more Pythonic way to merge two HTML header rows with colspans?
[ "", "python", "beautifulsoup", "" ]
I am working on creating an immutable class. I have marked all the properties as read-only. I have a list of items in the class. Although if the property is read-only the list can be modified. Exposing the IEnumerable of the list makes it immutable. I wanted to know what is the basic rules one has to follow to ...
I think you're on the right track - * all information injected into the class should be supplied in the constructor * all properties should be getters only * if a collection (or Array) is passed into the constructor, it should be copied to keep the caller from modifying it later * if you're going to return your collec...
To be immutable, all your properties and fields should be readonly. And the items in any list should themselves be immutable. You can make a readonly list property as follows: ``` public class MyClass { public MyClass(..., IList<MyType> items) { ... _myReadOnlyList = new List<MyType>(items).As...
How do I create an immutable Class?
[ "", "c#", ".net", "immutability", "" ]
I have an interface A, for which I have to supply a few different implementations. However, those implementations share some helper methods, so I moved those methods to an abstract base class. ``` Interface A { void doX(); } abstract Class B implements A { protected void commonY() { // ... } ...
I think it would be better to do it as follows: ``` Interface A { void doX(); } abstract Class B { protected void commonY() { // ... } } Class C extends B implements A{ public void doX() { // ... } } Class D extends B implements A{ pu...
* Should I declare the abstract Method doX() in Class B? Why (not)? No. It's an abstract class - defining the interface will mean that all subclasses will need to implement those methods. In other words, it's redundant. * Should I also explicitly declare "implements A" on Class C and D? Why (not)? No, again - becaus...
What (not) to declare when implementing an interface with an abstract class?
[ "", "java", "class", "interface", "declaration", "abstract", "" ]
A client has installed Sql server 2005 reporting services. When we go to the web bit at `http://servername/reports/` we just see a blank screen like: ![http://img91.imageshack.us/img91/3787/rsblankqx4.jpg](https://i.stack.imgur.com/nGQXH.jpg) We are using windows authentication and I think it has authenticated us as t...
Client reinstalled and this then worked fine. Must have become corrupted in some way.
Does the user have access to any reports? Login as an admin user and make sure to give him access to the reports
sql reporting serices not showing anything when go to web interface
[ "", "sql", "reporting-services", "reporting", "" ]
I made a code that translate strings to match each word from the array 0ne to the array two and its showing the right results. But how to let the compiler take the number in the string and print it out as it is, ummmm see the code i wrote --- ``` class Program { public static string[] E = { "i", "go", "sc...
Change your regex to `[a-zA-Z0-9]+` By the way, why don't you use `String.Split` method instead of Regex?
This regular expression will work better when you actually start typing the accents on your French words, and you want to split a French string: ``` \w+ ``` In .NET, \w includes all letters and numbers from all scripts, not just the English a-z and 0-9.
Regular Expression, numbers?
[ "", "c#", "regex", "" ]
I am starting a WPF project, which will be fairly complicated in complexity and will make use of a lot of modern UIs, like outlook bar, grids, tabs, etc... I've looked around in the marketplace and there aren't too many control suites. Some of the available ones are either Beta or CTP. Others don't look too polished. Y...
The thing to remember is that WPF is very different from WinForms, you can do amazing things buy just re-skining existing controls, when you are starting your first WPF big project you don't yet understand WPF and you don't know the possibilities and pitfalls of the system. I suggest you start developing the project w...
One of the best things about WPF (and XAML in general) is that it makes customizing the available controls a whole lot easier than it was back in WinForms days. Everything depends on the level of customization that you need. If you just have to tweak the look-and-feel of the standard controls, you can do that using a t...
Starting WPF project. Build own controls or buy?
[ "", "c#", "wpf", "visual-studio-2008", "" ]
i need to convert pointers to long (SendMessage()) and i want to safely check if the variable is correct on the otherside. So i was thinking of doing dynamic\_cast but that wont work on classes that are not virtual. Then i thought of doing typeid but that will work until i pass a derived var as its base. Is there any ...
If all you have is a `long`, then there's not really much you can do. There is no general way to determine whether an arbitrary number represents a valid memory address. And even if you know it's a valid memory address, there is no way to determine the type of the thing the pointer points to. If you can't be sure of th...
Your reference to `SendMessage()` makes i sounds like MS Windows is your platform and then the [Rules for Using Pointers (Windows)](http://msdn.microsoft.com/en-us/library/aa384242(VS.85).aspx) is recommended reading. It details the `PtrToLong` and `PtrToUlong` functions and other things Microsoft provide for you in si...
check if X is derived of Y via typeid
[ "", "c++", "casting", "typeid", "" ]
In a .NET application, how can I identify which network interface is used to communicate to a given IP address? I am running on workstations with multiple network interfaces, IPv4 and v6, and I need to get the address of the "correct" interface used for traffic to my given database server.
The simplest way would be: ``` UdpClient u = new UdpClient(remoteAddress, 1); IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address; ``` Now, if you want the NetworkInterface object you do something like: ``` foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfacePr...
Neither of these will actually give the OP the info he's looking for -- he wants to know which interface will be used to reach a given destination. One way of doing what you want would be to shell out to the **route** command using System.Diagnostics.Process class, then screen-scrape the output. `route PRINT (destinati...
Identifying active network interface
[ "", "c#", ".net", "networking", "" ]
How can I convert a RGB Color to HSV using C#? I've searched for a fast method without using any external library.
Have you considered simply using System.Drawing namespace? For example: ``` System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue); float hue = color.GetHue(); float saturation = color.GetSaturation(); float lightness = color.GetBrightness(); ``` Note that it's not exactly what you've asked for ...
Note that `Color.GetSaturation()` and `Color.GetBrightness()` return HSL values, not HSV. The following code demonstrates the difference. ``` Color original = Color.FromArgb(50, 120, 200); // original = {Name=ff3278c8, ARGB=(255, 50, 120, 200)} double hue; double saturation; double value; ColorToHSV(original, out h...
How to Convert RGB Color to HSV?
[ "", "c#", "colors", "rgb", "hsv", "" ]
Is there a better, more elegant (and/or possibly faster) way than ``` boolean isNumber = false; try{ Double.valueOf(myNumber); isNumber = true; } catch (NumberFormatException e) { } ``` ...? --- **Edit**: Since I can't pick two answers I'm going with the regex one because a) it's elegant and b) saying "Jon Sk...
I don't believe there's anything built into Java to do it faster and still reliably, assuming that later on you'll want to actually parse it with Double.valueOf (or similar). I'd use Double.parseDouble instead of Double.valueOf to avoid creating a Double unnecessarily, *and* you can also get rid of blatantly silly num...
You could use a regex, i.e. something like `String.matches("^[\\d\\-\\.]+$");` (if you're not testing for negative numbers or floating point numbers you could simplify a bit). Not sure whether that would be faster than the method you outlined though. **Edit:** in the light of all this controversy, I decided to make a...
Most elegant way to detect if a String is a number?
[ "", "java", "string", "parsing", "numbers", "" ]
I'm building a website in ASP.Net, using MVC, and need to list a set of results. Both of the following work as I want them to but I'm wondering which is faster, cleaner and/or better - or if another option entirely would be more appropriate? Note: `ViewData.Model` is of type `IEnumerable<Thing>` and I need to display ...
`foreach` is definitely faster, if you don't specifically screw up something. `Repeater` is cleaner of course, and more neatly separates UI and logic. Sometimes you need more conditions (other than different look even and odd rows) to render your stuff properly which makes `foreach` the only choice. I personally prefe...
`foreach` is the way to go for ASP.NET MVC. Why? i personally avoid *any* legacy `asp:xxx` controls .. because they could possibly have the bloat that exists with the webforms model. Secondly, what about all the `event delegates` you have to wire up? you're starting to mix and match architectures, IMO, so this could se...
foreach or Repeater - which is better?
[ "", "c#", "asp.net-mvc", "loops", "" ]
I'm thinking about using BlogEngine.NET to launch my blog. I'm a C# programmer and was wondering was BlogEngine.NET has in the belly. Does it scale well? Is it caching properly? Is it memory intensive? Can you easily add/remove functionality? I also accept any hosting recommendation :)
I'm running BlogEngine.Net. I don't know about scaling because my weblog isn't that popular (yet). I'm very happy with it. I tried subtext before and I had some stability problems with it, it logged exceptions that I found hard to debug. I got an error exporting the database to BlogML and it messed up the order of my b...
I've tried dasBlog, subText, and BlogEngine.Net, and I personally think that BlogEngine.Net is overall the most solid open source .Net blogging platform. But as with most open-source project, you should expect to put it a little elbow grease in order to make it look and behave like you want. For instance, I've had to m...
Who is using BlogEngine.Net for their blog? Does it run well? Will it scale? :P
[ "", "c#", "blogs", "blogengine.net", "" ]
The size and range of the integer value types in C++ are platform specific. Values found on most 32-bit systems can be found at [Variables. Data Types. - C++ Documentation](http://www.cplusplus.com/doc/tutorial/variables.html). How do you determine what the actual size and range are for your specific system?
## C Style limits.h contains the min and max values for ints as well as other data types which should be exactly what you need: ``` #include <limits.h> // C header #include <climits> // C++ header // Constant containing the minimum value of a signed integer (–2,147,483,648) INT_MIN; // Constant containing the maxi...
Take a look at `std::numeric_limits`
How do you find the range of values that integer types can represent in C++?
[ "", "c++", "types", "" ]
## Goal Java client for Yahoo's HotJobs [Resumé Search REST API](http://developer.yahoo.com/hotjobs/resume_search_user_guide/index.html). ## Background I'm used to writing web-service clients for SOAP APIs, where [wsimport](https://jax-ws.dev.java.net/jax-ws-ea3/docs/wsimport.html) generates proxy stubs and you're o...
It's interesting that they provide an HTTP URL as the namespace URI for the schema, but don't actually save their schema there. That could be an oversight on their part, which an email or discussion-list posting could correct. One approach is to create your own schema, but this seems like a lot of work for little retu...
I would suggest writing beans by hand, and only annotating with JAXB annotations if you have to. For most accessors/mutators (getters/setters) you do not have to; by default all public bean accessors and fields are considered, name is derived using bean convention, and default is to use elements instead of attributes (...
Java REST client without schema
[ "", "java", "xml", "jaxb", "jax-rs", "" ]
I'm writing an application that includes a plugin system in a different assembly. The problem is that the plugin system needs to get application settings from the main app (like the directory to look for plugins). How is this done, or am I going about this the wrong way? Edit: I was encouraged to add some details ab...
Let the main application get the plugin directory from the application settings and push it into the plugin system.
Perhaps you could insert the configuration as an argument when creating the plugin? ``` //Get the configuration for the current appDomain System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //Create the plugin, and pass in the configuration IPlugin myPlu...
Using application settings across assemblies
[ "", "c#", ".net", "plugins", "" ]
Simple question: Can I mix in my desktop application Java and JavaFX Script code? If it is possible could you provide me with some link with examples? Or could I pack my custom made javafx CustomNode-s in a jar and use them in my project side by side with standard SWING components?
[This article](http://java.dzone.com/news/calling-javafx-from-java) gives an example of calling JavaFX from Java, using the [Scripting API](http://java.sun.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html).
Yes, you can mix Java and JavaFX. According to [one of the FAQ entries](http://www.javafx.com/faq/#1.10): > In addition, developers can use any Java library in their JavaFX applications. This allows JavaFX applications to take advantage of the rich JavaFX UI libraries, as well as the amazing breadth of functionality ...
JavaFX Script and Java
[ "", "java", "interop", "javafx", "javafx-1", "" ]
I want to pass an enum value as command parameter in WPF, using something like this: ``` <Button x:Name="uxSearchButton" Command="{Binding Path=SearchMembersCommand}" CommandParameter="SearchPageType.First" Content="Search"> </Button> ``` `SearchPageType` is an enum and this is to know from which b...
Try this ``` <Button CommandParameter="{x:Static local:SearchPageType.First}" .../> ``` `local` - is your [namespace reference](http://msdn.microsoft.com/en-us/library/ms747086.aspx#The_WPF_and_XAML_Namespace_Declarations) in the XAML
Also remember that if your enum is inside another class you need to use the `+` operator. ``` <Button CommandParameter="{x:Static local:MyOuterType+SearchPageType.First}".../> ```
Passing an enum value as command parameter from XAML
[ "", "c#", ".net", "wpf", "xaml", "command", "" ]
I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code [on github](http://github.com/dbr/pyerweb/tree/master) Basically it's written to be as simple to use as possible. An example "Hello World" like site: ``` from p...
Look at [PEP 333](http://www.python.org/dev/peps/pep-0333/) for an excellent design pattern for a very lightweight web server. If your server has this exact API, you can reuse it in a lot of context with a lot of other products. PEP 333 (WSGI) suggests that you don't directly return the page, but you provide the HTML ...
you could use that idea of returning a dict or a string, but add a new decorator, so the 'evolution' for a user would be: simple html: ``` @GET("/") def index(): return "<html><body>...</body></html>" ``` with constant headers (one @HEADER for each one, or a dict with all of them): ``` @GET("/") @HEADER("Location",...
Emitting headers from a tiny Python web-framework
[ "", "python", "frameworks", "" ]
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime? Consider the following sample code - inside the `Example()` method, what's the most concise way to invoke `GenericMethod<T>()` using the `Type` stored in the `myType` variab...
You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with [MakeGenericMethod](http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx): ``` MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod)); MethodInfo g...
Just an addition to the original answer. While this will work: ``` MethodInfo method = typeof(Sample).GetMethod("GenericMethod"); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null); ``` It is also a little dangerous in that you lose compile-time check for `GenericMethod`. If you later d...
How do I call a generic method using a Type variable?
[ "", "c#", ".net", "generics", "reflection", "" ]
Once it is compiled, is there a difference between: ``` delegate { x = 0; } ``` and ``` () => { x = 0 } ``` ?
Short answer : no. Longer answer that may not be relevant: * If you assign the lambda to a delegate type (such as `Func` or `Action`) you'll get an anonymous delegate. * If you assign the lambda to an Expression type, you'll get an expression tree instead of a anonymous delegate. The expression tree can then be compi...
I like Amy's answer, but I thought I'd be pedantic. The question says, "Once it is compiled" - which suggests that both expressions *have* been compiled. How could they both compile, but with one being converted to a delegate and one to an expression tree? It's a tricky one - you have to use another feature of anonymou...
delegate keyword vs. lambda notation
[ "", "c#", ".net", "delegates", "lambda", "anonymous-methods", "" ]
I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?
If you're having problems with syntax, you could try an editor with syntax highlighting. Until you get the feel for a language, simple errors won't just pop out at you. The simplest form of debugging is just to insert some print statements. A more advanced (and extensible) way to do this would be to use the [logging](...
Here is some techniques to facilitate debugging in Python: * use interactive shell e.g., [ipython](http://ipython.scipy.org/moin/Documentation). Python is a dynamic language you can explore your code as you type. The shell is running in the second window in my editor at all times. * copy-paste from the shell into docs...
What are good ways to make my Python code run first time?
[ "", "python", "debugging", "" ]
I have an Eclipse RCP application that displays a lot (10k+) of small images next to each other, like a film strip. For each image, I am using a SWT `Image` object. This uses an excessive amount of memory and resources. I am looking for a more efficient way. I thought of taking all of these images and concatenating the...
You can draw directly on the GC (graphics context) of a new (big) image. Having one big Image should result in much less resource usage than thousands of smaller images (each image in SWT keeps some OS graphics object handle) What you can try is something like this: ``` final List<Image> images; final...
Presumably not every image is visible on screen at any one time? Perhaps a better solution would be to only load the images when they become (or are about to become) visible, disposing of them when they have been scrolled off the screen. Obviously you'd want to keep a few in memory on either side of the current viewpor...
SWT Image concatenation or tiling / mosaic
[ "", "java", "eclipse", "swt", "eclipse-pde", "" ]
I recently learnt that oracle has a feature which was pretty useful to me - as the designer/implementator didn't care much about data history - I can query the historical state of a record if it's available yet in the oracle cache, like this: ``` select * from ( select * from sometable where some_condit...
Yes, like this: ``` SQL> select sal from emp where empno=7369; SAL ---------- 5800 SQL> update emp set sal = sal+100 where empno=7369; 1 row updated. SQL> commit; Commit complete. SQL> update emp set sal = sal-100 where empno=7369; 1 row updated. SQL> commit; Commit complete. SQL> select e...
One note to be aware of is that this sort of flashback query relies on UNDO information that is written to the UNDO tablespace. And that information is not retained forever-- most production systems under reasonable load are not going to have 24 hours of UNDO information available. Depending on the Oracle version, you...
Oracle record history using as of timestamp within a range
[ "", "sql", "oracle", "caching", "timestamp", "range", "" ]
I have a series of Extension methods to help with null-checking on IDataRecord objects, which I'm currently implementing like this: ``` public static int? GetNullableInt32(this IDataRecord dr, int ordinal) { int? nullInt = null; return dr.IsDBNull(ordinal) ? nullInt : dr.GetInt32(ordinal); } public static int...
You can just declare your method like this: ``` public static T GetNullable<T>(this IDataRecord dr, int ordinal) { return dr.IsDBNull(ordinal) ? default(T) : (T) dr.GetValue(ordinal); } ``` This way, if T is a nullable int or any other nullable value type, it will in fact return null. If it's a regular datatype, ...
This works: ``` public static T Get<T>( this IDataRecord dr, int ordinal) { T nullValue = default(T); return dr.IsDBNull(ordinal) ? nullValue : (T) dr.GetValue(ordinal); } public void Code(params string[] args) { IDataRecord dr= null; int? a = Get<int?>(dr, 1); string b = Get<string>(dr, 2); } ...
Can a Generic Method handle both Reference and Nullable Value types?
[ "", "c#", ".net", "generics", "" ]
Well basically I have this script that takes a long time to execute and occasionally times out and leaves semi-complete data floating around my database. (Yes I know in a perfect world I would fix THAT instead of implementing commits and rollbacks but I am forced to not do that) Here is my basic code (dumbed down for ...
Take a look at [this tutorial](http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#11) on transactions with PDO. Basically wrap the long running code in: ``` $dbh->beginTransaction(); ... $dbh->commit(); ``` And [according to this PDO document page](http://usphp.com/manual/en/ref.pdo.php): "When the script ...
You need to use InnoDB based tables for transactions then use any library like PDO or MySQLi that supports them.
How can I implement commit/rollback for MySQL in PHP?
[ "", "php", "mysql", "pdo", "commit", "rollback", "" ]
I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those ...
splitting should do the trick. Here's a good way to extract the data, as well: ``` >>> line = "$GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00" >>> line = line.split(",") >>> neededData = (float(line[2]), line[3], float(line[4]), line[5], float(line[9])) >>> print neededData (3248.7779999999998, '...
You could use a library like [pynmea2](https://github.com/Knio/pynmea2) for parsing the NMEA log. ``` >>> import pynmea2 >>> msg = pynmea2.parse('$GPGGA,142927.829,2831.4705,N,08041.0067,W,1,07,1.0,7.9,M,-31.2,M,0.0,0000*4F') >>> msg.timestamp, msg.latitude, msg.longitude, msg.altitude (datetime.time(14, 29, 27), 28.5...
Parsing GPS receiver output via regex in Python
[ "", "python", "regex", "parsing", "gps", "nmea", "" ]
Should Singleton objects that don't use instance/reference counters be considered memory leaks in C++? Without a counter that calls for explicit deletion of the singleton instance when the count is zero, how does the object get deleted? Is it cleaned up by the OS when the application is terminated? What if that Single...
You can rely on it being cleaned up by the operating system. That said, if you are in a garbage collected language with finalizers rather than destructors you may want to have a graceful shutdown procedure that can cleanly shutdown your singletons directly so they can free any critical resources in case there are usin...
As so often, "it depends". In any operating system worthy of the name, when your process exits, all memory and other resources used locally within the process WILL be released. You simply don't need to worry about that. However, if your singleton is allocating resources with a lifetime outside it's own process (maybe ...
Singleton Destructors
[ "", "c++", "memory-management", "singleton", "" ]
I'm matching ASP.Net generated elements by ID name, but I have some elements which may render as text boxes or labels depending on the page context. I need to figure out whether the match is to a textbox or label in order to know whether to get the contents by val() or by html(). ``` $("[id$=" + endOfIdToMatch + "]")....
Just one jQuery too much: ``` $("[id$=" + endOfIdToMatch + "]").each(function () { alert(this.tagName); }); ```
Consider this solution without using *each()*: ``` var elements = $("[id$=" + endOfIdToMatch + "]"); var vals = elements.is("input").val(); var htmls = elements.is("label").html(); var contents = vals.concat(htmls); ``` [Have a look at the documentation for *is*.](http://docs.jquery.com/Traversing/is)
How can I determine the element type of a matched element in jQuery?
[ "", "asp.net", "javascript", "jquery", "html", "" ]
Having a strange issue with some C# code - the Getter method for a property is showing up as virtual when not explicitly marked. The problem exhibits with the DbKey property on this class (code in full): ``` public class ProcessingContextKey : BusinessEntityKey, IProcessingContextKey { public ProcessingContextKey...
It's virtual because it implements an interface method. Interface implementation methods are always virtual as far as the CLR is concerned.
The DbKey property getter is virtual in the IL because it is in an interface. The setter is not virtual because it is not part of the interface but part of the concrete class. [ECMA-335: Common Language Infrastructure](http://www.ecma-international.org/publications/standards/Ecma-335.htm) Section 8.9.4 notes that: > ...
Why is this property Getter virtual?
[ "", "c#", ".net", "reflection", ".net-3.5", "" ]
I'm trying to run the Camel Example "camel-example-spring-jms" (also at <http://activemq.apache.org/camel/tutorial-jmsremoting.html>). However, when I try to start Camel using "org.apache.camel.spring.Main" class, I get the error saying **"Configuration problem: Unable to locate Spring NamespaceHandler for XML schema ...
So it works fine under maven - but not if you run it how? In your IDE or something? If you are using eclipse / intellij you can create an IDE project for the maven project using maven. ``` mvn eclipse:eclipse ``` or ``` mvn idea:idea ``` If you are writing some shell script or running it from the command line then...
This particular exception is caused when the camel-jms library .jar is not on your classpath. As mentioned by James, ensure this library is correctly in your classpath when running.
Unable to start Camel 1.5.0
[ "", "java", "spring", "jakarta-ee", "jms", "apache-camel", "" ]
I have an element with an **onclick** method. I would like to activate that method (or: fake a click on this element) within another function. Is this possible?
If you're using JQuery you can do: ``` $('#elementid').click(); ```
Once you have selected an element you can call click() ``` document.getElementById('link').click(); ``` see: <https://developer.mozilla.org/En/DOM/Element.click> I don't remember if this works on IE, but it should. I don't have a windows machine nearby.
Fake "click" to activate an onclick method
[ "", "javascript", "event-handling", "" ]
Say I have a rectangular string array - not a jagged array ``` string[,] strings = new string[8, 3]; ``` What's the best way to extract a one-dimensional array from this (either a single row or a single column)? I can do this with a for loop, of course, but I'm hoping .NET has a more elegant way built in. Bonus poin...
For a rectangular array: ``` string[,] rectArray = new string[3,3] { {"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"} }; var rectResult = rectArray.Cast<object>().ToArray(); ``` And for a jagged array: ``` string[][] jaggedArray = { new string[] {"a", "b", "c", "d"}, new string[] {"e", "f...
You can cast a string array to an object array trivially - going the other way doesn't work. The actual extraction *has* to use a for loop though, as far as I can see: [`Array.Copy`](http://msdn.microsoft.com/en-us/library/system.array.copy.aspx) requires the source and target ranks to be the same, and [`Buffer.BlockCo...
What's the best way to extract a one-dimensional array from a rectangular array in C#?
[ "", "c#", ".net", "arrays", "casting", "" ]
I have a table in a DB (Postgres based), which acts like a superclass in object-oriented programming. It has a column 'type' which determines, which additional columns should be present in the table (sub-class properties). But I don't want the table to include all possible columns (all properties of all possible types)...
The design you're experimenting with is a variation of [Entity-Attribute-Value](http://en.wikipedia.org/wiki/Entity-attribute-value_model), and it comes with a whole lot of problems and inefficiencies. It's not a good solution for what you're doing, except as a last resort. What could be a better solution is what fall...
How about this instead... each sub-type gets its own DB table. And the base/super table just has a varchar column that holds the name of the sub-type DB table. Then you can have something like this... ``` Entity ------ ID Name Type SubTypeName (value of this column will be 'Dog') Dog --- VetName VetNumber etc ``` ...
Optimal DB structure for additional fields entity
[ "", "sql", "database", "postgresql", "entity-attribute-value", "" ]
this is not a primary key, but merely used as a marker in existing system that marks these items with a 1 letter code ie 'N' for new, 'R' for return, etc. I was going to go with a varchar(50) as the data type but wondering if there's anything wrong with say varchar(2) instead aiming for efficiency. thx!
The best datatype would be char(1). varchar means [variable width](http://msdn.microsoft.com/en-us/library/aa258242(SQL.80).aspx), that is, if on a varchar(50) you store only 3 characters, there will be no 47 wasted bytes. But there is a (small) performance hit on accessing it as it has to go check the actual length o...
I would think char(1) would be ideal
What's the best data type for a 1 character code column in a SQL table?
[ "", "sql", "database-design", "" ]
When writing a class do you group members variables of the same type together? Is there any benefit to doing so? For example: ``` class Foo { private: bool a_; bool b_; int c_; int d_; std::string e_; std::string f_; ... }; ``` As opposed to: ``` class Bar { private: std::string e_; ...
I group them according to semantics, i.e. ``` class Foo { private: std::string peach; bool banana; int apple; int red; std::string green; std::string blue; ... }; ``` The more readable, the better.
You should have them in the order you want them initialised, because that's the order they will be initialised, regardless of your initialiser list within the constructor. Not all compilers will warn you about inconsistencies, either.
Grouping similar types of member variables together
[ "", "c++", "" ]
I have a mysql table that relies on the unix epoch time stamp equivalent of the date of the entry to sort and filter in various parts of the website. I'm trying to implement a date picker that will enter the date into the form field in the mm/dd/yyyy format. I've been struggling with converting that date into the unix ...
If you know that it will always be in that format, strtotime will convert it directly into the unix timestamp. ``` strtotime($_POST['app_date']); ``` HTH!
You should look at the [mktime()](http://lv2.php.net/manual/en/function.mktime.php) function. Couple that with either regular expressions or [strtotime()](https://www.php.net/strtotime), and you'll have it.
mm/dd/yyyy format to epoch with PHP
[ "", "php", "timestamp", "epoch", "" ]
I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later? Depending on the circumstances, I may need to pass various arguments into the method too. Some of the functions may take the form of `namespace.namespace.function(args[...])`.
Don't use `eval` unless you *absolutely, positively* have no other choice. As has been mentioned, using something like this would be the best way to do it: ``` window["functionName"](arguments); ``` That, however, will not work with a namespace'd function: ``` window["My.Namespace.functionName"](arguments); // fail...
Just thought I'd post a slightly altered version of [Jason Bunting's very helpful function](https://stackoverflow.com/questions/359788/javascript-function-name-as-a-string/359910#359910). First, I have simplified the first statement by supplying a second parameter to *slice()*. The original version was working fine in...
How to execute a JavaScript function when I have its name as a string
[ "", "javascript", "" ]
This is a follow-up to a [previous question](https://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest) of mine. In the previous question, methods were explored to implement what was essentially the same test over an entire family of functions, ensuring ...
Nose has a "test generator" feature for stuff like this. You write a generator function that yields each "test case" function you want it to run, along with its args. Following your previous example, this could check each of the functions in a separate test: ``` import unittest import numpy from somewhere import the_...
Nose does not scan for tests statically, so you *can* use metaclass magic to make tests that Nose finds. The hard part is that standard metaclass techniques don't set the func\_name attribute correctly, which is what Nose looks for when checking whether methods on your class are tests. Here's a simple metaclass. It l...
How do I get nose to discover dynamically-generated testcases?
[ "", "python", "unit-testing", "nose", "" ]
I need to compare 2 strings in C# and treat accented letters the same as non-accented letters. For example: ``` string s1 = "hello"; string s2 = "héllo"; s1.Equals(s2, StringComparison.InvariantCultureIgnoreCase); s1.Equals(s2, StringComparison.OrdinalIgnoreCase); ``` These 2 strings need to be the same (as far as m...
*FWIW, [knightfor's answer](https://stackoverflow.com/a/7720903/12379) below (as of this writing) should be the accepted answer.* Here's a function that strips diacritics from a string: ``` static string RemoveDiacritics(string text) { string formD = text.Normalize(NormalizationForm.FormD); StringBuilder sb = new...
If you don't need to convert the string and you just want to check for equality you can use ``` string s1 = "hello"; string s2 = "héllo"; if (String.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) == 0) { // both strings are equal } ``` or if you want the comparison to be case insensit...
Ignoring accented letters in string comparison
[ "", "c#", "string", "localization", "" ]
What is the easiest way to check if a computer is alive and responding (say in ping/NetBios)? I'd like a deterministic method that I can time-limit. One solution is simple access the share (File.GetDirectories(@"\compname")) in a separate thread, and kill the thread if it takes too long.
Easy! Use `System.Net.NetworkInformation` namespace's ping facility! [<http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx>](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx)
To check a specific TCP port (`myPort`) on a known server, use the following snippet. You can catch the `System.Net.Sockets.SocketException` exception to indicate non available port. ``` using System.Net; using System.Net.Sockets; ... IPHostEntry myHostEntry = Dns.GetHostByName("myserver"); IPEndPoint host = new IPEn...
How to check if a computer is responding from C#
[ "", "c#", "networking", "netbios", "" ]
Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string? For example: ``` asimpletest -> Asimpletest aSimpleTest -> ASimpleTest ``` I would like to be able to do all string lengths as well.
@[saua](https://stackoverflow.com/a/352494/2285236) is right, and ``` s = s[:1].upper() + s[1:] ``` will work for any string.
``` >>> b = "my name" >>> b.capitalize() 'My name' >>> b.title() 'My Name' ```
Capitalize a string
[ "", "python", "string", "" ]
Are there any good Eclipse plugins for creating smarty templates? I am using Europa with PDT on Ubuntu (though I doubt the OS will make a difference for this). I found [SmartyPDT](http://code.google.com/p/smartypdt/), but it did not seem to install properly and some of the discussions on it seemed to suggest it was fo...
You can find newer version of this plugin here : <http://code.google.com/p/smartypdt/issues/detail?id=31> But I haven't installed it yet with my machine.
When I last used PHPeclipse (you know, the original PHP tools for Eclipse) around 2 years ago, it included a Smarty editor, but it was a bit rudimentary. I don't follow PHPeclipse development anymore, so maybe it has improved in the meantime.
Smarty Plugin for Eclipse Europa
[ "", "php", "eclipse-plugin", "smarty", "eclipse-3.3", "" ]
How would one go about deleting all of the directories in a directory tree that have a certain name if the only access to the server available is via FTP? To clarify, I would like to iterate over a directory tree and delete every directory whose name matches a certain string via FTP. A way to implement this in PHP wou...
Here is a starting point- a function that will scan through an FTP directory and print the name of any directory in the tree which matches the pattern. I have tested it briefly. ``` function scan_ftp_dir($conn, $dir, $pattern) { $files = ftp_nlist($conn, $dir); if (!$files) { return; } foreach...
Presumably there's more to this question than it first appears. FTP supports DIR to list directory contents, RMDIR to remove directories and DEL to delete files, so it supports the operations you need. Or are you asking how to iterate over an FTP directory tree? Do you have a preferred/required implementation langua...
Deleting all directories in an FTP archive that have a certain name using PHP
[ "", "php", "ftp", "" ]
I need a Javascript application that, when run, prompts a password to be entered, and if the password is correct, the script causes the webpage to close. If the password is incorrect, the script prompts for the password to be entered again. I'm planning on loading this script onto my cell phone, which doesn't have a p...
Don't know if this works on your cell phone, but it does with my browser: ``` <head> <script language="JavaScript"> var pass_entered; var password="cool"; while (pass_entered!=password) { pass_entered=prompt('Please enter the password:',''); } self.close(); </script> </head> ```
Javascript "keylock" on a cell phone will probably be trivial to work around. Anyway, if you really want to check password in Javascript, you can at least avoid putting it in plain text in page source. Get [MD5 JS implementation](http://pajhome.org.uk/crypt/md5/), and compare (salted!) password hashes instead.
Simple Password Javascript Code?
[ "", "javascript", "" ]
How do I achieve authorization with MVC asp.net?
Use the Authorize attribute ``` [Authorize] public ActionResult MyAction() { //stuff } ``` You can also use this on the controller. Can pass in users or roles too. If you want something with a little more control, you could try something like [this](http://schotime.net/blog/index.php/2009/02/17/custom-authorizati...
There is an Authorization feature with MVC, using ASP.NET MVC beta and creating the MVC project from Visual Studio, automatically adds a controller that used authorization. One thing that will help with your google search, is that it is a "filter". So try searching on "Authorization Filter MVC" and anything preview 4 o...
ASP.NET MVC Authorization
[ "", "c#", "asp.net-mvc", "authorization", "" ]
What is the best way to ascertain the length (in characters) of the longest element in an array? I need to find the longest element in an array of option values for a select box so that I can set the width dynamically.
This returns the key of the longest value and can also give you the value itself ``` function array_longest_value( $array, &$val = null ) { $val = null; $result = null; foreach( array_keys( $array ) as $i ) { $l = strlen( $array[ $i ] ); if ( $l > $result ) { $resul...
If you just want the highest value: ``` echo max(array_map('strlen', $arr)); ``` If you want the longest values: ``` function array_longest_strings(array $arr) { $arr2 = array_map('strlen', $arr); $arr3 = array_intersect($arr2, array(max($arr2))); return array_intersect_key($arr, $arr3); } print_r(array_...
What is the best way to ascertain the length (in characters) of the longest element in an array?
[ "", "php", "arrays", "" ]
I've been doing some performance testing around the use of System.Diagnostics.Debug, and it seems that all code related to the static class Debug gets completely removed when the Release configuration is built. I was wondering how the compiler knows that. Maybe there is some class or configuration attribute that allows...
You can apply the [ConditionalAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=netframework-4.8) attribute, with the string "DEBUG" to any method and calls to that item will only be present in DEBUG builds. This differs from using the #ifdef approach as this allows y...
Visual Studio defines a DEBUG constant for the Debug configuration and you can use this to wrap the code that you don't want executing in your Release build: ``` #ifdef DEBUG // Your code #endif ``` However, you can also decorate a method with a Conditional attribute, meaning that the method will never be called fo...
Removing code from Release build in .NET
[ "", "c#", "debugging", "" ]
I am just looking at the [source code](https://github.com/BlogEngine/BlogEngine.NET) of [BlogEngine.Net](https://learn.microsoft.com/en-us/iis/publish/deploying-application-packages/blogenginenet) and was intrigued at how it stores application settings. Instead of using web.config or app.config which I am accustomed t...
If you have an admin area where you can alter the configuration settings, writing to web.config will cause the app to be restarted and all users to lose their session data. Using a separate config file will prevent this from happening.
One serious drawback to this model is the inability to pick up changes made outside the application. As the config settings are loaded at startup and maintained in memory all changes have to be done either through the administration pages or while the application is offline.
Configuration settings in (web.config|app.config) versus a Static Class Object
[ "", "c#", "asp.net", ".net", "architecture", "app-config", "" ]
What is the most efficient way of setting values in C# multi-dimensional arrays using a linear index? For example given an array... ``` int[,,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}} , {{9,10,11}, {12,13,14}, {15,16,17}} , {{18,19,20}, {21,22,23}, {24,25,26}} }; ``` How do I se...
why do you need the IList ? ``` static void SetValue2(this Array a, object value, int i) { int[] indices = new int[a.Rank]; for (int d = a.Rank - 1; d >= 0; d--) { var l = a.GetLength(d); indices[d] = i % l; i /= l } a.SetValue(value, indices); } ``` Test Code: ``` static void...
Do you know how many tuples will exist initially? If you have say a matrix with dimensions a x b x c x d, couldn't you use the following to get a list of all the indices: ``` for i=0 to (a*b*c*d) Array[i % a, (i/a) % b, (i/(a*b) % c, i / (a*b*c)] = 30 ``` So that as the counter rolls over various bounds, each...
How to set values in a multidimensional array using a linear index
[ "", "c#", ".net", "" ]
(I'm using the [pyprocessing](http://developer.berlios.de/projects/pyprocessing) module in this example, but replacing processing with multiprocessing should probably work if you run [python 2.6](http://docs.python.org/library/multiprocessing.html) or use the [multiprocessing backport](http://code.google.com/p/python-m...
Isnt that what select is for?? Only call accept on the socket if the select indicates it will not block... The select has a timeout, so you can break out occasionally occasionally to check if its time to shut down....
I thought I could avoid it, but it seems I have to do something like this: ``` from processing import connection connection.Listener.fileno = lambda self: self._listener._socket.fileno() import select l = connection.Listener('/tmp/x', 'AF_UNIX') r, w, e = select.select((l, ), (), ()) if l in r: print "Accepting......
Proper way of cancelling accept and closing a Python processing/multiprocessing Listener connection
[ "", "python", "sockets", "multiprocessing", "" ]
I am building a search box (input field) which should make a server call to filter a grid with the text being inserted on it but I need to make this in an smart way, I need to fire the server call only if the user has stopped. Right now I'm trying to implement it, but if someone knows how to do it I'll be very pleased....
1. When a key is pressed: 1. Check if there's an existing timer - stop it if there is one 2. start a timer. 2. When the timer expires, call the server method. ``` var searchTimeout; document.getElementById('searchBox').onkeypress = function () { if (searchTimeout != undefined) clearTimeout(searchTimeout); ...
You could use calls to `setTimeout` that calls your server function (with a maybe 2-3 second delay) on a keypress event. As soon as akey is pressed, cancel the previous `setTimeout`call and create a new one. Then, 2-3 seconds have elapsed with no keypresses, the server event will be fired.
Determine when an user is typing
[ "", "javascript", "ajax", "" ]
I'm using an image component that has a FromBinary method. Wondering how do I convert my input stream into a byte array ``` HttpPostedFile file = context.Request.Files[0]; byte[] buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); ImageElement image = ImageElement.FromBinary(b...
Use a BinaryReader object to return a byte array from the stream like: ``` byte[] fileData = null; using (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) { fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength); } ```
``` BinaryReader b = new BinaryReader(file.InputStream); byte[] binData = b.ReadBytes(file.InputStream.Length); ``` line 2 should be replaced with ``` byte[] binData = b.ReadBytes(file.ContentLength); ```
How to create byte array from HttpPostedFile
[ "", "c#", "arrays", "" ]
I'm seeing a lot of Javascript errors in IE8 on pages which worked fine in IE7 (and Firefox, Chrome, and Safari). I know that IE made some changes to things like Javascript security. Some of these don't give clear error messages - things like cross-domain violations can end up throwing very vague exceptions. Let's mak...
I can verify that the ones posted by "unique\_username" are accurate! (quote) Actually a TON of stuff has changed. First off, it REALLY matters what mode you are in. In IE8, there are 3 (THREE) modes. * IE5 Quirks - your page has no doctype, page renders like IE5 did * IE 7 Standards Mode - you have a doctype, but e...
Here's a REALLY fun one (/sarcasm off) that I discovered. If you have a MIME type of "application/javascript", rather than "text/javascript" Internet Explorer will: A) ignore the unexpected MIME type and use the file anyway? B) not load the file at all? C) take the first hundred or so lines of the file, prepend them...
What are the most likely causes of Javascript errors in IE8?
[ "", "javascript", "internet-explorer", "internet-explorer-8", "" ]
Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same. E.g: ``` a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid ``` Whats the best way to go about doing that? FYI, i don't know how many strings are going to be in the list...
Use list.count to get the number of items in a list that match a value. If that number doesn't match the number of items, you know they aren't all the same. ``` if a.count( "foo" ) != len(a) ``` Which would look like... ``` if a.count( a[0] ) != len(a) ``` ...in production code.
Perhaps ``` all(a[0] == x for x in a) ``` is the most readable way.
Comparing List of Arguments to it self?
[ "", "python", "" ]
I have a C# method that projects the value of a number from an interval to a target interval. **For example:** we have an interval of -1000 and 9000 and a value of 5000; if we want to project this value to an interval of 0..100 we get 60. Here is the method: ``` /// <summary> /// Projects a value to an interval /...
Just maths. What you're "projecting" is a normalisation of ranges A-B and A'-B' such that: ratio r = (x-A) / (B-A) = (y-A') / (B'-A') which using your terms is: (val-min) / (max-min) = (returnValue-intervalBottom) / (intervalTop-intervalBottom) which solves for returnValue as: ``` returnValue = ((intervalTop-inte...
Only thousands of values? Do you really need to optimise this further? I can't imagine it's actually a bottleneck at the moment. Have you profiled the app to check that this is really an issue? Given that the method is O(1), you're not going to make the most drastic kind of optimisation you normally aim at - improving...
Make C# algorithm more efficient
[ "", "c#", "algorithm", "performance", "" ]
I have the VS2005 standard edition and MS says this: > Note: The Windows Service Application > project templates and associated > functionality are not available in the > Standard Edition of Visual Basic and > Visual C# .NET... Is it possible to write a Windows Service application without upgrading my VS2005 Standard...
If you can cut and paste, an example is enough. A simple service to periodically log the status of another service. The example does not include the [ServiceInstaller class](http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx) (to be called by the install utility when installing a servi...
Yes, look here: <http://www.codeproject.com/KB/system/WindowsService.aspx>
Windows Service without the VS2005 template
[ "", "c#", "windows-services", "" ]
I am extending a template class using C++ in Visual Studio 2005. It is giving me an error when I try to extend the template base class with: ``` template <class K, class D> class RedBlackTreeOGL : public RedBlackTree<K, D>::RedBlackTree // Error 1 { public: RedBlackTreeOGL(); ~RedBlackTreeOGL(); ``` and a secon...
The code is trying to inherit a constructor, not a class :-) The start of the class declaration should be ``` template <class K, class D> class RedBlackTreeOGL : public RedBlackTree<K, D> ```
OMG, I feel so silly..... been looking at my own code for far too long! Thats a pretty basic thing and I dont know how i missed it! Thank you James (and SDX2000) this worked by taking the "constructor" off the end of the declaration to what James said. Thank you :)
How do I resolve: "error C2039: '{ctor}' : is not a member of" in Visual Studio 2005?
[ "", "c++", "visual-studio-2005", "templates", "class-design", "visual-c++-2005", "" ]
Can someone share a simple example of using the `foreach` keyword with custom objects?
Given the tags, I assume you mean in .NET - and I'll choose to talk about C#, as that's what I know about. The `foreach` statement (usually) uses `IEnumerable` and `IEnumerator` or their generic cousins. A statement of the form: ``` foreach (Foo element in source) { // Body } ``` where `source` implements `IEnum...
(I assume C# here) If you have a list of custom objects you can just use the foreach in the same way as you do with any other object: ``` List<MyObject> myObjects = // something foreach(MyObject myObject in myObjects) { // Do something nifty here } ``` If you want to create your own container you can use the yi...
How to use foreach keyword on custom Objects in C#
[ "", "c#", "foreach", "" ]
I've got a test class in a module that extends another test class in one of its dependency modules. How can I import the dependency's test code into the test scope of the dependent module? To illiterate, I've got two modules, "module-one" being a dependency of "module-two". `SubTestCase` is a subclass of `TestCase`. ...
Usually this is solved by building and deploying modulename-test.jar files in addition to the regular modulename.jar file. You deploy these to repos like regular artifacts. This is not totally flawless, but works decently for code artifacts. Then you would add test scoped dependencies to the test-jars to other modules...
You can deploy the test code as an additional artifact by using the [maven-jar-plugin's test-jar goal](http://maven.apache.org/plugins/maven-jar-plugin/test-jar-mojo.html). It will be attached to the project and deployed with the classifier tests. ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <art...
Test class extending test class in dependency module
[ "", "java", "maven-2", "" ]
I want to use a signals/slots library in a project that doesn't use QT. I have pretty basic requirements: 1. Connect two functions with any number of parameters. 2. Signals can be connected to multiple slots. 3. Manual disconnection of signal/slot connection. 4. Decent performance - the application is frame-based (i.e...
First, try with boost::signal anyway. Don't assume it will not be fast enough until you try in your specific case that is your application If it's not efficient enough, maybe something like [FastDelegate](http://www.codeproject.com/KB/cpp/FastDelegate.aspx) will suit your needs? (i did'nt try it but heard it was a nic...
[Very, very fast event library](http://www.gamedev.net/topic/456646-very-very-fast-event-library) on Gamedev.net forms > When profiling some code I'd been > working on recently, I was surprised > and dismayed to see boost::signals > functions floating to the top. For > those of you who are unaware, > boost::signals is...
Which C++ signals/slots library should I choose?
[ "", "c++", "boost", "signals-slots", "" ]
I have the following in a page e.g. `/mypage?myvar=oldvalue` ``` $_SESSION['myvar'] = $_GET['myvar']; $myvar = 'a_new_string' ``` Now `$_SESSION['myvar']` has the value `'a_new_string'` Is this by design? How can I copy the *value* of `'myvar'` rather than a reference to it?
register\_globals is the invention of the devil. Fortunately in PHP 6.0 it will be entirely disabled. It wasn't just a huge security problem, it makes people confuse. Please turn it off in your php.ini using register\_globals = Off More information: <https://www.php.net/register_globals> Also you can check the current ...
It's a feature not a bug :-) luckily you can turn it off, set [register\_globals = off](http://www.php.net/register_globals) in your php.ini
Mutability and Reference of PHP5 GET Variables
[ "", "php", "variables", "" ]
I have a few huge tables on a production SQL 2005 DB that need a schema update. This is mostly an addition of columns with default values, and some column type change that require some simple transformation. The whole thing can be done with a simple "SELECT INTO" where the target is a table with the new schema. Our te...
We have a similar problem and I've found that the fastest way to do it is to export the data to delimited files (in chunks - depending on the size of the rows - in our case, each file had 500,000 rows), doing any transforms during the export, drop and recreate the table with the new schema, and then do a bcp import fro...
Are you applying indexes immediately, or in a secondary step? Should go much faster without indexing during the build.
Best way to update table schema for huge tables (SQL Server)
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
How to change text encoded in ANSEL to UTF-8 in C#?
This is a non-trivial conversion as Windows/.NET Framework does not have an ANSEL codepage. See [here](http://www.heiner-eichmann.de/gedcom/charintr.htm) for the travails of another person attempting this conversion.
Joshperry is correct. Eichmann's site has basically the ONLY documentation around that attempts to explain ANSEL encoding. Unfortunately there is no program code there, so you'll have to code it yourself. There is another code table (dated Dec 2007 - I didn't know anyone was still interested) for ANSEL at: <http://lcw...
How to convert ANSEL text to UTF-8
[ "", "c#", "encoding", "" ]
I've a HTML page with several Div's that will show the time difference between now and each given date. ``` <div class="dated" onEvent="calculateHTML(this, 'Sat Jun 09 2007 17:46:21')"> 30 Minutes Ago</div> ``` I want that time difference to be dynamic (calculated to all elements when the page loads and also within a...
Using innerHTML works most (all?) of the time and may frequently be faster than generating a bunch of HTML (i.e. not in this case). I always prefer using standard methods as shown below, because I know they should never break. [Note that I don't check the 'class' attribute directly, since an element may have multiple ...
You can simplify your life with the use of a library like jQuery. This library allows you to select all elements with a particular class and apply a function to each one. It also can be made to wait until the DOM is fully loaded before executing. Like this: ``` $(document).ready(function(){ $(".dated").each(functi...
The best way to change the innerHTML of a certain type of Elements
[ "", "javascript", "" ]
**Let's share Java based web application architectures!** There are lots of different architectures for web applications which are to be implemented using Java. The answers to this question may serve as a library of various web application designs with their pros and cons. While I realize that the answers will be subj...
Ok I'll do a (shorter) one: * Frontend : [Tapestry](https://tapestry.apache.org/index.html) (3 for older projects, 5 for newer projects) * Business layer: Spring * DAO's : Ibatis * Database : Oracle We use Sping transaction support, and start transactions upon entering the service layer, propagating down to the DAO c...
**Ideal Java Based Web Development Technologies Today.** # Web Layer : HTML+CSS+Ajax+JQuery # RESTFul Web Controller/Action/Request Processing Layer : Play Framework # Business Logic/Service Layer: Use Pure Java Code as long as possible. One can do fusion of web services here. # XML/JSon Data Transformation Laye...
Describe the architecture you use for Java web applications?
[ "", "java", "architecture", "jakarta-ee", "" ]
I started with [jetlang](http://code.google.com/p/jetlang/) and the basic samples are pretty clear. What I didn't found is a good sample for using the PoolFiber. Anybody played around with that already? I read also the retlang samples but it seems little bit different there. Thanks for sharing your thoughts! Okami
Using a PoolFiber and ThreadFiber are nearly the same. The only difference is that the thread pool needs to initialized and used for creating each PoolFiber. ``` // create java thread pool. ExecutorService pool = Executors.newCachedThreadPool(); //initialize factory with backing pool PoolFiberFactory fiberFactory = ne...
Here it is on Github. <https://github.com/jetlang/jetlang/blob/readme/src/test/java/org/jetlang/examples/BasicExamples.java> Here's the mvn site <http://jetlang.github.io/jetlang/>
Jetlang PoolFiber sample
[ "", "java", "concurrency", "" ]
I need to bind labels or items in a toolstrip to variables in Design Mode. I don't use the buit-in resources not the settings, so the section Data is not useful. I am taking the values out from an XML that I map to a class. I know there are many programs like: <http://www.jollans.com/tiki/tiki-index.php?page=Multilang...
Aleksandar's response is one way to accomplish this, but in the long run it's going to be very time consuming and won't really provide much benefit. The bigger question that should be asked is why do you not want to use the tools and features built-in to .NET and Visual Studio or at least use a commercial third-party t...
Try with inheriting basic win controls and override OnPaint method. Example bellow is a button that has his text set on paint depending on value contained in his Tag property (let suppose that you will use Tag property to set the key that will be used to read matching resource). Then you can find some way to read all c...
Localization for Winforms from designmode?
[ "", "c#", "winforms", "localization", "" ]
Code like this often happens: ``` l = [] while foo: # baz l.append(bar) # qux ``` This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements. In Java, you can create an ArrayList with an initial capacity. If you...
## Warning: This answer is contested. See comments. ``` def doAppend( size=10000 ): result = [] for i in range(size): message= "some unique object %d" % ( i, ) result.append(message) return result def doAllocate( size=10000 ): result=size*[None] for i in range(size): messag...
Python lists have no built-in pre-allocation. If you really need to make a list, and need to avoid the overhead of appending (and you should verify that you do), you can do this: ``` l = [None] * 1000 # Make a list of 1000 None's for i in xrange(1000): # baz l[i] = bar # qux ``` Perhaps you could avoid th...
Create a list with initial capacity in Python
[ "", "python", "list", "dictionary", "initialization", "" ]
For a WPF application which will need 10 - 20 small icons and images for illustrative purposes, is storing these in the assembly as embedded resources the right way to go? If so, how do I specify in XAML that an Image control should load the image from an embedded resource?
If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all `Image` elements. To do this, create a [`BitmapSource`](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx) as a resource somewhere: ``` <Bitma...
I found to be the best practice of using images, videos, etc. is: * Change your files **"Build action"** to **"Content"**. Be sure to check *Copy to build directory*. + Found on the "Right-Click" menu at the Solution Explorer window. * *Image Source* in the following format: + **"/*«YourAssemblyName»*;component/«Y...
Storing WPF Image Resources
[ "", "c#", ".net", "wpf", "embedded-resource", "" ]
How do I select the unique elements from the list `{0, 1, 2, 2, 2, 3, 4, 4, 5}` so that I get `{0, 1, 3, 5}`, effectively removing *all instances of* the repeated elements `{2, 4}`?
``` var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 }; var uniqueNumbers = from n in numbers group n by n into nGroup where nGroup.Count() == 1 select nGroup.Key; // { 0, 1, 3, 5 } ```
``` var nums = new int{ 0...4,4,5}; var distinct = nums.Distinct(); ``` make sure you're using Linq and .NET framework 3.5.
Selecting unique elements from a List in C#
[ "", "c#", "list", "unique", "" ]
I have been using the partial class modifier for some time in order to put helper classes in their own file. Today we got a new guy and he said that the last team he worked with didn't allow partial classes for this because modifying a helper class that is in a separate file would cause the main partial class file to ...
Partial classes are *primarily* for code-generator usage, such as designers - but I use the approach you have cited - in particular when an object implements multiple (non-trivial) interfaces, I find it useful to break it up 1 file per interface implementation. I also commonly have a file for the static methods, which ...
Personally I can't see anything wrong with using partial classes like this, but that's just my own opinion. The only thing that might seem like "bad practice" is to name your classes "Helper1" and "Helper2" (but that might be an example only for clarification). If you're using partial classes like this, check out the ...
Best Practices: When not/to use partial classes
[ "", "c#", "coding-style", "partial-classes", "" ]
I am developping in C#. I need to capture a password written inside a Text Box, but would like to not show the password that is being typed, showing instead \*\*\*\* or any other character to hide the password. How can I do that? I'm sure it's by modifying an attribute, but can't find which one.
<http://msdn.microsoft.com/en-us/library/d3223ht2.aspx> set the PasswordChar property of the textbox
Set the [`PasswordChar` property](http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.passwordchar.aspx).
How to show a text as hidden using c#
[ "", "c#", "" ]
I have a simple problem when querying the SQL Server 2005 database. I have tables called Customer and Products (1->M). One customer has most 2 products. Instead of output as CustomerName, ProductName ... I like to output as CustomerName, Product1Name, Product2Name ... Could anybody help me? Thanks!
Like others have said, you can use the PIVOT and UNPIVOT operators. Unfortunately, one of the problems with both PIVOT and UNPIVOT are that you need to know the values you will be pivoting on in advance or else use dynamic SQL. It sounds like, in your case, you're going to need to use dynamic SQL. To get this working ...
Here two link about pivot: <http://www.tsqltutorials.com/pivot.php> <http://www.simple-talk.com/sql/t-sql-programming/creating-cross-tab-queries-and-pivot-tables-in-sql/> I solve my problem with pivot ;)
How to transform rows to columns
[ "", "sql", "sql-server", "" ]
When parsing HTML for certain web pages (most notably, any windows live page) I encounter a lot of URL’s in the following format. http\x3a\x2f\x2fjs.wlxrs.com\x2fjt6xQREgnzkhGufPqwcJjg\x2fempty.htm These appear to be partially UTF8 escaped strings (\x2f = /, \x3a=:, etc …). Is there a .Net API that can be used to tra...
What you posted is not valid HTTP. As such, of course `HttpUtility.UrlDecode()` won't work. But irrespective of that, you can turn this back into normal text like this: ``` string input = @"http\x3a\x2f\x2fjs.wlxrs.com\x2fjt6xQREgnzkhGufPqwcJjg\x2fempty.htm"; string output = Regex.Replace(input, @"\\x([0-9a-f][0-9a-f]...
here is another solution : (as continued from @timwi solution) ``` string output = Regex.Replace(input, @"\\x([0-9a-f][0-9a-f])", m => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString()); ```
Finding a parsing API for partially utf8 encoded URL's
[ "", "c#", ".net", "uri", "" ]
I want to check whether the user is viewing my site from a mobile device or PC. If it's a mobile device, I want to redirect my site URL like Google does... If possible I would like to implement this in JavaScript. How can I do this?
See this [existing question](https://stackoverflow.com/questions/142273/standard-way-to-detect-mobile-browsers-in-a-web-application-based-on-the-http-r "Standard way to detect mobile browsers..."). You will have better luck doing this server side, as many mobile browsers don't even support JavaScript. Basically you wa...
You typically use the User-Agent header to detect the browser. Here's JavaScript code that does basically that (only for mainstream browsers though, you'd have to add the Mobile User-Agents) <http://www.quirksmode.org/js/detect.html> And here's a list of mobile browser identifiers <http://www.zytrax.com/tech/web/mo...
How can I redirect mobile devices to a different URL?
[ "", "javascript", "browser", "mobile", "" ]
On the web page, it looks like there is no current development in the old style .doc. * Is it good enough to create complex documents? * Can it read all .docs without crashing? * What features do (not) work? I am not currently interested in the XML based formats, as I don't control the client side. The excel support...
If you are looking for programmatically reading or writing doc files, I believe you're better of with remoting OpenOffice or StarOffice. We've done this at a former company, even though it's a pretty heavy solution, it worked quite well. OpenOffice has (right after Word) a very good doc-Support. For remoting it's a lot...
It dependes by your goal. I code with POI for report in Excel format and it's ok for simple report, because there'a a lot of code for simple operation. I coded some utility methods for repeating task. If you code for java =>1.5 you try JXLS (what extends POI and use XML/XSLT technologies).
How good is Apache POI word support?
[ "", "java", "apache", "ms-word", "ms-office", "" ]
In my Symbian S60 application, my Options menu works as expected. But the Exit button does nothing. I am developing with Carbide and have used the UI Designer to add items to the options menu. Does anyone know how to enable the exit button, or why else it might not work? Thanks!
Are you handling (in your `appui::HandleCommandL`) command ids `EEikCmdExit` and `EAknSoftkeyExit?` ``` if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit ) { Exit(); } ```
Have you looked inside the `HandleCommandL( TInt aCommand )` method of the `AppUi` class of your application? For example, in all UI projects I create with Carbide, the following is automatically present inside the `HandleCommandL()` method: ``` void MyAppUi::HandleCommandL( TInt aCommand ) { TBool commandHandled ...
S60 application - Symbian C++ - Exit button doesn't work
[ "", "c++", "symbian", "exit", "s60", "carbide", "" ]
I am looking for a tool/framework to (automatically) generate a Swing user interface to perform CRUD operations on an underlying database. I would also like to configure the database fields that should be exposed. Something like django (via [modelforms](http://docs.djangoproject.com/en/dev/topics/forms/modelforms)) or...
NetBeans does seem like an obvious answer. These guys make a NetBeans plugin that does just that: <http://www.morelisland.com/java_services/netbeans_tutorial/midbmetadata_se.htm> I've heard jgoodies does something similar: <http://www.jgoodies.com/products/index.html> And more specifically their sub-project, Binding:...
Have a look at tools like: MetaWidget <http://www.metawidget.org/> [Apache Isis](http://isis.apache.org/) They generate UI's "on-the-fly" but allow you to customise the UI when necessary. Much better than code generation.
Is there a tool or framework to Generate a CRUD UI in Swing?
[ "", "java", "swing", "user-interface", "crud", "" ]