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, Form frm)
{
frm.TopLevel = false;
frm.FormBorderStyle = FormBorderStyle.None;
frm.Dock = DockStyle.Fill;
frm.Visible = true;
ctl.Controls.Add(frm);
}
```
I have that in a Class Library and then I call it like so from the FORM I want to embed.
```
public FrmCaseNotes FrmCaseNotes;
FrmCaseNotes = new FrmCaseNotes();
WinFormCustomHandling.ShowFormInContainerControl(tpgCaseNotes, FrmCaseNotes);
```
Where `tpgCaseNotes` is the control I want Form `FrmCaseNotes` embedded in.
In this case a tab page on the Form I am calling from. | 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());
}
```
Unfortunately, I cannot do it using .NET 2.0 and C# 2.0. | 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 you could just do:
```
public void MyMethod(){
Func<int, int, int> mySumImplementation =
delegate (int a, int b) { return a+b; };
Console.WriteLine(mySumImplementation(1,1).ToString());
}
```
The declarations are on my [C#/.NET Versions page](http://csharpindepth.com/Articles/Chapter1/Versions.aspx). | 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(1,1).ToString());
}
}
```
would be valid.
The best solution may be to emulate .NET3.5, and create some generic delegate types globally, which can be used all over your solution, to avoid having to constantly redeclare delegate types for everything:
```
delegate R Func<R>();
delegate R Func<T, R>(T t);
delegate R Func<T0, T1, R>(T0 t0, T1 t1);
delegate R Func<T0, T1, T2, R>(T0 t0, T1 t1, T2 t2);
```
Then you can just use a `Func<int, int, int>` delegate in your code above. | 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 = "No";
}
```
For each field, which is tedious and seems like there should be a better way, than using an if clause for each field. If there is, what is it? | 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 can be executed? | [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 of all, no requirement to install *anything* in the system being
tested. No need for xdebug, etc., which means you don't have to argue
with the sysadmin to do your testing.
You can use it with PHPUnit to get unit-test driven coverage. Or you can use it on your website to collect coverage from any functional testing approach/tools you may have. | 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 tool. Syntax is:
```
sn -k c:\keypair.snk
```
2) Use the keypair to strongly name (i.e. sign) your client application. You can set this using the signing tab in the properties page on your application
3) Create a license for your client, this should be an XML document and sign it using your Private key. This involves simply computing a digital signature and steps to accomplish it can be found at:
<http://msdn.microsoft.com/en-us/library/ms229745.aspx>
4) On the client, when checking the license you load the XmlDocument and use your Public key to verify the signature to prove the license has not been tampered with. Details on how to do this can be found at:
<http://msdn.microsoft.com/en-us/library/ms229950.aspx>
To get around key distribution (i.e. ensuring your client is using the correct public key) you can actually pull the public key from the signed assembly itself. Thus ensuring you dont have another key to distribute and even if someone tampers with the assembly the .net framework will die with a security exception because the strong name will no longer match the assembly itself.
To pull the public key from the client assembly you want to use code similar to:
```
/// <summary>
/// Retrieves an RSA public key from a signed assembly
/// </summary>
/// <param name="assembly">Signed assembly to retrieve the key from</param>
/// <returns>RSA Crypto Service Provider initialised with the key from the assembly</returns>
public static RSACryptoServiceProvider GetPublicKeyFromAssembly(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly", "Assembly may not be null");
byte[] pubkey = assembly.GetName().GetPublicKey();
if (pubkey.Length == 0)
throw new ArgumentException("No public key in assembly.");
RSAParameters rsaParams = EncryptionUtils.GetRSAParameters(pubkey);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParams);
return rsa;
}
```
I've uploaded a sample class with a lot of helpful Encryption Utilities on Snipt at: <http://snipt.net/Wolfwyrd/encryption-utilities/> to help get you on your way.
I have also included a sample program at: <https://snipt.net/Wolfwyrd/sign-and-verify-example/>. The sample requires that you add it to a solution with the encryption utils library and provide a test XML file and a SNK file for signing. The project should be set to be signed with the SNK you generate. It demonstrates how to sign the test XML file using a private key from the SNK and then verify from the public key on the assembly.
**Update**
Added an [up to date blog post](http://www.leapinggorilla.com/Blog/Read/1019/signed-xml-licenses) with a nice detailed run through on license files | 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.
It's of course logical that you sign the license file at your own company and send the license file to the customer who then places the license file in a folder for you to read.
Of course, people can cut out/hack your distributed assembly and rip out the xml sign checking, but then again, they will always be able to do so, no matter what you do. | 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, without any pipelining). In fact, I would like one subprocess shell and the ability to launch many commands on it. | 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" separators in a single long string.
Use """s, like this.
```
"""
command1
command2
command3
"""
```
Or, if you must do things piecemeal, you have to do something like this.
```
class Command( object ):
def __init__( self, text ):
self.text = text
def execute( self ):
self.proc= subprocess.Popen( ... self.text ... )
self.proc.wait()
class CommandSequence( Command ):
def __init__( self, *steps ):
self.steps = steps
def execute( self ):
for s in self.steps:
s.execute()
```
That will allow you to build a sequence of commands. | 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 get it back INTO the database I want.
My goal was to transfer the data I had in one rails app to another so I didn't have to take all sorts of time creating dummy data again . . . so I dumped the data from my first app, got rid of all the CREATE TABLE statements, and made sure my schema on my second app matches . . . now I just have to get it IN there.
Would anyone mind helping me out? And when you find a way, will you tell me what you plugged into the google, 'cause I am beating my head open with a spoon right now over what I thought would be an easy find. | ```
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_Action=logout&User_Id=1111">
```
in the tag to automatically log him out.
But I've noticed many users are there for ever, never logged out. I found out why, by closing their browsers, they never manually or automatically logged out, so their user Ids will never be removed from the valid user Ids vector.
So, my question is : how do I detect users closing their browsers, so my servlet can remove their Ids from the vector ?
---
I see some light at the end of the tunnel, but there is still a problem, my program has something like this :
Active User List :
```
User_1 : Machine_1 [ IP_1 address ]
User_2 : Machine_2 [ IP_2 address ]
User_3 : Machine_3 [ IP_3 address ]
...
```
How do I know, from the session listener, which user's session has ended and therefore remove him from my list?
I was hoping when the session ends, the HttpServlet's `destroy()` method would be called and I can remove the user Id in there, but it never gets called when user closes his browser, why? And is there any other method in the HttpServlet that gets called when a session closes? | 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 when a Session has been destroyed (such as due to time-out). Take a look at [this page](http://www.stardeveloper.com/articles/display.html?article=2001112001&page=1) to see how to configure a [`HttpSessionListener`](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSessionListener.html) to receive these events. Then you can simply keep track of the number of active sessions.
The number of active sessions will lag behind the actual number of current users, since some period of (configurable) time has to elapse before a session is timed out; however, this should be somewhat close (you can lower the session-timeout to increase the accuracy) and it is a lot cleaner and easier than 1) tracking Sessions yourself or 2) sending some asynchronous JavaScript to the server when a browser is closed (which is not guaranteed to be sent). | 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-servlet-how-to-detect-browser-closing#299697)'s idea will only help you detect that the session is over more immediately. | 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.Demand() will determine if the user is in the windows group specified by the permissionGroup variable.
```
private static void DemandManagerPermission()
{
// Verify the use has authority to proceed
string permissionGroup = ConfigurationManager.AppSettings["ManagerPermissionGroup"];
if (string.IsNullOrEmpty(permissionGroup))
throw new FaultException("Group permissions not set for access control.");
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
var p = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, permissionGroup, true);
p.Demand();
}
``` | 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 in all the other arrays.
Obviously this is trivial in imperative code:
```
int[] sums = new int[myList[0].Length];
foreach(int[] array in myList)
{
for(int i = 0; i < sums.Length; i++)
{
sums[i] += array[i];
}
}
```
But I was wondering if there was a nice Linq or Enumerable.xxx technique? | 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()
);
```
That's kind of ugly...but I think the statement version would be even worse. | 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(
(value, index) => new { value, index })
.Aggregate(new int[myList[0].Length],
(result, item) => { result[item.index] += value; return result; });
```
I haven't tested it, but I think it should work. I wouldn't recommend it though. The SelectMany flattens all the data into a sequence of pairs - each pair is the value, and its index within its original array.
The Aggregate step is entirely non-pure - it modifies its accumulator as it goes, by adding the right value at the right point.
Unless anyone can think of a way of basically pivoting your original data (at which point my earlier answer is what you want) I suspect you're best off doing this the non-LINQ way. | 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 method in the CMS to do this, because file handling is really a job for the CMS.
Obviously (and I know why), this is bad design and a case of high coupling.
I know a few ways to handle high coupling, like restructuring the project (although I don't really think this is a robust solution), but what else can I do to reduce high coupling? Any simple tips? Also, it would be good to know why/how they reduce coupling. I use .NET 3.5 and Sql Server 2005 so things like JMS (which I keep coming across in my search for tips on this design issue), are not applicable.
Thanks
---
BTW,
One of the reasons I ask this is that I have read the previous questions similar to this but usually if a question that has been asked before is asked again, different tips can be learnt as different people reply to the post.
I know of dependency injection/IOC, but I am interested in the small things that can be done to reduce coupling.
How could I choose between using a static class, or an interface-derived class, or the IOC approach when deciding on *how* to reduce coupling? Also, I could develop a web service which could call a static class - mixing up the approaches in my solution.
The interesting thing is that in my application, I don't want it to be disjointed. So I just have a forum, ecommerce system, and any other module required, but everything has to gel into one site so each module (which is represented as a dedicated project in my Visual Studio solution) needs to know about every other module and work with it. So for example, I might have a module which handles user profiles (working with ASP.NET membership, roles, etc), but this will work with the forum module as a user on the forum will be a registered user on the site (one login throughout), and his or her profile will be coming from the user profile module. This is as opposed to seperate profiles as seen on other sites I've come across). | 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 some infrastructre assemblies along the way, but again - they should be considered more stable than the assemblies dependent on them.
I'd guess your App.ECommerce and App.Cms assemblies are more siblings than layers - so you would not want those to depend on each other, but that doesn't mean you can't reuse functionality. For your particular scenario, you need to push the needed functionality down to a Core or Utilities assembly that both ECommerce and Cms can depend on. If it's a specific implementation that ECommerce provides, then you can push an interface or abstract base class to the Core - and have a higher layer (perhaps IoC container) wire up the concrete Cms.FileCreator class to the ECommerce.IFileCreator dependency. | 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's my code:
```
for(var i in DisplayGlobals.Indicators)
{
var div = d.createElement("div");
div.style.width = "100%";
td.appendChild(div);
for(var j = 0;j<3;j++)
{
var test = j;
if(DisplayGlobals.Indicators[i][j].length > 0)
{
var img = d.createElement("img");
jQuery(img).attr({
src : DisplayGlobals.Indicators[i][j],
alt : i,
className: "IndicatorImage"
}).click(
function(indGroup,indValue){
jQuery(".IndicatorImage").removeClass("active");
_this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];
_this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
jQuery(this).addClass("active");
}(i,j)
);
div.appendChild(img);
}
}
}
```
I've tried a couple of different ways without success...
The original problem was that \_this.Indicator.TrueImage was always the last value because I was using the loop counters rather than parameters to choose the right image. | 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[indGroup][indValue];
_this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
jQuery(this).addClass("active");
}
}(i,j);
);
``` | 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}, function(event) {
alert(event.data.indGroup);
alert(event.data.indValue);
...
});
```
Looks much simpler and probably more efficient (one less closure per iteration).
Documentation for [bind](http://api.jquery.com/bind/) method has description and some examples on event data. | 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="${param1 + param2}"/>
</jsp:useBean>
```
Of course this won't work because Integer objects don't have a property named 'amount', the only way their value can be set is via a constructor parameter (i.e. Integer objects are immutable). Is there any way to instantiate such an object and set it's value without using scriptlet code?
Thanks,
Don | **`<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 + param2);
%>
```
And then just using <%= total %> where you need the value to be output. You could also do:
```
<%
pageContext.setAttribute("total", new Integer(param1 + param2));
%>
```
if you want the value to be in the page scope like useBean will do. | 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 FROM bookSession WHERE session='"&theCookie&"'"
'--Connect to DB'
Set objConn = ConnectDB()
'--Query to DB'
Set objRS = objConn.Execute(query)
custID = objRS.Fields("custID")
query = "SELECT billingID FROM bookBilling WHERE custID="&custID&""
objConn.Execute(query)
```
Here is where it becomes an issue. I tried using this to obtain the value:
```
billingID = objRS.Fields("billingID")
```
When that didn't work I printed the query to my browser to make sure it worked and it came back good, I checked it in SQL Server Management Studio to make sure. After that I decided to play with it a bit and found that using "0" as the reference works since it is the first item in my table.
```
billingID = objRS.Fields(0)
```
So that worked, I know my table column header is correct I have looked at it and used it in other queries before. Does anyone know why this might happen? Is it a result of not clearing my connection or closing it afterward?
Thanks | 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 the query.execute to it after, rather than the initial all in one with the first CustId query | 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 cookie value directly in your query like that there is the potential for sql injection. It's not the normal attack vector, but it's still possible.
As to your specific error, you execute the 2nd query directly from the connection rather than opening it in the record set:
```
objConn.Execute(query)
```
I'm surprised you get anything at all, and I expect the value you're seeing in `objRS.Fields(0)` is probably just the `custID` from the previous query. But that all becomes moot if you consolidate the queries like I recommended. | 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 are downloaded? | 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: 50px; right: 50px; top: 50px; bottom: 50px; border: 3px solid black;"
id="loading-div"
>
This page is loading! Be patient!
</div>
... Your body content ...
</body>
</html>
```
Contents of clear-load.js:
```
document.getElementById('loading-div').style.display = 'none';
```
Of course, you could also tack the javascript code that hides the div at the bottom of the last javascript file that's loaded.
Also, try to pack your javascript and css files into one file and apply gzip compression or "minify" to them. You can bring 500KB of javascript in 20 requests to 1 request of less than 100KB if you do it right. | 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 the backcolor of the Panel the same when the mouse is in its area without the other controls inside affecting it? | 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 control, you can still use MousePosition and PointToScreen to determine if the mouse is still within the bounds of the control.
```
private void panel1_MouseLeave(object sender, EventArgs e)
{
Rectangle screenBounds = new Rectangle(this.PointToScreen(panel1.Location), panel1.Size);
if (!screenBounds.Contains(MousePosition))
{
panel1.BackColor = Color.Gray;
}
}
``` | 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 replacing `==` with `===`?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over `==`? | 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 `==` operator will compare for equality *after doing any necessary type conversions*. The `===` operator will **not** do the conversion, so if two values are not the same type `===` will simply return `false`. Both are equally quick.
To quote Douglas Crockford's excellent [JavaScript: The Good Parts](https://rads.stackoverflow.com/amzn/click/com/0596517742),
> JavaScript has two sets of equality operators: `===` and `!==`, and their evil twins `==` and `!=`. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then `===` produces `true` and `!==` produces `false`. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
> ```
> '' == '0' // false
> 0 == '' // true
> 0 == '0' // true
> ```
> ```
> false == 'false' // false
> false == '0' // true
> ```
> ```
> false == undefined // false
> false == null // false
> null == undefined // true
> ```
> ```
> ' \t\r\n ' == 0 // true
> ```
[](https://i.stack.imgur.com/yISob.png)
> The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use `===` and `!==`. All of the comparisons just shown produce `false` with the `===` operator.
---
### Update
A good point was brought up by [@Casebash](https://stackoverflow.com/users/165495/casebash) in the comments and in [@Phillipe Laybaert's](https://stackoverflow.com/users/113570/philippe-leybaert) [answer](https://stackoverflow.com/a/957602/1288) concerning objects. For objects, `==` and `===` act consistently with one another (except in a special case).
```
var a = [1,2,3];
var b = [1,2,3];
var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };
var e = "text";
var f = "te" + "xt";
a == b // false
a === b // false
c == d // false
c === d // false
e == f // true
e === f // true
```
The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its `toString` or `valueOf` method. For example, consider the comparison of a string primitive with a string object created using the `String` constructor.
```
"abc" == new String("abc") // true
"abc" === new String("abc") // false
```
Here the `==` operator is checking the values of the two objects and returning `true`, but the `===` is seeing that they're not the same type and returning `false`. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the `String` constructor to create string objects from string literals.
**Reference**
<https://262.ecma-international.org/5.1/#sec-11.9.3> | ### 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 `==` does type coercion**, meaning that the interpreter implicitly tries to convert the values before comparing.
On the other hand, the **identity operator `===` does not do type coercion**, and thus does not convert the values when comparing. | 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 = firstName;
this.LastName = lastName;
}
}
class List1
{
public List<Person> l1 = new List<Person>();
public List1()
{
l1.Add(new Person("f1","l1"));
l1.Add(new Person("f2", "l2"));
l1.Add(new Person("f3", "l3"));
l1.Add(new Person("f4", "l4"));
l1.Add(new Person("f5", "l5"));
}
public IEnumerable<Person> Get()
{
foreach (Person p in l1)
{
yield return p;
}
//return l1.AsReadOnly();
}
}
class Program
{
static void Main(string[] args)
{
List1 list1Instance = new List1();
List<Person> p = new List<Person>(list1Instance.Get());
UpdatePersons(p);
bool sameFirstName = (list1Instance.l1[0].FirstName == p[0].FirstName);
}
private static void UpdatePersons(List<Person> list)
{
list[0].FirstName = "uf1";
}
}
```
Can we change this behavior with out changing the return type of `List1.Get()`?
Thanks | 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.e. a `class`), you can alter its members through the reference.
There are two solutions:
* Use a `struct` as the return type (that makes a copy of the value each time it's returned, so the original value will not be altered — which can be costly, by the way)
* Use read only properties on the `Person` type to accomplish this task. | 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)
{
yield return p.Clone();
}
}
``` | 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 some other way to unload the DLL? | 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 provide a clean way to release resources, it does only provide a `_handle` field to the dlopen handle...
So the only way I see, a really, **really non-clean way**, is to system dependently dlclose the handle, but it is very very unclean, as moreover ctypes keeps internally references to this handle. So unloading takes something of the form:
```
mydll = ctypes.CDLL('./mylib.so')
handle = mydll._handle
del mydll
while isLoaded('./mylib.so'):
dlclose(handle)
```
It's so unclean that I only checked it works using:
```
def isLoaded(lib):
libp = os.path.abspath(lib)
ret = os.system("lsof -p %d | grep %s > /dev/null" % (os.getpid(), libp))
return (ret == 0)
def dlclose(handle)
libdl = ctypes.CDLL("libdl.so")
libdl.dlclose(handle)
``` | 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++ -c -DBUILDING_EXAMPLE_DLL test.cpp')
call('g++ -shared -o test.dll test.o -Wl,--out-implib,test.a')
import ctypes
import numpy
# Simplest way to load the DLL
mydll = ctypes.cdll.LoadLibrary('test.dll')
# Call a function in the DLL
print mydll.test(10)
# Unload the DLL so that it can be rebuilt
libHandle = mydll._handle
del mydll
ctypes.windll.kernel32.FreeLibrary(libHandle)
```
I don't know much of the internals so I'm not really sure how clean this is. I think that deleting mydll releases the Python resources and the FreeLibrary call tells windows to free it. I had assumed that freeing with FreeLibary first would have produced problems so I saved a copy of the library handle and freed it in the order shown in the example.
I based this method on [ctypes unload dll](https://stackoverflow.com/questions/13128995/ctypes-unload-dll) which loaded the handle explicitly up front. The loading convention however does not work as cleanly as the simple "ctypes.cdll.LoadLibrary('test.dll')" so I opted for the method shown. | 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)
{
std::vector<int>::iterator iter = myNumbers_in.begin();
std::vector<int>::iterator endIter = myNumbers_in.end();
for(; iter != endIter; ++iter)
{
if(*iter == number_in)
{
myNumbers_in.erase(iter);
}
}
}
int main(int argc, char* argv[])
{
std::vector<int> myNmbers;
for(int i = 0; i < 2; ++i)
{
myNmbers.push_back(i);
myNmbers.push_back(i);
}
erase(myNmbers, 1);
return 0;
}
```
This code obviously crashes because I am changing the end of the vector while iterating through it. What is the best way to achieve this? I.e. is there any way to do this without iterating through the vector multiple times or creating one more copy of the vector? | 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 to C++20, use the [erase-remove idiom](https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom):
```
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
// or
vec.erase(std::remove_if(vec.begin(), vec.end(), [&](int x) {
return x == number_in;
}), vec.end());
```
What happens is that `std::remove` compacts the elements that differ from the value to be removed (`number_in`) in the beginning of the `vector` and returns the iterator to the first element after that range. Then `erase` removes these elements (whose value is unspecified). | 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);
}
else
{
++iter;
}
}
}
```
Or you could use [std::remove\_if](https://en.cppreference.com/w/cpp/algorithm/remove) together with a functor and std::vector::erase:
```
struct Eraser
{
Eraser(int number_in) : number_in(number_in) {}
int number_in;
bool operator()(int i) const
{
return i == number_in;
}
};
std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());
```
Instead of writing your own functor in this case you could use [std::remove](https://en.cppreference.com/w/cpp/algorithm/remove):
```
std::vector<int> myNumbers;
myNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());
```
In C++11 you could use a lambda instead of a functor:
```
std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());
```
In C++17 [std::experimental::erase](https://en.cppreference.com/w/cpp/experimental/vector/erase_if) and [std::experimental::erase\_if](https://en.cppreference.com/w/cpp/experimental/vector/erase_if) are also available, in C++20 these are (finally) renamed to [std::erase](https://en.cppreference.com/w/cpp/container/vector/erase2) and [std::erase\_if](https://en.cppreference.com/w/cpp/container/vector/erase2) (*note: in Visual Studio 2019 you'll need to change your C++ language version to the latest experimental version for support*):
```
std::vector<int> myNumbers;
std::erase_if(myNumbers, Eraser(number_in)); // or use lambda
```
or:
```
std::vector<int> myNumbers;
std::erase(myNumbers, number_in);
``` | 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 like to do a
```
Server.Transfer( LinkHolder.Link )
```
on the corresponding Link.
I am unsure what is the best/most correct way to do this. Any hints would be appreciated. | 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 Hyperlinks instead of having to use Server.Transfer? | 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: The reason for the communication is that the modules use some shared functionality, and we want to locate this functionality in only one place, since it requires a significant amount of resources. Also, this requires synchronous communication. | 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, you could have the centralized logging service that has its own logging configuration and lets you manage this in a single place. In this case, you need to share the service.
You can share the library by placing the jar inside each war or inside the ear.
You can share the service by being the service client. So, your web services can use another service. In that case, one web service is a client of another, achieving service composition (a common pattern in enterprise development)
If both service client and service itself reside inside the same ear, than you might avoid some overhead by calling the service “directly”, for example using the Spring’s parent context feature:
<http://springtips.blogspot.com/2007/06/using-shared-parent-application-context.html>
but I would advise against flattening the service because you will loose different benefits that having service in the first place provides like governance, manageability etc. | 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.
If there is stateful code in both web projects that need to be updated, then your only option is to make a call to the servlet for the web project (assuming the stateful code is contained within the web project).
Just remember that the shared resource must be threadsafe.
Similar question [here](https://stackoverflow.com/questions/334425/different-war-files-shared-resources#334443). | 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 below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic.
Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.
```
longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
``` | 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 Beautiful Soup Tag objects. Also, this version doesn't assume anything about the lengths of the two rows.
```
def merge3( row1, row2 ):
i1= 0
i2= 0
result= []
while i1 != len(row1) or i2 != len(row2):
if i1 == len(row1):
result.append( ' '.join(row1[i1].contents) )
i2 += 1
elif i2 == len(row2):
result.append( ' '.join(row2[i2].contents) )
i1 += 1
else:
if row1[i1]['colspan'] < row2[i2]['colspan']:
# Fill extra cols from row1
c1= row1[i1]['colspan']
while c1 != row2[i2]['colspan']:
result.append( ' '.join(row2[i2].contents) )
c1 += 1
elif row1[i1]['colspan'] > row2[i2]['colspan']:
# Fill extra cols from row2
c2= row2[i2]['colspan']
while row1[i1]['colspan'] != c2:
result.append( ' '.join(row1[i1].contents) )
c2 += 1
else:
assert row1[i1]['colspan'] == row2[i2]['colspan']
pass
txt1= ' '.join(row1[i1].contents)
txt2= ' '.join(row2[i2].contents)
result.append( txt1 + " " + txt2 )
i1 += 1
i2 += 1
return result
``` | 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):
def __init__(self, header):
self.longHeader = header
self.combinedHeader = []
self.longHeaderCount = 0
def combine(self, shortValue):
self.combinedHeader.append(
[self.longHeader[self.longHeaderCount]+' '+shortValue] )
self.longHeaderCount += 1
return self.longHeaderCount
def main():
longHeader = [
'','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader = [
'','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
sumSpanLong=0
sumSpanShort=0
combiner = collector(longHeader)
for sLen,sHead in zip(spanShort,shortHeader):
sumSpanLong += spanLong[combiner.longHeaderCount]
sumSpanShort += sLen
while sumSpanShort - sumSpanLong > 0:
combiner.combine(sHead)
sumSpanLong += spanLong[combiner.longHeaderCount]
combiner.combine(sHead)
return combiner.combinedHeader
``` | 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 make a class immutable ? | 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 collection, either return a copy or a read-only version (for example, using [ArrayList.ReadOnly](http://msdn.microsoft.com/en-us/library/system.collections.arraylist.readonly.aspx) or similar - you can combine this with the previous point and *store* a read-only copy to be returned when callers access it), return an enumerator, or use some other method/property that allows read-only access into the collection
* keep in mind that you still may have the appearance of a mutable class if any of your members are mutable - if this is the case, you should copy away whatever state you will want to retain and avoid returning entire mutable objects, unless you copy them before giving them back to the caller - another option is to return only immutable "sections" of the mutable object - thanks to @Brian Rasmussen for encouraging me to expand this point | 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).AsReadOnly();
}
public IList<MyType> MyReadOnlyList
{
get { return _myReadOnlyList; }
}
private IList<MyType> _myReadOnlyList
}
``` | 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() {
// ...
}
@Override
public abstract void doX();
}
Class C extends B {
@Override
public void doX() {
// ...
}
}
Class D extends B {
@Override
public void doX() {
// ...
}
}
```
My code works as expected, but I have a few questions:
* Should I declare the abstract Method doX() in Class B? Why (not)?
* Should I also explicitly declare "implements A" on Class C and D? Why (not)? | 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{
public void doX() {
// ...
}
}
```
You shouldn't mix the interface (signature of methods) with the implementation. | * 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 - because your superclass (Abstract base class) implements that interface, your concrete subclasses will be guaranteed to implement that interface. | 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:

We are using windows authentication and I think it has authenticated us as the "site settings" button is appearing and we can alter site security, add to roles etc.
I have had this before and cant remember how I fixed it.
Any ideas?
Thanks,
Alex | 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", "school", "to", "at" };
public static string[] A = { "Je", "vais", "ecole", "a", "a" };
public static string Translate(string s)
{
string str = "";
Regex Expression = new Regex(@"[a-zA-Z]+");
MatchCollection M = Expression.Matches(s);
foreach (Match x in M)
str = str + " " + TranslateWord(x.ToString());
return str;
}
public static string TranslateWord(string s)
{
for (int i = 0; i < E.Length; i++)
if (s.ToLower() == E[i].ToLower())
return A[i];
return "Undefined";
}
```
---
here I want to enter the the whole string and the code should translate it with the number, now i know how to do the word (by spliting them and translate) but what about the numbers)
```
static void Main(string[] args)
{
string str = "I go to school at 8";
Console.WriteLine(Translate(str));
}
```
how to continue ?! | 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. Yet others are pretty nice looking.
At this point, today, should I buy or, bite the bullet and build my own? What are the experiences people are having with 1st generation control suites? | 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 without those controls and add them later, that way when you get around to adding those controls you will have a better feel of what controls you need and what controls are a trivial customization of an existing control.
If you need anything that isn't trivial it's better to buy - but only if the component you buy is good, so evaluate carefully.
and read Joel's "In Defense of Not-Invented-Here Syndrome" at <http://www.joelonsoftware.com/articles/fog0000000007.html> | 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 tool like Expression Blend and you don't need any third-party stuff. If you have a good designer on your team (or if you are one yourself), that shouldn't be a problem. And if what you need is some advanced functionality that isn't provided by the standard controls out-of-the box, I'd still recommend trying to customize the standard controls. It's really amazing to what extent you can change the appearance and behavior of a control in WPF by tweaking things like the ControlTemplate, DataTemplate, etc., and/or by subclassing. Besides - now that is just a personal opinion - depending on third-party custom controls generally sucks... | 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 way to check if the pointer is what i am expecting during runtime?
Is there a way i can use typeid to see if a pointer is a type derived from a particular base? | 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 the real type of the thing before its address was cast to `long`, then you can't be sure that it's going to be safe to cast the `long` to whatever type you plan on casting it to.
You'll just have to trust that the sender of the message has sent you a valid value. The best you can do is to take some precautions to reduce the consequences to your own program when it receives a bogus value. | 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 situations like this. | 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())
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
// check if localAddr is in ipProps.UnicastAddresses
}
```
Another option is to use P/Invoke and call [GetBestInterface()](http://msdn.microsoft.com/en-us/library/aa365920(vs.85).aspx) to get the interface index, then again loop over all the network interfaces. As before, you'll have to dig through `GetIPProperties()` to get to the `IPv4InterfaceProperties.Index` property). | 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 (destination IP)` will get you something useable. That's probably not the *best* solution, but it's the only one I can give you right now. | 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 (see [differences between HSL and HSV](http://en.wikipedia.org/wiki/HSL_color_space) and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably [easy to add](https://web.archive.org/web/20120307233434/http://christogreeff.blogspot.com/2008/06/hsl-to-rgb-conversion-for-gdi.html). | 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 hue, out saturation, out value);
// hue = 212.0
// saturation = 0.75
// value = 0.78431372549019607
Color copy = ColorFromHSV(hue, saturation, value);
// copy = {Name=ff3278c8, ARGB=(255, 50, 120, 200)}
// Compare that to the HSL values that the .NET framework provides:
original.GetHue(); // 212.0
original.GetSaturation(); // 0.6
original.GetBrightness(); // 0.490196079
```
The following C# code is what you want. It converts between RGB and HSV using the algorithms described on [Wikipedia](http://en.wikipedia.org/wiki/HSL_and_HSV). The ranges are 0 - 360 for `hue`, and 0 - 1 for `saturation` or `value`.
```
public static void ColorToHSV(Color color, out double hue, out double saturation, out double value)
{
int max = Math.Max(color.R, Math.Max(color.G, color.B));
int min = Math.Min(color.R, Math.Min(color.G, color.B));
hue = color.GetHue();
saturation = (max == 0) ? 0 : 1d - (1d * min / max);
value = max / 255d;
}
public static Color ColorFromHSV(double hue, double saturation, double value)
{
int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;
double f = hue / 60 - Math.Floor(hue / 60);
value = value * 255;
int v = Convert.ToInt32(value);
int p = Convert.ToInt32(value * (1 - saturation));
int q = Convert.ToInt32(value * (1 - f * saturation));
int t = Convert.ToInt32(value * (1 - (1 - f) * saturation));
if (hi == 0)
return Color.FromArgb(255, v, t, p);
else if (hi == 1)
return Color.FromArgb(255, q, v, p);
else if (hi == 2)
return Color.FromArgb(255, p, v, t);
else if (hi == 3)
return Color.FromArgb(255, p, q, v);
else if (hi == 4)
return Color.FromArgb(255, t, p, v);
else
return Color.FromArgb(255, v, p, q);
}
``` | 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 Skeet solved the problem" is a tautology because Jon Skeet himself is the solution to all problems. | 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 numbers quicker than the exception will by checking for digits, e/E, - and . beforehand. So, something like:
```
public boolean isDouble(String value)
{
boolean seenDot = false;
boolean seenExp = false;
boolean justSeenExp = false;
boolean seenDigit = false;
for (int i=0; i < value.length(); i++)
{
char c = value.charAt(i);
if (c >= '0' && c <= '9')
{
seenDigit = true;
continue;
}
if ((c == '-' || c=='+') && (i == 0 || justSeenExp))
{
continue;
}
if (c == '.' && !seenDot)
{
seenDot = true;
continue;
}
justSeenExp = false;
if ((c == 'e' || c == 'E') && !seenExp)
{
seenExp = true;
justSeenExp = true;
continue;
}
return false;
}
if (!seenDigit)
{
return false;
}
try
{
Double.parseDouble(value);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
```
Note that despite taking a couple of tries, this *still* doesn't cover "NaN" or hex values. Whether you want those to pass or not depends on context.
In my experience regular expressions are slower than the hard-coded check above. | 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 test and get some data about how fast each of these methods were. Not so much the correctness, but just how quickly they ran.
You can read about my results [on my blog](http://sacrephill.wordpress.com/2008/12/15/how-to-over-analyse/). (Hint: Jon Skeet FTW). | 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 more attributes than `Name` - I've cropped the code for this example.
---
```
<% foreach (var thing in ViewData.Model)
{ %>
<p><%= thing.Name %></p>
<% }; %>
```
---
```
<% rptThings.DataSource = ViewData.Model;
rptThings.DataBind(); %>
<asp:Repeater ID="rptThings" runat="server">
<ItemTemplate>
<p><%# DataBinder.Eval(Container.DataItem, "Name") %></p>
</ItemTemplate>
</asp:Repeater>
```
--- | `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 prefer `Repeater` for normal situations and `foreach` for more complex ones.
EDIT: I was talking about plain ASP.NET with WebControls. For MVC and even pages that are mostly generated by code, I agree that foreach is more straightforward and cleaner. | `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 seriously lead to real spagetti code with crazy maintenence and support issues. (IMO: DataBinder.Eval == very evil :( :( :( )
The only `asp:xxx` control i use is the `mastpage / content control`(because there are no alternatives to it).
Lastly, doing `foreach` in asp.net mvc is NOT spagetti code, as many people believe. I know i did when i first saw the initial mvc demo's. If anything, it actually makes the UI so much more cleaner than before, imo .. so much more maintainable. IMO, spagetti code is when u have lots of `<% .. %>` doing business logic and ui logic and (gag) db access. Remember, that's what peeps did in the wild west of asp.net *classic* :P
## Summary
Stick with `foreach` and avoid using any webform controls - it's simple, very efficient and very possible to do. | 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 blogposts. BlogEngine.Net seems a lot more stable.
I'm running on a virtualized server hosted by a friend of mine. I have seen no performance issues but that might be because of the massive 15 visitors per day peak load. I've have some trouble where Live Writer posts blog entries twice, but I suspect this is Live Writer's fault.
I really like the extension model and the way you can drag and drop extensions on the design of your blog. There aren't much themes that support this yet but I created my own look and feel by changing the standard theme in about three hours. | 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 modify the core and recompile in order to be able to show comments on the front page of the blog.
I've experienced a bit of weirdness with the caching. Sometimes changes don't show up right away. If it really started to cause problems then there's probably a setting somewhere in the config to work with. But overall caching isn't an issue for me.
On the other hand, the platform runs really fast for me, perhaps because caching is working well.
I'm currently working on implementing my 4th blog/site using BE.Net. I am very happy with it and am looking forward to contributing to the project in the near future. I used to be a big fan of subText, but BE just blow it out of the water. Plus the subText revs aren't very frequent, and Haack is looking to rewrite the whole thing in ASP MVC, which is interesting, but ASP MVC isn't something I want to have to learn just so I can skin and customize my blog instance.
Regards. | 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 maximum value of a signed integer (+2,147,483,647)
INT_MAX;
```
For a complete list of constants and their common values check out: [Wikipedia - limits.h](http://en.wikipedia.org/wiki/Limits.h)
---
## C++ Style
There is a template based C++ method as other commenters have mentioned using:
```
#include <limits>
std::numeric_limits
```
which looks like:
```
std::numeric_limits<int>::max();
```
and it can even do craftier things like determine the number of digits possible or whether the data type is signed or not:
```
// Number of digits for decimal (base 10)
std::numeric_limits<char>::digits10;
// Number of digits for binary
std::numeric_limits<char>::digits;
std::numeric_limits<unsigned int>::is_signed;
``` | 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 off and running. But this is a REST API, which is new to me.
## Details
* [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer) API
* No [WADL](http://en.wikipedia.org/wiki/Web_Application_Description_Language)
* No formal XML schema (XSD or DTD files). There are [example XML request/response pairs](http://developer.yahoo.com/hotjobs/resume_search_user_guide/auth.html).
* No example code provided
## Progress
I looked at question [Rest clients for Java?](https://stackoverflow.com/questions/221442/rest-clients-for-java), but the automated solutions there assume you are providing both the server and the client, with JAXB invoked on POJOs to generate a schema and a REST API.
Using [Jersey](http://jersey.java.net/) (a [JAX-RS](http://jcp.org/en/jsr/detail?id=311) implementation), I have been able to make a manual HTTP request:
```
import com.sun.jersey.api.client.*;
...
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("https://hj.yahooapis.com/v1/HJAuthTokens");
webResource.accept("application/xml");
// body is a hard-coded string, with replacements for the variable bits
String response = webResource.post(String.class, body);
// parse response into a org.w3c.dom.Document
// interface with Document via XPATH, or write my own POJO mappings
```
The response can look like:
```
<?xml version="1.0" encoding="utf-8"?>
<Response>
<ResponseCode>0</ResponseCode>
<ResponseMessage>Login successful</ResponseMessage>
<Token>NTlEMTdFNjk3Qjg4NUJBNDA3MkJFOTI3NzJEMTdDNDU7bG9jYWxob3N0LmVnbGJwLmNvcnAueWFob28uY29tO0pVNWpzRGRhN3VhSS4yQVRqRi4wWE5jTWl0RHVVYzQyX3luYWd1TjIxaGx6U0lhTXN3LS07NjY2MzM1OzIzNDY3NTsxMjA5MDE2OTE5OzZCM1RBMVNudHdLbl9VdFFKMFEydWctLQ==</Token>
</Response>
```
Or, it can look like:
```
<?xml version="1.0" encoding="utf-8"?>
<yahoo:error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" xml:lang="en-US">
<yahoo:description>description</yahoo:description>
<yahoo:detail>
<ErrorCode>errorCode</ErrorCode>
</yahoo:detail>
</yahoo:error>
```
## Questions
* Is there a way to auto-generate [POJOs](http://en.wikipedia.org/wiki/POJO) which can be marshalled/unmarshalled without a formal schema?
* Should I attempt to generate those POJOs by hand, with [JAXB](http://jaxb.java.net/) annotations?
* ***Is there some tool I should be leveraging so I don't have to do all this manually?*** | 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 return. Given how simple the messages are, I wonder if you even need a POJO to wrap them? Why not just have a handler that extracts the data you need using XPath?
---
Edit: blast from the past, but I saw the comment, reread the question, and realized that the first sentence was hard to understand. So, clarification:
One very good habit, if you're going to write a publicly accessible web service, is to make your schema document available at the same URL that you use for the schema's namespace URI -- or better, have that URL be a link to complete documentation (the W3C XSD namespace is itself a good example: <http://www.w3.org/2001/XMLSchema>). | 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 (so attributes need to be annotated).
Alternatively you can of course write schema by hand, generate beans using JAXB, if you like W3C Schema a lot. And just use resulting code, not schema, for data binding.
As to POJO: that can be very simple. Something like:
```
@XmlRootElement("Response")
class Response {
public int responseCode;
public String responseMessage;
public String token; // or perhaps byte[] works for automated base64?
}
```
and similarly for other ones. Or, use getters/setters if you like them and don't mind bit more verbosity. These are just data containers, no need to get too fancy.
And if you must auto-detect type from content, consider using Stax parser to see what the root element, and then bind using JAXB Unmarshaller, handing XMLStreamReader that points to that root element. That way you can pass different object type to bind to.
And finally: sending/receiving requests: plain old HttpURLConnection works ok for GET and POST requests (construct using, say, URL.openConnection()). Jakarta HttpClient has more features if need be. So oftentimes you don't really need a separate REST client -- they may come in handy, but generally build on simple http client pieces. | 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 about how the plugin system works. I haven't completely worked that out and I've only just begun implementing it, but I basically went by [this article](http://divil.co.uk/net/articles/plugins/plugins.asp). | 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 myPlugin = new AlfaPlugin(config);
```
You'll probably need a reference to the System.Configuration assembly. | 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 offered by Java.
The official source of information, including tools downloads, FAQ, and tutorials is [the JavaFX web site](http://www.javafx.com/). | 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 button search command is invoked.
Is this possible in WPF, or how can you pass an enum value as command parameter? | 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 pyerweb import GET, runner
@GET("/")
def index():
return "<strong>This</strong> would be the output HTML for the URL / "
@GET("/view/([0-9]+?)$")
def view_something(id):
return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123"
runner(url = "/", # url would be from a web server, in actual use
output_helper = "html_tidy" # run returned HTML though "HTML tidy"
```
Basically you have a function that returns HTML, and the GET decorator maps this to a URL.
When `runner()` is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.
Now, the problem - outputting headers. Currently for development I've just put a line before the `runner()` call which does `print Content-type:text/html\n` - this is obviously a bit limiting..
My first ideas was to have the functions return a dict, something like..
```
@GET("/")
def index():
return {
"html": "<html><body>...</body></html>",
"headers": {"Location":"http://google.com"}
}
```
I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..
I could check if the returned data is a dict, if so use `returned_data['html']` as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from `return my_html` to `return {'html':my_html}` which isn't very elegant either..
After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:
```
get "/" do
content_type 'text/css', :charset => 'utf-8'
end
```
This seems like it could be nice enough in Python:
```
@GET("/")
def index():
header("location", "http://google.com")
```
To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change `sys.stdout` to a StringIO, so you could do..
```
def index():
print "<html>"
print "<head><title>Something</title></head>"
print "<body>...</body>"
print "</html>
```
..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above `header()` function would write to this.. Something like:
```
def header(name, value):
pyerweb.header_stream.write("%s: %s" % (name, value))
```
Basically, the question is, how would you output headers from this web-framework (mostly in terms of *use*, but to a lesser extent implementation)? | 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 page to a "start\_response" callable object, which wraps your HTML in the proper HTTP response, with the proper headers. | 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","http://google.com")
def index():
return "<html><body>...</body></html>"
```
with complex, maybe calculated headers:
```
@GET("/")
def index():
return {
"html": "<html><body>...</body></html>",
"headers": {"Location":"http://google.com"}
}
```
the @HEADER() decorator would simply change the returned value, so the 'framework' code would stay simple. | 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` variable?
```
public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
``` | 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 generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
```
For a static method, pass `null` as the first argument to `Invoke`. That's nothing to do with generic methods - it's just normal reflection.
As noted, a lot of this is simpler as of C# 4 using `dynamic` - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question. | 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 do a refactoring and rename `GenericMethod`, this code won't notice and will fail at run time. Also, if there is any post-processing of the assembly (for example obfuscating or removing unused methods/classes) this code might break too.
So, if you know the method you are linking to at compile time, and this isn't called millions of times so overhead doesn't matter, I would change this code to be:
```
Action<> GenMethod = GenericMethod<int>; //change int by any base type
//accepted by GenericMethod
MethodInfo method = this.GetType().GetMethod(GenMethod.Method.Name);
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
```
While not very pretty, you have a compile time reference to `GenericMethod` here, and if you refactor, delete or do anything with `GenericMethod`, this code will keep working, or at least break at compile time (if for example you remove `GenericMethod`).
Other way to do the same would be to create a new wrapper class, and create it through `Activator`. I don't know if there is a better way. | 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 compiled to an anonymous delegate.
Edit:
Here's some links for Expressions.
* [System.Linq.Expression.Expression(TDelegate)](http://msdn.microsoft.com/en-us/library/bb335710.aspx) (start here).
* Linq in-memory with delegates (such as System.Func) uses [System.Linq.Enumerable](http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx). Linq to SQL (and anything else) with expressions uses [System.Linq.Queryable](http://msdn.microsoft.com/en-us/library/system.linq.queryable_members.aspx). Check out the parameters on those methods.
* An [Explanation from ScottGu](http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx). In a nutshell, Linq in-memory will produce some anonymous methods to resolve your query. Linq to SQL will produce an expression tree that represents the query and then translate that tree into T-SQL. Linq to Entities will produce an expression tree that represents the query and then translate that tree into platform appropriate SQL. | 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 anonymous methods; the only one which isn't shared by lambda expressions. If you specify an anonymous method without specifying a parameter list *at all* it is compatible with any delegate type returning void and without any `out` parameters. Armed with this knowledge, we should be able to construct two overloads to make the expressions completely unambiguous but very different.
But disaster strikes! At least with C# 3.0, you can't convert a lambda expression with a block body into an expression - nor can you convert a lambda expression with an assignment in the body (even if it is used as the return value). This may change with C# 4.0 and .NET 4.0, which allow more to be expressed in an expression tree. So in other words, with the examples MojoFilter happened to give, the two will *almost* always be converted to the same thing. (More details in a minute.)
We can use the delegate parameters trick if we change the bodies a little bit though:
```
using System;
using System.Linq.Expressions;
public class Test
{
static void Main()
{
int x = 0;
Foo( () => x );
Foo( delegate { return x; } );
}
static void Foo(Func<int, int> action)
{
Console.WriteLine("I suspect the anonymous method...");
}
static void Foo(Expression<Func<int>> func)
{
Console.WriteLine("I suspect the lambda expression...");
}
}
```
But wait! We can differentiate between the two even without using expression trees, if we're cunning enough. The example below uses the overload resolution rules (and the anonymous delegate matching trick)...
```
using System;
using System.Linq.Expressions;
public class Base
{
public void Foo(Action action)
{
Console.WriteLine("I suspect the lambda expression...");
}
}
public class Derived : Base
{
public void Foo(Action<int> action)
{
Console.WriteLine("I suspect the anonymous method...");
}
}
class Test
{
static void Main()
{
Derived d = new Derived();
int x = 0;
d.Foo( () => { x = 0; } );
d.Foo( delegate { x = 0; } );
}
}
```
Ouch. Remember kids, every time you overload a method inherited from a base class, a little kitten starts crying. | 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](http://docs.python.org/library/logging.html#module-logging) module from the std lib.
The interactive interpreter is a wonderful tool for working with python code, and [IPython](http://ipython.org) is a great improvement over the built-in REPL (Read Eval Print Loop).
If you actually want to step through your code, the python debugger is called [pdb](http://docs.python.org/library/pdb.html#module-pdb), which can be called from the command line, or embedded in your code.
If you're used to a fully integrated IDE, I would recommend using Eclipse with pydev, and PyCharm has a great commercial offering, with autocomplete, quick access to docs, and numerous shortcuts, among many other interesting features. | 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 docstrings a code that illustrates a dominant usage and corner cases of the function (class, module). `doctest.testmod()` placed in a `if __name__=="__main__"` section allows to test all docstrings in the module. [doctest](https://docs.python.org/library/doctest.html) can be easily integrated with [unittest](https://docs.python.org/library/unittest.html).
* use `assert` for stuff that can never happen.
* `print()` can solve many debugging problems; [logging](https://docs.python.org/library/logging.html) module is suitable for long-living python processes.
* write tests (not necessarily before your code), run them often (automatically or with one keystroke at most); [nose](http://code.google.com/p/python-nose/) provides extended test discovery and running features for [unittest](https://docs.python.org/library/unittest.html).
* run [pylint](http://www.logilab.org/card/pylint_tutorial) occasionally.
At this point there is a little use for a formal python debugger.
[Winpdb](http://winpdb.org/docs/) is an external multi-platform GPL'ed GUI python debugger if you need one. | 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 them by creating an `ImageData` object of the proper total, concatenated width (with a constant height) and using `setPixel()` for the rest of the pixels. However, the `Palette` used in the `ImageData` constructor I can't figure out.
I also searched for SWT tiling or mosaic functionality to create one image from a group of images, but found nothing.
Any ideas how I can display thousands of small images next to each other efficiently? Please note that once the images are displayed, they are not manipulated, so this is a one-time cost. | 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 Image bigImage = new Image(Display.getCurrent(), combinedWidth, height);
final GC gc = new GC(bigImage);
//loop thru all the images while increasing x as necessary:
int x = 0;
int y = 0;
for (Image curImage : images) {
gc.drawImage(curImage, x, y);
x += curImage.getBounds().width;
}
//very important to dispose GC!!!
gc.dispose();
//now you can use bigImage
``` | 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 viewport in order to make a smooth transition for the user. | 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_condition )
as of timestamp sysdate-1
```
But now I need to check the historical data within a range. Is it possible anyhow, using the cache? | 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 empno, sal, versions_starttime,versions_xid
2 from emp
3 versions between timestamp sysdate-1 and sysdate
4 where empno=7369;
EMPNO SAL VERSIONS_STARTTIME VERSIONS_XID
---------- ---------- --------------------------------------------------------------------------- --
7369 5900 11-DEC-08 16.05.32 0014001300002A74
7369 5800 11-DEC-08 16.03.32 000D002200012EB1
7369 5800
```
Note that how far back you can go is limited by the UNDO\_RETENTION parameter, and will typically be hours rather than days. | 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 may need to set the `UNDO_RETENTION` parameter to a value longer than the time period you are trying to flashback through. | 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? GetNullableInt32(this IDataRecord dr, string fieldname)
{
int ordinal = dr.GetOrdinal(fieldname);
return dr.GetNullableInt32(ordinal);
}
```
and so on, for each type I need to deal with.
I'd like to reimplement these as a generic method, partly to reduce redundancy and partly to learn how to write generic methods in general.
I've written this:
```
public static Nullable<T> GetNullable<T>(this IDataRecord dr, int ordinal)
{
Nullable<T> nullValue = null;
return dr.IsDBNull(ordinal) ? nullValue : (Nullable<T>) dr.GetValue(ordinal);
}
```
which works as long as T is a value type, but if T is a reference type it won't.
This method would need to return either a Nullable type if T is a value type, and default(T) otherwise. How would I implement this behavior? | 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, it will just return the default value for that type. | 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 simplicity):
```
$database = new PDO("mysql:host=host;dbname=mysql_db","username","password");
while (notDone())
{
$add_row = $database->prepare("INSERT INTO table (columns) VALUES (?)");
$add_row->execute(array('values'));
//PROCESSING STUFF THAT TAKES A LONG TIME GOES HERE
}
$database = null;
```
So my problem is that if that if the entire process within that while loop isn't complete then I don't want the row inserted to remain there. I think that somehow I could use commits/rollbacks at the beginning and end of the while loop to do this but don't know how. | 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 ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. "
So you will lose the transaction that was pending when the script timed out.
But really, you ought to redesign this so that it doesn't depend on the scriipt staying alive. | 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 calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.
Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.
At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:
$GPRMC,092204.999,**4250.5589,S,14718.5084,E**,1,12,24.4,**89.6**,M,,,0000\*1F
$GPRMC,093345.679,**4234.7899,N,11344.2567,W**,3,02,24.5,**1000.23**,M,,,0000\*1F
$GPRMC,044584.936,**1276.5539,N,88734.1543,E**,2,04,33.5,**600.323**,M,,,\*00
$GPRMC,199304.973,**3248.7780,N,11355.7832,W**,1,06,02.2,**25722.5**,M,,,\*00
$GPRMC,066487.954,**4572.0089,S,45572.3345,W**,3,09,15.0,**35000.00**,M,,,\*1F
Here is some further explanation of the data:
> "I looks like I'll need five things
> out of every line. And bear in mind
> that any one of these area's may be
> empty. Meaning there will be just two
> commas right next to each other. Such
> as ',,,' There are two fields that may
> be full at any time. Some of them only
> have two or three options that they
> may be but I don't think I should be
> counting on that."
Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in [this pastebin](http://pastebin.com/f5f5cf9ab).
I am still rather new with regular expressions myself, so I am looking for some assistance. | 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, 'N', 11355.7832, 'W', 25722.5)
``` | 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.524508333333333, -80.683445, 7.9)
```
Disclaimer: I am the author of pynmea2 | 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 Singleton had allocated memory on the heap?
In a nutshell, do I have to call a Singelton's destructor or can I rely on it getting cleaned up when the application terminates? | 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 using system resources that won't be correctly cleaned up by merely ending the application.
This is because finalizers run on a sort of 'best effort' basis in most languages. On the other hand there a very very few resources that need this sort of reliability. file handles, memory, etc. all go back to the OS cleanly regardless.
If you are using a singleton that is lazily allocated (i.e. with a triple-check lock idiom) in a language like c++ with real destructors rather than finalizers, then you cannot rely on its destructor being invoked during program shutdown. If you are using a single static instance then the destructor will run after main completes at some point.
Regardless, when the process ends, all memory returns to the operating system. | 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 a file, a named mutex, or something similar) then you do need to consider the appropriate cleanup.
RAII will help you here. If you have a scenario like this:
```
class Tempfile
{
Tempfile() {}; // creates a temporary file
virtual ~Tempfile(); // close AND DELETE the temporary file
};
Tempfile &singleton()
{
static Tempfile t;
return t;
}
```
...then you can be reassured that your temporary file WILL be closed and deleted however your application exits. [However, this is NOT thread-safe, and the order of object deletion may not be what you expect or require.](https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function#246594)
however, if your singleton is implemented like THIS
```
Tempfile &singleton()
{
static Tempfile *t = NULL;
if (t == NULL)
t = new Tempfile();
return *t;
}
```
... then you have a different situation. The memory used by your tempfile will be reclaimed, but the file will NOT be deleted because the destructor will not be invoked. | 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 + "]").each(function () {
//determine whether $(this) is a textbox or label
//do stuff
});
```
I found a solution that doesn't work, it just returns "undefined":
```
$("[id$=" + endOfIdToMatch + "]").each(function () {
alert($(this).tagName);
});
```
What am I missing? | 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()
{
// Nothing
}
public ProcessingContextKey(int dbKey)
{
this.mDbKey = dbKey;
}
public int DbKey
{
get { return this.mDbKey; }
set { this.mDbKey = value; }
}
private int mDbKey;
public override Type GetEntityType()
{
return typeof(IProcessingContextEntity);
}
}
```
When I use reflection to inspect the DbKey property, I get the following (unexpected) result:
```
Type t = typeof(ProcessingContextKey);
PropertyInfo p = t.GetProperty("DbKey");
bool virtualGetter = p.GetGetMethod(true).IsVirtual; // True!
bool virtualSetter = p.GetSetMethod(true).IsVirtual; // False
```
Why does virtualGetter get set to True? I expected false, given that the property is neither **abstract** nor **virtual**.
For completeness - and for the remote possibilty they are relevant, here are the declarations for BusinessEntityKey, IProcessingContextKey, and IBusinessEntityKey:
```
public abstract class BusinessEntityKey : IBusinessEntityKey
{
public abstract Type GetEntityType();
}
public interface IProcessingContextKey : IBusinessEntityKey
{
int DbKey { get; }
}
public interface IBusinessEntityKey
{
Type GetEntityType();
}
```
Thanks in advance for your help.
**Clarification** - why does this matter to me?
We're using NHibernate and traced some issues with lazy loading to properties that were only half overridable - virtual getter but private setter. After fixing these up, we added a Unit test to catch any other places where this could occur:
```
public void RequirePropertiesToBeCompletelyVirtualOrNot()
{
var properties
= typeof(FsisBusinessEntity).Assembly
.GetExportedTypes()
.Where(type => type.IsClass)
.SelectMany(
type =>
type.GetProperties(
BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic))
.Where(property => property.CanRead
&& property.CanWrite)
.Where(property =>
property.GetGetMethod(true).IsVirtual
!= property.GetSetMethod(true).IsVirtual);
Assert.That(
properties.Count(),
Is.EqualTo(0),
properties.Aggregate(
"Found : ",
(m, p) => m + string.Format("{0}.{1}; ",
p.DeclaringType.Name,
p.Name)));
}
```
This unit test was failing on the DbKey property mentioned above, and I didn't understand why. | 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:
> Interfaces can have static or virtual methods, but shall not have instance methods.
Therefore the getter defined by your interface will be marked virtual when implemented in a derived class. | 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 namespace [<http://activemq.apache.org/schema/core]>"**
[Note: I'm able to run the example just fine when I use Maven command "mvn exec:java -PCamelServer" ]
Can someone please help me understand what might be causing this. A potential resolution hint will not hurt either :)
++++++ Error Stack +++++
```
Dec 4, 2008 12:45:01 PM org.apache.camel.util.MainSupport doStart
INFO: Apache Camel 1.5.0 starting
Dec 4, 2008 12:45:01 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1ac3c08: display name [org.springframework.context.support.ClassPathXmlApplicationContext@1ac3c08]; startup date [Thu Dec 04 12:45:01 EST 2008]; root of context hierarchy
Dec 4, 2008 12:45:01 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server-aop.xml]
Dec 4, 2008 12:45:02 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server.xml]
Dec 4, 2008 12:45:03 PM org.apache.camel.util.MainSupport run
SEVERE: Failed: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [camel-server.xml]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server-aop.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://activemq.apache.org/schema/core]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server.xml]
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [camel-server.xml]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server-aop.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://activemq.apache.org/schema/core]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:201)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:147)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:132)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:113)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:80)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:423)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:353)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at org.apache.camel.spring.Main.createDefaultApplicationContext(Main.java:189)
at org.apache.camel.spring.Main.doStart(Main.java:152)
at org.apache.camel.impl.ServiceSupport.start(ServiceSupport.java:47)
at org.apache.camel.util.MainSupport.run(MainSupport.java:121)
at org.apache.camel.util.MainSupport.run(MainSupport.java:310)
at org.apache.camel.spring.Main.main(Main.java:72)
```
++++++ | 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 its likely you are missing some jars; you'll need spring + jaxb + commons-logging + camel-core, camel-spring and camel-jms.
To get an accurate list of the dependencies in maven type
```
mvn dependency:tree
``` | 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 points for converting the extracted string array to an object array. | 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"},
new string[] {"g", "h", "i"} };
var jaggedResult = jaggedArray.SelectMany(s => s).Cast<object>().ToArray();
``` | 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.BlockCopy`](http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx) only works for value type arrays. It does seem odd though...
You can use LINQ to extra a row or column in a single statement, although it will be inefficient (as it'll build up a list internally, then have to convert it to an array - if you do it yourself you can preallocate the array to the right size and copy directly).
Copying a row (`rowNum` is the row to be copied):
```
object[] row = Enumerable.Range(0, rowLength)
.Select(colNum => (object) stringArray[rowNum, colNum])
.ToArray();
```
Copying a column (`colNum` is the column to be copied):
```
object[] column = Enumerable.Range(0, columnLength)
.Select(rowNum => (object) stringArray[rowNum, colNum])
.ToArray();
```
I'm not sure that this is really any better/simpler than a foreach loop though - particularly if you write an `ExtractRow` method and an `ExtractColumn` method and reuse them. | 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).
So I decided to make a table, containg the 'key' and 'value' columns (i.e. 'filename' = '/file', or 'some\_value' = '5'), which contain any possible property of the object, not included in the superclass table. And also made one related table to contain the available 'key' values.
But there is a problem with such architecture - the 'value' column should be of a string data type by default, to be able to contain anything. But I don't think converting to and from strings is a good decision. What is the best way to bypass this limitation? | 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 fallen888 describes: create a "subtype" table for each of your subtypes. This is okay if you have a finite number of subtypes, which sounds like what you have. Then your subtype-specific attributes can have data types, and also a `NOT NULL` constraint if appropriate, which is impossible if you use the EAV design.
One remaining weakness of the subtype-table design is that you can't enforce that a row exists in the subtype table just because the main row in the superclass table says it should. But that's a milder weakness than those introduced by the EAV design.
**edit:** Regarding your additional information about comments-to-any-entity, yes this is a pretty common pattern. Beware of a broken solution called "polymorphic association" which is a technique many people use in this situation. | 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
```
If you don't want your (sub-)table names to be varchar values in the base table, you can also just have a SubType table whose primary key will be in the base table. | 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 of the field for each row.
If the requirement changes later you can alter table and modify the datatype without much trouble. | 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_;
bool a_;
int d_;
bool b_;
std::string f_;
int c_;
.
```
..
};
Or do you simply have them in the order they were added? | 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 epoch format to add that entry in the row field. All the attempts I've made have resulted in generating the current day epoch time stamp. Does anyone have any idea how I can take that date format and convert in the it's equivalent epoch time stamp?
Thanks in advance.
**Additional information:**
I have been trying mktime, and all I get is todays epoch. Apologies, I should have added some code earlier to better explain:
The form id is "date" The database field is "epoch"
Here's what I'm trying (unsuccessfully) when I post the for date:
```
$epochhold = ($_POST['date']);
$epoch = mktime(0,0,0,$epochhold);
```
I understand from a previous post that this would still submit the value as mm/dd/yyyy and not mm, dd, yyyy as mktime expects, however the post didn't offer and resolution on how to do that. I tried a str\_replace to change the "/" to "," and that yeilded the same result - getting today's epoch date regardless of the date entered.
Here's that code example - again this didn't work, but I add it to help illustrate what I've tried
```
$epochhold = ($_POST['date']);
$epochold2 = str_replace('/', ', ', $epochhold)
$epoch = mktime(0,0,0,$epochhold2);
```
Thanks for the previous response as well, I didn't want the quick reply to go unnoticed!
**Thanks everyone!**
Thanks to everyone for the replies - strtotime seems to be working best on the initial tests and may be the way to go as this format is consistent throughout the site. But all the suggestions helped with this a few other things all well so thank you all again! | 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
```
This is how you would do that:
```
window["My"]["Namespace"]["functionName"](arguments); // succeeds
```
In order to make that easier and provide some flexibility, here is a convenience function:
```
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
```
You would call it like so:
```
executeFunctionByName("My.Namespace.functionName", window, arguments);
```
Note, you can pass in whatever context you want, so this would do the same as above:
```
executeFunctionByName("Namespace.functionName", My, arguments);
``` | 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 all browsers except IE.
Second, I have replaced *this* with *context* in the return statement; otherwise, *this* was always pointing to *window* when the target function was being executed.
```
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
``` | 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 testing did not stop at the first function that failed.
My preferred solution used a metaclass to dynamically insert the tests into a unittest.TestCase. Unfortunately, nose does not pick this up because nose statically scans for test cases.
How do I get nose to discover and run such a TestCase? Please refer [here](https://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest#347175) for an example of the TestCase in question. | 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_functions
def test_matrix_functions():
for function in the_functions:
yield check_matrix_function, function
def check_matrix_function(function)
matrix1 = numpy.ones((5,10))
matrix2 = numpy.identity(5)
output = function(matrix1, matrix2)
assert matrix1.shape == output.shape, \
"%s produces output of the wrong shape" % str(function)
``` | 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 looks through the func dict and adds a new method for every method it finds, asserting that the method it found has a docstring. These new synthetic methods are given the names `"test_%d" %i`.
```
import new
from inspect import isfunction, getdoc
class Meta(type):
def __new__(cls, name, bases, dct):
newdct = dct.copy()
for i, (k, v) in enumerate(filter(lambda e: isfunction(e[1]), dct.items())):
def m(self, func):
assert getdoc(func) is not None
fname = 'test_%d' % i
newdct[fname] = new.function(m.func_code, globals(), fname,
(v,), m.func_closure)
return super(Meta, cls).__new__(cls, 'Test_'+name, bases, newdct)
```
Now, let's create a new class that uses this metaclass
```
class Foo(object):
__metaclass__ = Meta
def greeter(self):
"sdf"
print 'Hello World'
def greeter_no_docstring(self):
pass
```
At runtime, `Foo` will actually be named `Test_Foo` and will have `greeter`, `greeter_no_docstring`, `test_1` and `test_2` as its methods. When I run `nosetests` on this file, here's the output:
```
$ nosetests -v test.py
test.Test_Foo.test_0 ... FAIL
test.Test_Foo.test_1 ... ok
======================================================================
FAIL: test.Test_Foo.test_0
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/Users/rmcgibbo/Desktop/test.py", line 10, in m
assert getdoc(func) is not None
AssertionError
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (failures=1)
```
This metaclass isn't really useful as is, but if you instead use the `Meta` not as a proper metaclass, but as more of a functional metaclass (i.e. takes a class as an argument and returns a new class, one that's renamed so that nose will find it), then it *is* useful. I've used this approach to automatically test that the docstrings adhere to the Numpy standard as part of a nose test suite.
Also, I've had a lot of trouble getting proper closure working with new.function, which is why this code uses `m(self, func)` where `func` is made to be a default argument. It would be more natural to use a closure over `value`, but that doesn't seem to work. | 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 my application is concerned), but both of these statements evaluate to false. Is there a way in C# to do this? | *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 StringBuilder();
foreach (char ch in formD)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(ch);
if (uc != UnicodeCategory.NonSpacingMark)
{
sb.Append(ch);
}
}
return sb.ToString().Normalize(NormalizationForm.FormC);
}
```
More details [on MichKap's blog](http://www.siao2.com/2007/05/14/2629747.aspx) ([RIP...](http://www.siao2.com/)).
The principle is that is it turns 'é' into 2 successive chars 'e', acute.
It then iterates through the chars and skips the diacritics.
"héllo" becomes "he<acute>llo", which in turn becomes "hello".
```
Debug.Assert("hello"==RemoveDiacritics("héllo"));
```
---
Note: Here's a more compact .NET4+ friendly version of the same function:
```
static string RemoveDiacritics(string text)
{
return string.Concat(
text.Normalize(NormalizationForm.FormD)
.Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch)!=
UnicodeCategory.NonSpacingMark)
).Normalize(NormalizationForm.FormC);
}
``` | 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 insensitive as well
```
string s1 = "HEllO";
string s2 = "héLLo";
if (String.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) == 0)
{
// both strings are equal
}
``` | 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 IPEndPoint(myHostEntry.AddressList[0], myPort);
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
s.Connect(host);
```
Further, specialized, checks can try IO with timeouts on the socket. | 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 for an older version of PDT. | 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 would be nice - where should I start? Also, if anyone knows of any utilities that would already do this, that would be great as well. | 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 ($files as $file) {
//the quickest way i can think of to check if is a directory
if (ftp_size($conn, $file) == -1) {
//get just the directory name
$dirName = substr($file, strrpos($file, '/') + 1);
if (preg_match($pattern, $dirName)) {
echo $file . ' matched pattern';
} else {
//directory didn't match pattern, recurse
scan_ftp_dir($conn, $file, $pattern);
}
}
}
}
```
Then do something like this
```
$host = 'localhost';
$user = 'user';
$pass = 'pass';
if (false === ($conn = ftp_connect($host))) {
die ('cannot connect');
}
if (!ftp_login($conn, $user, $pass)) die ('cannot authenticate');
scan_ftp_dir($conn, '.', '/^beginswith/');
```
Unfortunately you can only delete an empty directory with `ftp_rmdir()`, but if you look [here](http://theserverpages.com/php/manual/en/function.ftp-rmdir.php) there is a function called `ftp_rmAll()` which you could use to remove whole directory structures which you find.
Also I have only tested on Unix the trick of using the fail status returned from `ftp_size()` as a method of checking if an item returned by `ftp_nlist()` is a directory. | 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 language for this? | 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 password-protected keylock feature. | 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-authorization-with-aspnet-mvc/).
```
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string[] users = Users.Split(',');
if (!httpContext.User.Identity.IsAuthenticated)
return false;
if (users.Length > 0 &&
!users.Contains(httpContext.User.Identity.Name,
StringComparer.OrdinalIgnoreCase))
return false;
return true;
}
}
``` | 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 or greater will help. | 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 )
{
$result = $i;
$val = $array[ $i ];
}
}
return $result;
}
``` | 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_longest_strings($arr));
``` | 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 to specify exactly that behavior.
I am trying to create some debugging code that I want completely removed from the Release configuration, and I was wondering if I could do it just like the Debug class where simply changing the configuration parameters removes the code. | 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 you to release methods for use by other people in their DEBUG configurations (like the Debug class methods in the .NET framework). | 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 for non-Debug builds (the method and any call-sites will be removed from the assembly):
```
[Conditional("DEBUG")]
private void MyDebugMethod()
{
// Your code
}
``` | 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 to, the source uses a static class object implemented using a singleton pattern to achieve the application settings. the information is still stored in a settings file but any calls to retrieve information is done via the class object which preloaded all information into property values.
Any advantages of different approaches? | 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 set all the elements to 30 using a linear index ...
```
//This code does not work
for (int i = 0; i < arr.Length; i++)
{
arr.SetValue(30, i);
}
```
Apparently the SetValue() above does not work with multidimensional arrays.
Here is the best solution that I could come up with...
EDIT: Added some clarifications to the code...
```
static class Program
{
static void Main(string[] args)
{
//Sample input.
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}}
};
int[] arr1 = { 1, 2, 3, 4 };
setElementsTo30(arr2);
setElementsTo30(arr1);
}
//Must be able to process int arrays of arbitrary dimensions and content
private static void setElementsTo30(Array arr)
{
IList<int> cumulativeLength = getCumulativeLengths(arr);
for (int i = 0; i < arr.Length; i++)
{
SetValue(arr, i, 30, cumulativeLength);
}
}
public static void SetValue(this Array arr, int index, object value, IList<int> cumulativeLength)
{
int[] arrayIndex = new int[arr.Rank];
for (int dim = arr.Rank-1; dim >= 0; dim--)
{
arrayIndex[dim] = index / cumulativeLength[dim] % arr.GetLength(dim);
}
arr.SetValue(value, arrayIndex);
}
private static IList<int> getCumulativeLengths(Array arr)
{
List<int> lengths = new List<int>(arr.Rank);
for (int dim = 0; dim < arr.Rank; dim++)
{
int prod = 1;
for (int i = dim + 1; i < arr.Rank; i++)
{
prod *= arr.GetLength(i);
}
lengths.Add(prod);
}
return (IList<int>)lengths;
}
}
```
Is there a way to do the same more efficiently and possibly using something provided by the framework itself (i.e. something which can be used without much hassle.)
Thanks,
SDX2000. | 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 Main(string[] args) {
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}}
};
for (int i = 0; i < arr2.Length; i++) {
arr2.SetValue2(30, i);
}
}
``` | 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 subsequent index is increased. If there are more, this does generalize to an n-tuple simply be multiplying previous values. One could reverse the arithmetic of the indices if one wanted to traverse in a different way. | 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-multiprocessing/))
I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:
```
import processing
from processing.connection import Listener
import threading
import time
import os
import signal
import socket
import errno
# This is actually called by the connection handler.
def closeme():
time.sleep(1)
print 'Closing socket...'
listener.close()
os.kill(processing.currentProcess().getPid(), signal.SIGPIPE)
oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None)
listener = Listener('/tmp/asdf', 'AF_UNIX')
# This is a thread that handles one already accepted connection, left out for brevity
threading.Thread(target=closeme).start()
print 'Accepting...'
try:
listener.accept()
except socket.error, e:
if e.args[0] != errno.EINTR:
raise
# Cleanup here...
print 'Done...'
```
The only other way I've thought about is reaching deep into the connection (listener.\_listener.\_socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.
Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.
**Clarification**:
Thanks all! As usual, ambiguities in my original question are revealed :)
* I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.
* I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy
* The reasons for threads are that:
+ They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.
+ I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.
Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing. | 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..."
c = l.accept()
# ...
```
I am aware that this breaks the law of demeter and introduces some evil monkey-patching, but it seems this would be the most easy-to-port way of accomplishing this. If anyone has a more elegant solution I would be happy to hear it :) | 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.
Anyway, if I do it first I'll post the answer here...
Best Regards,
Jaime. | 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);
searchTimeout = setTimeout(callServerScript, 250);
};
function callServerScript() {
// your code here
}
``` | 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(byteArray);
``` | 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 make a checklist of top offenders when we're troubleshooting IE8 Javascript errors. Please list **one** change to the way IE8 Javascript that would cause a Javascript error. | 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 either opted out of IE8 standards mode, or are running on localhost, or in "Compatibility Mode"
* IE 8 Standards Mode - you have a doctype, and are on the INTRANET (default mode)
Now, if you are rendering in IE5/IE7 mode, then Nothing changes except that there will be a few methods added that *shouldn't* interfere with your page.
However, if like the majority, you are running with a doctype set, and thus in IE8 Standards mode, the following changes have occurred.
```
1.) document.getElementById( id ); //now only returns the CORRECT matches!
```
2.) .getElementsByName( name ); //now only returns the CORRECT matches! nope, not fixed!
```
3.) .getAttribute( name ); //returns the CORRECT value for the given attribute!
4.) .setAttribute( name, value ); //actually SETS the name/value CORRECTLY (no more cAmElCaSe crud)!
5.) CSS Expressions are NO LONGER allowed (deprecated)
6.) Operation Aborted errors will still be thrown (in some cases) however the cases are fewer, and the error won't kill the entire page/DOM
7.) The attributes[] array on elements should (from the RC build onwards) be correct in terms of contents, have a length, etc.
8.) Button elements now submit the contents of the value attribute, NOT the HTML contents of the Button Tag
```
There has also been a bunch of CSS 2.1 fixes, so things that rendered weird before, or needed hacks, should be much better. (see below for details on alpha/transparency - there's been big changes)
See the [IE Blog](http://blogs.msdn.com/ie/) for details.
Also see [Web Bug Track](http://webbugtrack.blogspot.com/2008/01/internet-explorer-8-ie8-facts-and.html) for fine grained details on Bugs, Fixes for IE8 (and all other browsers)
SVG, rounded corners, ECMAScript based Event Listeners, Better Form Element design/events etc. are still missing.
PS If you have specific issues, let us know and we'll help hunt them down for you. ;-)
Updates:
window.resize events are currently broken in IE8 Beta2 and IE8 Partner Release 1 (will not fire) now fixed in RTM build
```
window.open(); in IE8 Partner Release is sometimes failing "claiming" that the target url is not available (quirky, hard to reproduce)
``` | 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 to another JS file that comes before it in the HTML, and then give you all sorts of errors because your out-of-order half file + actual file doesn't work?
That's right, the answer is C ... I kid you not. We used to use the "application/javascript" MIME type to prevent JS file caching in IE6/7, and as a result I wasted an entire day trying to figure out why IE8 was giving some really crazy errors. Luckily I finally figured out what was going on when it told me I had an error on line 650 of a 500 line file (and then when I viewed the file in the debugger I saw the prepended other file).
Moral of the story: if you want IE8 to work DO NOT use "application/javascript" for your JS files' MIME type. | 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. Also this is a super easy question, but i am just too tired to think straight. | 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
/// </summary>
/// <param name="val">The value that needs to be projected</param>
/// <param name="min">The minimum of the interval the value comes from</param>
/// <param name="max">The maximum of the interval the value comes from</param>
/// <param name="intervalTop">The minimum of the interval the value will
/// be projected to</param>
/// <param name="intervalBottom">The maximum of the interval the value will
/// be projected to</param>
/// <returns>Projected value</returns>
public decimal ProjectValueToInterval(decimal val,
decimal min,
decimal max,
decimal intervalBottom,
decimal intervalTop)
{
decimal newMin = Math.Min(0, min);
decimal valueIntervalSize = Math.Abs(max - newMin);
decimal targetIntervalSize = Math.Abs(intervalTop - intervalBottom);
decimal projectionUnit = targetIntervalSize / valueIntervalSize;
return (val * projectionUnit) + Math.Abs((newMin * projectionUnit));
}
```
This method needs to be called for thousands of values.
I was wondering if there is a more efficient way to do this in C#? If yes, what changes do you suggest? | 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-intervalBottom) * (val-min) / (max-min)) + intervalBottom
``` | 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 the complexity.
Having said that - when you call this thousands of times, do any of the values stay constant? For example, are you using the same min and max repeatedly? If so, you could create a class which takes those values in the constructors and precomputes what it can, then has a method taking the rest of the parameters. This will improve things slightly, but I go back to my original point - only worry about this if it's actually causing problems. | 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 edition? | 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 service application), so installing is done manually.
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace SrvControl
{
public partial class Service1 : ServiceBase
{
Timer mytimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (mytimer == null)
mytimer = new Timer(5 * 1000.0);
mytimer.Elapsed += new ElapsedEventHandler(mytimer_Elapsed);
mytimer.Start();
}
void mytimer_Elapsed(object sender, ElapsedEventArgs e)
{
var srv = new ServiceController("MYSERVICE");
AppLog.Log(string.Format("MYSERVICE Status {0}", srv.Status));
}
protected override void OnStop()
{
mytimer.Stop();
}
}
public static class AppLog
{
public static string z = "SrvControl";
static EventLog Logger = null;
public static void Log(string message)
{
if (Logger == null)
{
if (!(EventLog.SourceExists(z)))
EventLog.CreateEventSource(z, "Application");
Logger = new EventLog("Application");
Logger.Source = z;
}
Logger.WriteEntry(message, EventLogEntryType.Information);
}
}
}
``` | 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 second error when I try to instantiate the object:
```
RedBlackTreeOGL<double, std::string> *tree = new RedBlackTreeOGL<double, std::string>; // error 2
```
**Error 1:**
\*\*redblacktreeopengl.hpp(27) : error C2039: '{ctor}' : is not a member of 'RedBlackTree'
with
[
K=double,
D=std::string
]
\*\*
**Error 2:**
main.cpp(50) : see reference to class template instantiation 'RedBlackTreeOGL' being compiled | 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 `IEnumerable<Foo>` is *roughly* equivalent to:
```
using (IEnumerator<Foo> iterator = source.GetEnumerator())
{
Foo element;
while (iterator.MoveNext())
{
element = iterator.Current;
// Body
}
}
```
Note that the `IEnumerator<Foo>` is disposed at the end, however the statement exits. This is important for iterator blocks.
To implement `IEnumerable<T>` or `IEnumerator<T>` yourself, the easiest way is to use an iterator block. Rather than write all the details here, it's probably best to just refer you to [chapter 6 of C# in Depth](http://www.manning.com/skeet), which is a free download. The whole of chapter 6 is on iterators. I have another couple of articles on my C# in Depth site, too:
* [Iterators, iterator blocks and data pipelines](http://csharpindepth.com/Articles/Chapter11/StreamingAndIterators.aspx)
* [Iterator block implementation details](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx)
As a quick example though:
```
public IEnumerable<int> EvenNumbers0To10()
{
for (int i=0; i <= 10; i += 2)
{
yield return i;
}
}
// Later
foreach (int x in EvenNumbers0To10())
{
Console.WriteLine(x); // 0, 2, 4, 6, 8, 10
}
```
To implement `IEnumerable<T>` for a type, you can do something like:
```
public class Foo : IEnumerable<string>
{
public IEnumerator<string> GetEnumerator()
{
yield return "x";
yield return "y";
}
// Explicit interface implementation for nongeneric interface
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator(); // Just return the generic version
}
}
``` | (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 yield keyword (from .Net 2.0 and upwards I believe) together with the IEnumerable interface.
```
class MyContainer : IEnumerable<int>
{
private int max = 0;
public MyContainer(int max)
{
this.max = max;
}
public IEnumerator<int> GetEnumerator()
{
for(int i = 0; i < max; ++i)
yield return i;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
```
And then use it with foreach:
```
MyContainer myContainer = new MyContainer(10);
foreach(int i in myContainer)
Console.WriteLine(i);
``` | 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`.
```
module-one
\src\test\java\com\example\TestCase.java
module-two
\src\test\java\com\example\SubTestCase.java
```
But the build is failing because the test code of "module-one" is not being imported into "module-two", just the main code. | 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 also solve this by putting test scoped artifacts in "main" scope in a separate module of its own and then include this in regular test-scope in other modules. This solution does not work very well in a multi-module build where each module exports some test artifacts, since you basically get 2N modules.
A lot of us actually give up on both of these solution when we realize that the number of classes is fairly limited and there are problems associated with both of these solution. We just put them in an appropriately named package in "main" scope. I just keep forgetting why the two first solutions are a pain. | 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>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
```
Other projects can then reference the test jar by declaring the tests classifier in the dependency.
```
<dependency>
<groupId>name.seller.rich</groupId>
<artifactId>foo</artifactId>
<version>1.0.0</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
``` | 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. not event-based) and I want to use the connections in each frame.
I've read a [comparison between libsigc++ and Boost.Signals](https://web.archive.org/web/20130626010123/http://www.3sinc.com/opensource/boost.bind-vs-sigc2.html). I've also read that Boost.Signals suffers from poor performance. However, I know there are other libraries and I'm still not sure which library should I choose.
Are there any recommendations for a signals/slots library? | 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 nice solution in some cases where boost::signal don't seem to suit).
Anyway, if in your application use the signal each frame, it may be worth to replace the signal system by something more simple, like a container that hold objects/functors that will be called each frame. Signal is more made to allow immediate "events" management than to make a loop cycle dynamic (allowing changing the functions called each frame).
(I have [my own solution](https://github.com/Klaim/gamecore/blob/master/GCore/GC_TaskManager.h) (UPDATE: it's very old and archaic now) that i heavily use in a game and for instance i've no problem with the performance, so maybe something similar could help). | [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 a wonderfully useful
> signal/slot library which can be used
> alongside boost::bind for
> delegate-based event handling such as
> one sees in C#. It is robust,
> featureful, and flexible. It is also,
> I have learned, incredibly,
> terrifyingly slow. For a lot of people
> who use boost::signals this is fine
> because they call events very seldom.
> I was calling several events per frame
> per object, with predictable results.
>
> So I wrote my own. Slightly less
> flexible and featureful. It's
> optimized for how everyone tends to
> actually use events. And event
> invocation is fifteen to eighty times
> faster than boost::signals.
see link | 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 settings with the command
if (ini\_get(register\_globals)) echo "turn it off! :)'; | 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 tests so far show that even this simple operation, done entirely inside the server (Not fetching or pushing any data), could take hours if not days, on a table with many millions of rows.
Is there a better update strategy for such tables?
edit 1: We are still experimenting with no definitive conclusion. What happens if one of my transformations to a new table, involve merging every five lines to one. There is some code that has to run on every transformation. The best performance we could get on this got us at a speed that will take at least a few days to convert a 30M rows table
Will using SQLCLR in this case (doing the transformation with code running inside the server) give me a major speed boost? | 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 from the files.
A 30 million row table took a couple of hours using that method, where an alter table took over 30 hours. | 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://lcweb2.loc.gov/diglib/codetables/45.html> which is worthwhile comparing Eichmann's work to, since he did admit there were a few codes he's unsure of.
If you are interested from a genealogy point of view, the GEDCOM standard release 5.5 has an abbreviated ANSEL character set and some encodings [in its Appendix D](http://homepages.rootsweb.ancestry.com/~pmcbride/gedcom/55gcappd.htm).
---
Update Sept 2017: Long after my original answer of this question, Tamura Jones wrote an excellent series of articles about ANSEL that are worth checking out:
* [GEDCOM ANSEL Table](https://www.tamurajones.net/GEDCOMANSELTable.xhtml) - May 14, 2013
* [LDS ANSEL versus LDS ANSEL](https://www.tamurajones.net/LDSANSELVersusLDSANSEL.xhtml) - May 18, 2013
* [ANSEL Administratively Withdrawn](https://www.tamurajones.net/ANSELAdministrativelyWithdrawn.xhtml) - July 8, 2013 | 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 time interval)
So, my idea was to go to all div's of class "dated", calculate the time diference for each one and replace the correspondent innerHTML.
Is this the best aproach or should I try a different one?
Edit:
One of the problems I've encountered was, where do I keep within the div, the date that will be used to generate the text? | 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 classes.]
```
function adjustDates() {
var i;
var elms = document.getElementsByTagName("div");
for (i = 0; i < elms.length; i++) {
var e = elms[i];
/* update timestamps with date */
if (elementHasClass(e, "dated")) {
var txt = YOUR_DIFFERENCE_CODE(e);
e.replaceChild(document.createTextNode(txt), e.lastChild);
}
}
}
``` | 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(function (i) {
//your code here--this refers to the current element
});
});
```
It comes with many many plugins like the [timer](http://plugins.jquery.com/project/Timer) plugin which helps you to run code periodically. I haven't tested the timer plugin myself but you could set up something like this:
```
$(document).ready(function(){
$.timer(1000, function (timer) {
$(".dated").each(function (i) {
//your code here--this refers to the current element
});
});
});
```
[EDIT] Maybe you can declare the date in a variable at the start of the page. Then the difference code will calculate the current date minus the date stored in the variable. That is, if each element is calculated from the same date? Otherwise use a hidden element to store the date for each one. | 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 subjective, let's try to be as objective as we can and motivate the pros and cons we list.
Use the detail level you prefer for describing your architecture. For your answer to be of any value you'll at least have to describe the major technologies and ideas used in the architecture you describe. And last but not least, *when* should we use your architecture?
I'll start...
---
# Overview of the architecture
We use a 3-tier architecture based on open standards from Sun like Java EE, Java Persistence API, Servlet and Java Server Pages.
* Persistence
* Business
* Presentation
The possible communication flows between the layers are represented by:
```
Persistence <-> Business <-> Presentation
```
Which for example means that the presentation layer never calls or performs persistence operations, it always does it through the business layer. This architecture is meant to fulfill the demands of a high availability web application.
## Persistence
Performs create, read, update and delete ([CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete)) persistence operations. In our case we are using ([Java Persistence API](http://java.sun.com/javaee/technologies/persistence.jsp)) JPA and we currently use [Hibernate](http://www.hibernate.org/) as our persistence provider and use [its EntityManager](http://www.hibernate.org/397.html).
This layer is divided into multiple classes, where each class deals with a certain type of entities (i.e. entities related to a shopping cart might get handled by a single persistence class) and is *used* by one and only one *manager*.
In addition this layer also stores [JPA entities](http://en.wikipedia.org/wiki/Java_Persistence_API#Entities) which are things like `Account`, `ShoppingCart` etc.
## Business
All logic which is tied to the web application functionality is located in this layer. This functionality could be initiating a money transfer for a customer who wants to pay for a product on-line using her/his credit card. It could just as well be creating a new user, deleting a user or calculating the outcome of a battle in a web based game.
This layer is divided into multiple classes and each of these classes is annotated with `@Stateless` to become a [Stateless Session Bean](http://en.wikipedia.org/wiki/Session_Beans) (SLSB). Each SLSB is called a *manager* and for instance a manager could be a class annotated as mentioned called `AccountManager`.
When `AccountManager` needs to perform CRUD operations it makes the appropriate calls to an instance of `AccountManagerPersistence`, which is a class in the persistence layer. A rough sketch of two methods in `AccountManager` could be:
```
...
public void makeExpiredAccountsInactive() {
AccountManagerPersistence amp = new AccountManagerPersistence(...)
// Calls persistence layer
List<Account> expiredAccounts = amp.getAllExpiredAccounts();
for(Account account : expiredAccounts) {
this.makeAccountInactive(account)
}
}
public void makeAccountInactive(Account account) {
AccountManagerPersistence amp = new AccountManagerPersistence(...)
account.deactivate();
amp.storeUpdatedAccount(account); // Calls persistence layer
}
```
We use [container manager transactions](http://java.sun.com/javaee/5/docs/tutorial/doc/bncij.html) so we don't have to do transaction demarcation our self's. What basically happens under the hood is we initiate a transaction when entering the SLSB method and commit it (or rollback it) immediately before exiting the method. It's an example of convention over configuration, but we haven't had a need for anything but the default, Required, yet.
Here is how The Java EE 5 Tutorial from Sun explains the [Required transaction attribute](http://java.sun.com/javaee/5/docs/tutorial/doc/bncij.html) for Enterprise JavaBeans (EJB's):
> If the client is running within a
> transaction and invokes the enterprise
> bean’s method, the method executes
> within the client’s transaction. If
> the client is not associated with a
> transaction, the container starts a
> new transaction before running the
> method.
>
> The Required attribute is the implicit
> transaction attribute for all
> enterprise bean methods running with
> container-managed transaction
> demarcation. You typically do not set
> the Required attribute unless you need
> to override another transaction
> attribute. Because transaction
> attributes are declarative, you can
> easily change them later.
## Presentation
Our presentation layer is in charge of... presentation! It's responsible for the user interface and shows information to the user by building HTML pages and receiving user input through GET and POST requests. We are currently using the old [Servlet](http://java.sun.com/products/servlet/)'s + Java Server Pages ([JSP](http://java.sun.com/products/jsp/)) combination.
The layer calls methods in *managers* of the business layer to perform operations requested by the user and to receive information to show in the web page. Sometimes the information received from the business layer are less complex types as `String`'s and `int`egers, and at other times [JPA entities](http://en.wikipedia.org/wiki/Java_Persistence_API#Entities).
# Pros and cons with the architecture
## Pros
* Having everything related to a specific way of doing persistence in this layer only means we can swap from using JPA into something else, without having to re-write anything in the business layer.
* It's easy for us to swap our presentation layer into something else, and it's likely that we will if we find something better.
* Letting the EJB container manage transaction boundaries is nice.
* Using Servlet's + JPA is easy (to begin with) and the technologies are widely used and implemented in lots of servers.
* Using Java EE is supposed to make it easier for us to create a high availability system with [load balancing](http://en.wikipedia.org/wiki/Load_balancing_(computing)) and [fail over](http://en.wikipedia.org/wiki/Failover). Both of which we feel that we must have.
## Cons
* Using JPA you may store often used queries as named queries by using the `@NamedQuery` annotation on the JPA entity class. If you have as much as possible related to persistence in the persistence classes, as in our architecture, this will spread out the locations where you may find queries to include the JPA entities as well. It will be harder to overview persistence operations and thus harder to maintain.
* We have JPA entities as part of our persistence layer. But `Account` and `ShoppingCart`, aren't they really business objects? It is done this way as you have to touch these classes and turn them into entities which JPA knows how to handle.
* The JPA entities, which are also our business objects, are created like Data Transfer Objects ([DTO](http://en.wikipedia.org/wiki/Data_Transfer_Object)'s), also known as Value Objects (VO's). This results in an [anemic domain model](http://en.wikipedia.org/wiki/Anemic_Domain_Model) as the business objects have no logic of their own except accessor methods. All logic is done by our managers in the business layer, which results in a more procedural programming style. It's not good object oriented design, but maybe that's not a problem? (After all object orientation isn't the only programming paradigm which has delivered results.)
* Using EJB and Java EE introduces a bit of complexity. And we can't use purely Tomcat (adding an EJB micro-container isn't *purely* Tomcat).
* There are lots of issues with using Servlet's + JPA. Use Google for more information about these issues.
* As the transactions are closed when exiting the business layer we can't load any information from JPA entities which is configured to be loaded from the database when it's needed (using `fetch=FetchType.LAZY`) from inside the presentation layer. It will trigger an exception. Before returning an entity containing these kinds of fields we have to be sure to call the relevant getter's. Another option is to use Java Persistence Query Language ([JPQL](http://java.sun.com/javaee/5/docs/tutorial/doc/bnbtg.html)) and do a `FETCH JOIN`. However both of these options are a little bit cumbersome. | 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 call's. The Service layer has the most bussines model knowledge, and the DAO's do relatively simple CRUD work.
Some more complicated query stuff is handled by more complicated queries in the backend for performance reasons.
Advantages of using Spring in our case is that we can have country/language dependant instances, which are behind a Spring Proxy class. Based on the user in the session, the correct country/language implementation is used when doing a call.
Transaction management is nearly transparent, rollback on runtime exceptions. We use unchecked exceptions as much as possible. We used to do checked exceptions, but with the introduction of Spring I see the benefits of unchecked exceptions, only handling exceptions when you can. It avoids a lot of boilerplate "catch/rethrow" or "throws" stuff.
Sorry it's shorter than your post, hope you find this interesting... | **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 Layer :
XMLTool(Search On Google Code),JSoup,Google GSon,XStream,JOOX (Search On Google Code)
# Persistence Layer :
CRUD : JPA or SienaProject or QueryDSL /
Complex Queries : JOOQ,QueryDSL | 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 = new PoolFiberFactory(pool);
Fiber fiber = fiberFactory.create();
fiber.start();
//use fiber for normal publishing and subscribing.
``` | 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=MultilangVsNetQuickTourForms>
but they work with compiled resx. I want to use not compiled XML.
I know that programatically i can do it, i create a method (for example, UpdateUI()), and there I assign the new values like this:
this.tsBtn.Text=Class.Texts.tsBtnText;
I would like something i could do from Design Mode or a more optimized way than the current one. Is there any Custom Control out there or Extension? | 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 tool? It sounds like you are spending (have spent?) a lot of time to solve a problem that has already been solved. | 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 cache resource strings from xml files (e.g. fictional MyGlobalResources class.
```
public class LocalizedButton : Button
{
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
this.Text = MyGlobalResources.GetItem(this.Tag.ToString());
}
}
``` | 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 have some idea how big your list will be, this will be a lot more efficient.
I understand that code like this can often be refactored into a list comprehension. If the *for*/*while* loop is very complicated, though, this is unfeasible. Is there an equivalent for us Python programmers? | ## 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):
message= "some unique object %d" % ( i, )
result[i]= message
return result
```
**Results**. (evaluate each function 144 times and average the duration)
```
simple append 0.0102
pre-allocate 0.0098
```
**Conclusion**. It barely matters.
Premature optimization is the root of all evil. | 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 the list by using a generator instead:
```
def my_things():
while foo:
#baz
yield bar
#qux
for thing in my_things():
# do something with thing
```
This way, the list isn't every stored all in memory at all, merely generated as needed. | 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:
```
<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />
```
Then, in your code, use something like:
```
<Image Source="{StaticResource MyImageSource}" />
```
In my case, I found that I had to set the `Image.png` file to have a build action of `Resource` rather than just `Content`. This causes the image to be carried within your compiled assembly. | 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/«YourPath»/*«YourImage.png»*"**
### Example
```
<Image Source="/WPFApplication;component/Images/Start.png" />
```
Benefits:
* Files are not embedded into the assembly.
+ The Resource Manager will raise some memory overflow problems with too many resources (at build time).
* Can be called between assemblies. | 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 get out of whack with the changes. Also, they were only allowed to put a helper classes inside of the main class as the last resort so that everything remained decoupled.
What do you think? Is there any problem using partial classes like this or does it boil down to preference?
For instance, I usually have something like this:
* MainClass.cs
* MainClass.Helper1.cs
* MainClass.Helper2.cs
...
```
// Inside of MainClass.cs I have code like this:
public abstract partial class MainClass
{
// ...
}
// Then in the MainClass.Helper1.cs I have:
partial class MainClass
{
private class Helper1
{
// ...
}
}
``` | 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 are usually different enough from instance methods to warrant separation. | 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 (free) addin [vsCommands](http://mokosh.co.uk/page/VsCommands.aspx) (for Visual Studio 2008) that makes it really easy to group files in the solution explorer (just like designer files) without editing the project file. | 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 well you'll need to pull a list of the products being used in your query. If you were using the AdventureWorks database, your code would look like this:
```
USE AdventureWorks;
GO
DECLARE @columns NVARCHAR(MAX);
SELECT x.ProductName
INTO #products
FROM (SELECT p.[Name] AS ProductName
FROM Purchasing.Vendor AS v
INNER JOIN Purchasing.PurchaseOrderHeader AS poh ON v.VendorID = poh.VendorID
INNER JOIN Purchasing.PurchaseOrderDetail AS pod ON poh.PurchaseOrderID = pod.PurchaseOrderID
INNER JOIN Production.Product AS p ON pod.ProductID = p.ProductID
GROUP BY p.[Name]) AS x;
SELECT @columns = STUFF(
(SELECT ', ' + QUOTENAME(ProductName, '[') AS [text()]
FROM #products FOR XML PATH ('')
), 1, 1, '');
SELECT @columns;
```
Now that you have your columns, you can pull everything that you need pivot on with a dynamic query:
```
DECLARE @sql NVARCHAR(MAX);
SET @sql = 'SELECT CustomerName, ' + @columns + '
FROM (
// your query goes here
) AS source
PIVOT (SUM(order_count) FOR product_name IN (' + @columns + ') AS p';
EXEC sp_executesql @sql
```
Of course, if you need to make sure you get decent values, you may have to duplicate the logic you're using to build @columns and create an @coalesceColumns variable that will hold the code to COALESCE(col\_name, 0) if you need that sort of thing in your query. | 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 transform these strings into a System.Uri? Seems easy enough to parse but I’m trying to avoid building a new wheel today. | 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])",
m => ((char) int.Parse(m.Groups[1].Value, NumberStyles.HexNumber)).ToString());
```
But notice that this assumes that the encoding is Latin-1 rather than UTF-8. The input you provided is inconclusive in that respect. If you need UTF-8 to work, you need a slightly longer route; you'll have to convert the string to bytes and replace the escape sequences with the relevant bytes in the process (probably needs a while loop), and then use `Encoding.UTF8.GetString()` on the resulting byte array. | 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 want to check the user agent and compare to a list of known mobile browsers. | 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/mobile_ids.html>
The list is not complete and will never be, given the rate new mobiles appear on the market, but what I did back when I did it is to store all received user agents in a database, and then look for them to classify them as mobile and which brand/model.
What you can't rely on though is JavaScript, it's better done in server code (not all mobile browsers execute JavaScript).
There is a related question here on SO but I couldn't find it. | 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 seems to be much better. | 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 better than Word itself. At said company we (earlier) used to remotecontrol Word with frequent problems because Word (on saving a document) insisted on displaying a warning dialog from time to time. Bad idea on a server deep down in some datacenter with nobody close to it.
As this was a Java shop, the very good OpenOffice support for Java came in handy. In fact, they even used to bundle the commercial version StarOffice and had some very good contacts at and help from Sun.
Disclaimer: As andHapp and alepuzio said, POI is very good in Excel support and I'm using it with big success. Last time I've seen the doc support, I didn't dare using it in production (for customers). I haven't looked at doc support for at least two years. | 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 = False;
switch ( aCommand )
{
default:
break;
}
if ( !commandHandled )
{
if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit )
{
Exit();
}
}
}
``` | 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 ruby on rails features, but in a Java desktop environment. | 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:
<https://binding.dev.java.net/>
I know less about the SwingLabs databinding project, but it looks worth looking into:
<https://databinding.dev.java.net/> | 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",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.